target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
docs/src/pages/demos/tabs/DisabledTabs.js
AndriusBil/material-ui
/* eslint-disable flowtype/require-valid-file-annotation */ /* eslint-disable react/no-multi-comp */ import React from 'react'; import Paper from 'material-ui/Paper'; import Tabs, { Tab } from 'material-ui/Tabs'; class DisabledTabs extends React.Component { state = { value: 0, }; handleChange = (event, value) => { this.setState({ value }); }; render() { return ( <Paper> <Tabs value={this.state.value} indicatorColor="primary" textColor="primary" onChange={this.handleChange} > <Tab label="Active" /> <Tab label="Disabled" disabled /> <Tab label="Active" /> </Tabs> </Paper> ); } } export default DisabledTabs;
app/javascript/mastodon/features/ui/components/column_loading.js
kazh98/social.arnip.org
import React from 'react'; import PropTypes from 'prop-types'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class ColumnLoading extends ImmutablePureComponent { static propTypes = { title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), icon: PropTypes.string, }; static defaultProps = { title: '', icon: '', }; render() { let { title, icon } = this.props; return ( <Column> <ColumnHeader icon={icon} title={title} multiColumn={false} focusable={false} placeholder /> <div className='scrollable' /> </Column> ); } }
src/svg-icons/hardware/speaker-group.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSpeakerGroup = (props) => ( <SvgIcon {...props}> <path d="M18.2 1H9.8C8.81 1 8 1.81 8 2.8v14.4c0 .99.81 1.79 1.8 1.79l8.4.01c.99 0 1.8-.81 1.8-1.8V2.8c0-.99-.81-1.8-1.8-1.8zM14 3c1.1 0 2 .89 2 2s-.9 2-2 2-2-.89-2-2 .9-2 2-2zm0 13.5c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/><circle cx="14" cy="12.5" r="2.5"/><path d="M6 5H4v16c0 1.1.89 2 2 2h10v-2H6V5z"/> </SvgIcon> ); HardwareSpeakerGroup = pure(HardwareSpeakerGroup); HardwareSpeakerGroup.displayName = 'HardwareSpeakerGroup'; HardwareSpeakerGroup.muiName = 'SvgIcon'; export default HardwareSpeakerGroup;
ajax/libs/redux-form/3.1.5/redux-form.min.js
sreym/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.ReduxForm=e(require("react")):t.ReduxForm=e(t.React)}(this,function(t){return function(t){function e(n){if(r[n])return r[n].exports;var u=r[n]={exports:{},id:n,loaded:!1};return t[n].call(u.exports,u,u.exports,e),u.loaded=!0,u.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(5),o=n(u),i=r(55),a=r(26),s=n(a),f=s.default(!1,o.default,i.connect),c=f.actionTypes,l=f.blur,d=f.change,p=f.changeWithKey,v=f.destroy,y=f.focus,h=f.reducer,m=f.reduxForm,g=f.initialize,b=f.initializeWithKey,_=f.propTypes,O=f.reset,x=f.startAsyncValidation,A=f.startSubmit,S=f.stopAsyncValidation,T=f.stopSubmit,j=f.touch,R=f.touchWithKey,M=f.untouch,P=f.untouchWithKey;e.actionTypes=c,e.blur=l,e.change=d,e.changeWithKey=p,e.destroy=v,e.focus=y,e.reducer=h,e.reduxForm=m,e.initialize=g,e.initializeWithKey=b,e.propTypes=_,e.reset=O,e.startAsyncValidation=x,e.startSubmit=A,e.stopAsyncValidation=S,e.stopSubmit=T,e.touch=j,e.touchWithKey=R,e.untouch=M,e.untouchWithKey=P},function(t,e){"use strict";function r(t){return Array.isArray(t)?t.reduce(function(t,e){return t&&r(e)},!0):t&&"object"==typeof t?Object.keys(t).reduce(function(e,n){return e&&r(t[n])},!0):!t}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r="redux-form/ADD_ARRAY_VALUE";e.ADD_ARRAY_VALUE=r;var n="redux-form/BLUR";e.BLUR=n;var u="redux-form/CHANGE";e.CHANGE=u;var o="redux-form/DESTROY";e.DESTROY=o;var i="redux-form/FOCUS";e.FOCUS=i;var a="redux-form/INITIALIZE";e.INITIALIZE=a;var s="redux-form/REMOVE_ARRAY_VALUE";e.REMOVE_ARRAY_VALUE=s;var f="redux-form/RESET";e.RESET=f;var c="redux-form/START_ASYNC_VALIDATION";e.START_ASYNC_VALIDATION=c;var l="redux-form/START_SUBMIT";e.START_SUBMIT=l;var d="redux-form/STOP_ASYNC_VALIDATION";e.STOP_ASYNC_VALIDATION=d;var p="redux-form/STOP_SUBMIT";e.STOP_SUBMIT=p;var v="redux-form/SUBMIT_FAILED";e.SUBMIT_FAILED=v;var y="redux-form/TOUCH";e.TOUCH=y;var h="redux-form/UNTOUCH";e.UNTOUCH=h},function(t,e){"use strict";function r(t,e){return t?Object.keys(t).reduce(function(r,u){var o;return n({},r,(o={},o[u]=e(t[u],u),o))},{}):t}e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=r,t.exports=e.default},function(t,e){function r(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}t.exports=r},function(e,r){e.exports=t},function(t,e,r){"use strict";function n(t,e,r){return{type:g.ADD_ARRAY_VALUE,path:t,value:e,index:r}}function u(t,e){return{type:g.BLUR,field:t,value:e}}function o(t,e){return{type:g.CHANGE,field:t,value:e}}function i(){return{type:g.DESTROY}}function a(t){return{type:g.FOCUS,field:t}}function s(t){return{type:g.INITIALIZE,data:t}}function f(t,e){return{type:g.REMOVE_ARRAY_VALUE,path:t,index:e}}function c(){return{type:g.RESET}}function l(){return{type:g.START_ASYNC_VALIDATION}}function d(){return{type:g.START_SUBMIT}}function p(t){return{type:g.STOP_ASYNC_VALIDATION,errors:t}}function v(t){return{type:g.STOP_SUBMIT,errors:t}}function y(){return{type:g.SUBMIT_FAILED}}function h(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:g.TOUCH,fields:e}}function m(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:g.UNTOUCH,fields:e}}e.__esModule=!0,e.addArrayValue=n,e.blur=u,e.change=o,e.destroy=i,e.focus=a,e.initialize=s,e.removeArrayValue=f,e.reset=c,e.startAsyncValidation=l,e.startSubmit=d,e.stopAsyncValidation=p,e.stopSubmit=v,e.submitFailed=y,e.touch=h,e.untouch=m;var g=r(2)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){return"function"==typeof t?function(){return o({},t.apply(void 0,arguments),e)}:"object"==typeof t?a.default(t,function(t){return u(t,e)}):t}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=u;var i=r(3),a=n(i);t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r="value";e.dataKey=r;var n=function(t,e){return function(t){t.dataTransfer.setData(r,e())}};e.default=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(10),o=n(u),i=function(t){var e=[];if(t)for(var r=0;r<t.length;r++){var n=t[r];n.selected&&e.push(n.value)}return e},a=function(t,e){if(o.default(t)){if(!e&&t.nativeEvent&&void 0!==t.nativeEvent.text)return t.nativeEvent.text;if(e&&void 0!==t.nativeEvent)return t.nativeEvent.text;var r=t.target,n=r.type,u=r.value,a=r.checked,s=r.files,f=t.dataTransfer;return"checkbox"===n?a:"file"===n?s||f&&f.files:"select-multiple"===n?i(t.target.options):u}return t&&"object"==typeof t&&void 0!==t.value?t.value:t};e.default=a,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function(t){return!!(t&&t.stopPropagation&&t.preventDefault)};e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(10),o=n(u),i=function(t){var e=o.default(t);return e&&t.preventDefault(),e};e.default=i,t.exports=e.default},function(t,e){"use strict";function r(t){return t.displayName||t.name||"Component"}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function u(t,e,r){var n=t.indexOf("."),o=t.indexOf("["),i=t.indexOf("]");if(o>0&&i!==o+1)throw new Error("found [ not followed by ]");if(o>0&&(0>n||n>o))!function(){var n=t.substring(0,o),a=t.substring(i+1);"."===a[0]&&(a=a.substring(1));var s=e&&e[n]||[];a?(r[n]||(r[n]=[]),s.forEach(function(t,e){r[n][e]||(r[n][e]={}),u(a,t,r[n][e])})):r[n]=s.map(function(t){return t.value})}();else if(n>0){var a=t.substring(0,n),s=t.substring(n+1);r[a]||(r[a]={}),u(s,e&&e[a]||{},r[a])}else r[t]=e[t]&&e[t].value},n=function(t,e){return t.reduce(function(t,n){return r(n,e,t),t},{})};e.default=n,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function(t,e){var r=!0;t:for(;r;){var n=t,u=e;if(r=!1,!n||!u)return u;var o=n.indexOf(".");if(0!==o){var i=n.indexOf("["),a=n.indexOf("]");if(o>=0&&(0>i||i>o))t=n.substring(o+1),e=u[n.substring(0,o)],r=!0,o=i=a=void 0;else{if(!(i>=0&&(0>o||o>i)))return u[n];if(0>a)throw new Error("found [ but no ]");var s=n.substring(0,i),f=n.substring(i+1,a);if(0===i){t=n.substring(a+1),e=u[f],r=!0,o=i=a=s=f=void 0;continue t}if(!u[s])return void 0;t=n.substring(a+1),e=u[s][f],r=!0,o=i=a=s=f=void 0}}else t=n.substring(1),e=u,r=!0,o=void 0}};e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(){var t,e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=r.form,o=r.key,i=u(r,["form","key"]);if(!n)return e;if(o){var a,c;if(r.type===f.DESTROY){var l;return s({},e,(l={},l[n]=e[n]&&Object.keys(e[n]).reduce(function(t,r){var u;return r===o?t:s({},t,(u={},u[r]=e[n][r],u))},{}),l))}return s({},e,(c={},c[n]=s({},e[n],(a={},a[o]=S((e[n]||{})[o],i),a)),c))}return r.type===f.DESTROY?Object.keys(e).reduce(function(t,r){var u;return r===n?t:s({},t,(u={},u[r]=e[r],u))},{}):s({},e,(t={},t[n]=S(e[n],i),t))}function i(t){return t.plugin=function(t){var e=this;return i(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],u=e(r,n);return s({},u,l.default(t,function(t,e){return t(u[e]||x,n)}))})},t.normalize=function(t){var e=this;return i(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],u=e(r,n);return s({},u,l.default(t,function(t,e){var n=m.default(s({},x,r[e])),o=s({},x,u[e]);return s({},o,l.default(t,function(t,u){return s({},o[u],{value:t(o[u]?o[u].value:void 0,r[e]&&r[e][u]?r[e][u].value:void 0,m.default(o),n)})}))}))})},t}e.__esModule=!0;var a,s=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},f=r(2),c=r(3),l=n(c),d=r(14),p=n(d),v=r(16),y=n(v),h=r(35),m=n(h),g=r(37),b=n(g),_=r(42),O=n(_),x={_active:void 0,_asyncValidating:!1,_error:void 0,_submitting:!1,_submitFailed:!1};e.initialState=x;var A=(a={},a[f.ADD_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,u=e.value,o=p.default(r,t),i=s({},t),a=o?[].concat(o):[],f={value:u};return void 0===n?a.push(f):a.splice(n,0,f),y.default(r,a,i)},a[f.BLUR]=function(t,e){var r=e.field,n=e.value,o=e.touch,i=(t._active,u(t,["_active"]));return y.default(r,function(t){var e=s({},t);return void 0!==n&&(e.value=n),o&&(e.touched=!0),e},i)},a[f.CHANGE]=function(t,e){var r=e.field,n=e.value,o=e.touch;return y.default(r,function(t){var e=s({},t,{value:n}),r=(e.asyncError,e.submitError,u(e,["asyncError","submitError"]));return o&&(r.touched=!0),r},t)},a[f.DESTROY]=function(){return void 0},a[f.FOCUS]=function(t,e){var r=e.field,n=y.default(r+".visited",!0,t);return n._active=r,n},a[f.INITIALIZE]=function(t,e){var r=e.data;return s({},b.default(r),{_asyncValidating:!1,_active:void 0,_error:void 0,_submitting:!1,_submitFailed:!1})},a[f.REMOVE_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,u=p.default(r,t),o=s({},t),i=u?[].concat(u):[];return void 0===n?i.pop():isNaN(n)?delete i[n]:i.splice(n,1),y.default(r,i,o)},a[f.RESET]=function(t){return s({},O.default(t),{_active:void 0,_asyncValidating:!1,_error:void 0,_submitting:!1,_submitFailed:!1})},a[f.START_ASYNC_VALIDATION]=function(t){return s({},t,{_asyncValidating:!0})},a[f.START_SUBMIT]=function(t){return s({},t,{_submitting:!0})},a[f.STOP_ASYNC_VALIDATION]=function(t,e){var r=e.errors;return s({},l.default(t,function(t){return t&&t.asyncError?s({},t,{asyncError:void 0}):t}),l.default(r,function(e,r){return s({},t[r],{asyncError:e})}),{_asyncValidating:!1,_error:r&&r._error})},a[f.STOP_SUBMIT]=function(t,e){var r=e.errors;return s({},t,r?l.default(r,function(e,r){return s({},t[r],{submitError:e})}):{},{_error:r&&r._error,_submitting:!1,_submitFailed:!(!r||!Object.keys(r).length)})},a[f.SUBMIT_FAILED]=function(t){return s({},t,{_submitFailed:!0})},a[f.TOUCH]=function(t,e){var r=e.fields;return s({},t,r.reduce(function(e,r){return e[r]=s({},t[r],{touched:!0}),e},{}))},a[f.UNTOUCH]=function(t,e){var r=e.fields;return s({},t,r.reduce(function(e,r){return e[r]=s({},t[r],{touched:!1}),e},{}))},a),S=function(){var t=arguments.length<=0||void 0===arguments[0]?x:arguments[0],e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=A[e.type];return r?r(t,e):t};e.default=i(o)},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function u(t,e,n){for(var o=!0;o;){var i,a=t,s=e,f=n;o=!1;var c=a.indexOf(".");if(0!==c){var l=a.indexOf("["),d=a.indexOf("]");if(c>=0&&(0>l||l>c)){var p,v=a.substring(0,c);return r({},f,(p={},p[v]=u(a.substring(c+1),s,f[v]||{}),p))}if(l>=0&&(0>c||c>l)){var y;if(0>d)throw new Error("found [ but no ]");var v=a.substring(0,l),h=a.substring(l+1,d),m=f[v]||[],g=a.substring(d+1);if(g.length){var b,_=m[h]||{},O=[].concat(m);return O[h]=u(g,s,_),r({},f||{},(b={},b[v]=O,b))}if(0===l){var x=[].concat(f);return x[h]=u(g,s,f[h]),x}var A=[].concat(f[v]||[]);return A[h]="function"==typeof s?s(A[h]):s,r({},f||{},(y={},y[v]=A,y))}return r({},f,(i={},i[a]="function"==typeof s?s(f[a]):s,i))}t=a.substring(1),e=s,n=f,o=!0,i=c=void 0}};e.default=n,t.exports=e.default},function(t,e,r){function n(t){return null===t||void 0===t}function u(t){return t&&"object"==typeof t&&"number"==typeof t.length?"function"!=typeof t.copy||"function"!=typeof t.slice?!1:t.length>0&&"number"!=typeof t[0]?!1:!0:!1}function o(t,e,r){var o,c;if(n(t)||n(e))return!1;if(t.prototype!==e.prototype)return!1;if(s(t))return s(e)?(t=i.call(t),e=i.call(e),f(t,e,r)):!1;if(u(t)){if(!u(e))return!1;if(t.length!==e.length)return!1;for(o=0;o<t.length;o++)if(t[o]!==e[o])return!1;return!0}try{var l=a(t),d=a(e)}catch(p){return!1}if(l.length!=d.length)return!1;for(l.sort(),d.sort(),o=l.length-1;o>=0;o--)if(l[o]!=d[o])return!1;for(o=l.length-1;o>=0;o--)if(c=l[o],!f(t[c],e[c],r))return!1;return typeof t==typeof e}var i=Array.prototype.slice,a=r(48),s=r(47),f=t.exports=function(t,e,r){return r||(r={}),t===e?!0:t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?r.strict?t===e:t==e:o(t,e,r)}},function(t,e){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0};t.exports=function(t,e){for(var u=Object.getOwnPropertyNames(e),o=0;o<u.length;++o)r[u[o]]||n[u[o]]||(t[u[o]]=e[u[o]]);return t}},function(t,e){"use strict";function r(t){return t.shape({subscribe:t.func.isRequired,dispatch:t.func.isRequired,getState:t.func.isRequired})}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){function r(){return f}function n(t){c.push(t);var e=!0;return function(){if(e){e=!1;var r=c.indexOf(t);c.splice(r,1)}}}function u(t){if(!i.default(t))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof t.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(l)throw new Error("Reducers may not dispatch actions.");try{l=!0,f=s(f,t)}finally{l=!1}return c.slice().forEach(function(t){return t()}),t}function o(t){s=t,u({type:a.INIT})}if("function"!=typeof t)throw new Error("Expected the reducer to be a function.");var s=t,f=e,c=[],l=!1;return u({type:a.INIT}),{dispatch:u,subscribe:n,getState:r,replaceReducer:o}}e.__esModule=!0,e.default=u;var o=r(23),i=n(o),a={INIT:"@@redux/INIT"};e.ActionTypes=a},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(20),o=n(u),i=r(61),a=n(i),s=r(60),f=n(s),c=r(59),l=n(c),d=r(22),p=n(d);e.createStore=o.default,e.combineReducers=a.default,e.bindActionCreators=f.default,e.applyMiddleware=l.default,e.compose=p.default},function(t,e){"use strict";function r(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(t){return e.reduceRight(function(t,e){return e(t)},t)}}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e){"use strict";function r(t){if(!t||"object"!=typeof t)return!1;var e="function"==typeof t.constructor?Object.getPrototypeOf(t):Object.prototype;if(null===e)return!0;var r=e.constructor;return"function"==typeof r&&r instanceof r&&n(r)===n(Object)}e.__esModule=!0,e.default=r;var n=function(t){return Function.prototype.toString.call(t)};t.exports=e.default},function(t,e){"use strict";function r(t,e){return Object.keys(t).reduce(function(r,n){return r[n]=e(t[n],n),r},{})}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(4),o=n(u),i=r(1),a=n(i),s=function(t,e,r){e();var n=t();if(!o.default(n))throw new Error("asyncValidate function passed to reduxForm must return a promise");var u=function(t){return function(e){if(!a.default(e))return r(e),Promise.reject();if(t)throw r(),new Error("Asynchronous validation promise was rejected without errors.");return r(),Promise.resolve()}};return n.then(u(!1),u(!0))};e.default=s,t.exports=e.default},function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function u(t){return t&&t.__esModule?t:{"default":t}}function o(t,e,r){return{actionTypes:g,blur:x,change:A,changeWithKey:S,destroy:T,focus:j,reducer:s.default,initialize:R,initializeWithKey:M,propTypes:_.default,reduxForm:c.default(t,e,r),reset:P,startAsyncValidation:E,startSubmit:w,stopAsyncValidation:V,stopSubmit:I,submitFailed:C,touch:F,touchWithKey:N,untouch:U,untouchWithKey:q}}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=o;var a=r(15),s=u(a),f=r(28),c=u(f),l=r(3),d=u(l),p=r(7),v=u(p),y=r(6),h=n(y),m=r(2),g=n(m),b=r(39),_=u(b),O=i({},d.default(i({},h,{changeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return v.default(h.change,{key:t}).apply(void 0,r)},initializeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return v.default(h.initialize,{key:t}).apply(void 0,r)},reset:function(t){return v.default(h.reset,{key:t})()},touchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return v.default(h.touch,{key:t}).apply(void 0,r)},untouchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return v.default(h.untouch,{key:t}).apply(void 0,r)},destroy:function(t){return v.default(h.destroy,{key:t})()}}),function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),u=1;r>u;u++)n[u-1]=arguments[u];return v.default(t,{form:e}).apply(void 0,n)}})),x=O.blur,A=O.change,S=O.changeWithKey,T=O.destroy,j=O.focus,R=O.initialize,M=O.initializeWithKey,P=O.reset,E=O.startAsyncValidation,w=O.startSubmit,V=O.stopAsyncValidation,I=O.stopSubmit,C=O.submitFailed,F=O.touch,N=O.touchWithKey,U=O.untouch,q=O.untouchWithKey;t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var s=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},f=r(6),c=u(f),l=r(12),d=n(l),p=r(15),v=r(17),y=n(v),h=r(7),m=n(h),g=r(13),b=n(g),_=r(1),O=n(_),x=r(41),A=n(x),S=r(36),T=n(S),j=r(25),R=n(j),M=r(34),P=n(M),E=r(11),w=n(E),V=r(45),I=n(V),C=r(46),F=n(C),N=function(t,e,r,n,u,f,l){var v=r.Component,h=r.PropTypes;return function(g,_,x,S){var j=function(n){function f(t){i(this,f),n.call(this,t),this.asyncValidate=this.asyncValidate.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.fields=A.default(t,{},this.asyncValidate,e)}return a(f,n),f.prototype.componentWillMount=function(){var t=this.props,e=t.initialize,r=t.initialValues;r&&e(r)},f.prototype.componentWillReceiveProps=function(t){y.default(this.props.fields,t.fields)&&y.default(this.props.form,t.form)||(this.fields=A.default(t,this.fields,this.asyncValidate,e)),y.default(this.props.initialValues,t.initialValues)||this.props.initialize(t.initialValues)},f.prototype.componentWillUnmount=function(){t.destroyOnUnmount&&this.props.destroy()},f.prototype.asyncValidate=function c(t,e){var r=this,n=this.props,c=n.asyncValidate,u=n.dispatch,o=n.fields,i=n.form,a=n.startAsyncValidation,s=n.stopAsyncValidation,f=n.validate;if(c){var l=function(){var n=b.default(o,i);t&&(n[t]=e);var l=f(n,r.props);return!t||O.default(l[t])?{v:R.default(function(){return c(n,u,r.props)},a,s)}:void 0}();if("object"==typeof l)return l.v}},f.prototype.handleSubmit=function(t){var e=this,r=this.props,n=r.onSubmit,u=r.fields,o=r.form,i=function(t){if(!t||"function"!=typeof t)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return t},a=b.default(u,o);return!t||w.default(t)?T.default(i(n),a,this.props,this.asyncValidate):P.default(function(r){w.default(r),T.default(i(t),a,e.props,e.asyncValidate)})},f.prototype.render=function(){var t,e=this,n=this.fields,i=this.props,a=(i.addArrayValue,i.asyncBlurFields,i.blur,i.change,i.destroy),f=(i.focus,i.fields),c=i.form,l=(i.initialValues,i.initialize),d=(i.onSubmit,i.propNamespace),p=i.reset,v=(i.removeArrayValue,i.returnRejectedSubmitPromise,i.startAsyncValidation,i.startSubmit,i.stopAsyncValidation,i.stopSubmit,i.submitFailed,i.touch),y=i.untouch,h=(i.validate,o(i,["addArrayValue","asyncBlurFields","blur","change","destroy","focus","fields","form","initialValues","initialize","onSubmit","propNamespace","reset","removeArrayValue","returnRejectedSubmitPromise","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitFailed","touch","untouch","validate"])),m=n._meta,g=m.allPristine,b=m.allValid,_=m.errors,O=m.formError,A=m.values,S={active:c._active,asyncValidating:c._asyncValidating,dirty:!g,error:O,errors:_,fields:n,formKey:x,invalid:!b,pristine:g,submitting:c._submitting,submitFailed:c._submitFailed,valid:b,values:A,asyncValidate:P.default(function(){return e.asyncValidate()}),destroyForm:P.default(a),handleSubmit:this.handleSubmit,initializeForm:P.default(l),resetForm:P.default(p),touch:P.default(function(){return v.apply(void 0,arguments)}),touchAll:P.default(function(){return v.apply(void 0,f)}),untouch:P.default(function(){return y.apply(void 0,arguments)}),untouchAll:P.default(function(){return y.apply(void 0,f)})},T=d?(t={},t[d]=S,t):S;return r.createElement(u,s({},h,T))},f}(v);j.displayName="ReduxForm("+d.default(u)+")",j.WrappedComponent=u,j.propTypes={asyncBlurFields:h.arrayOf(h.string),asyncValidate:h.func,dispatch:h.func.isRequired,fields:h.arrayOf(h.string).isRequired,form:h.object,initialValues:h.any,onSubmit:h.func,propNamespace:h.string,readonly:h.bool,returnRejectedSubmitPromise:h.bool,validate:h.func,addArrayValue:h.func.isRequired,blur:h.func.isRequired,change:h.func.isRequired,destroy:h.func.isRequired,focus:h.func.isRequired,initialize:h.func.isRequired,removeArrayValue:h.func.isRequired,reset:h.func.isRequired,startAsyncValidation:h.func.isRequired,startSubmit:h.func.isRequired,stopAsyncValidation:h.func.isRequired,stopSubmit:h.func.isRequired,submitFailed:h.func.isRequired,touch:h.func.isRequired,untouch:h.func.isRequired},j.defaultProps={asyncBlurFields:[],form:p.initialState,readonly:!1,returnRejectedSubmitPromise:!1,validate:function(){return{}}};var M=s({},c,{blur:m.default(c.blur,{touch:!!t.touchOnBlur}),change:m.default(c.change,{touch:!!t.touchOnChange})}),E=void 0!==x&&null!==x?n(F.default(f,function(t){var e=S(t,g);if(!e)throw new Error('You need to mount the redux-form reducer at "'+g+'"');return e&&e[_]&&e[_][x]}),I.default(l,m.default(M,{form:_,key:x}))):n(F.default(f,function(t){var e=S(t,g);if(!e)throw new Error('You need to mount the redux-form reducer at "'+g+'"');return e&&e[_]}),I.default(l,m.default(M,{form:_})));return E(j)}};e.default=N,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},a=r(29),s=n(a),f=r(18),c=n(f),l=function(t,e,r){var n=e.Component,a=s.default(t,e,r);return function(t,r,s){return function(f){var l=a(f,r,s),d=i({touchOnBlur:!0,touchOnChange:!1,destroyOnUnmount:!0},t),p=function(t){function r(){u(this,r),t.apply(this,arguments)}return o(r,t),r.prototype.render=function(){return e.createElement(l,i({},d,this.props))},r}(n);return c.default(p,f)}}};e.default=l,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var a=r(50),s=n(a),f=r(12),c=n(f),l=r(27),d=n(l),p=function(t,e,r){return function(n,a,f){var l=e.Component,p=e.PropTypes,v=function(c){function l(u){o(this,l),c.call(this,u),this.cache=s.default(this,{ReduxForm:{params:["reduxMountPoint","form","formKey","getFormState"],fn:d.default(u,t,e,r,n,a,f)}})}return i(l,c),l.prototype.componentWillReceiveProps=function(t){this.cache.componentWillReceiveProps(t)},l.prototype.render=function(){var t=this.cache.ReduxForm,r=this.props,n=(r.reduxMountPoint,r.destroyOnUnmount,r.form,r.getFormState,r.touchOnBlur,r.touchOnChange,u(r,["reduxMountPoint","destroyOnUnmount","form","getFormState","touchOnBlur","touchOnChange"]));return e.createElement(t,n)},l}(l);return v.displayName="ReduxFormConnector("+c.default(n)+")",v.WrappedComponent=n,v.propTypes={destroyOnUnmount:p.bool,reduxMountPoint:p.string,form:p.string.isRequired,formKey:p.string,getFormState:p.func,touchOnBlur:p.bool,touchOnChange:p.bool},v.defaultProps={reduxMountPoint:"form",getFormState:function(t,e){return t[e]}},v}};e.default=p,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(9),o=n(u),i=function(t,e,r,n){return function(u){var i=o.default(u,r);e(t,i),n&&n(t,i)}};e.default=i,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(9),o=n(u),i=function(t,e,r){return function(n){return e(t,o.default(n,r))}};e.default=i,t.exports=e.default},function(t,e,r){"use strict";e.__esModule=!0;var n=r(8),u=function(t,e){return function(r){e(t,r.dataTransfer.getData(n.dataKey))}};e.default=u,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function(t,e){return function(){return e(t)}};e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(11),o=n(u),i=function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),u=1;r>u;u++)n[u-1]=arguments[u];return o.default(e)?t.apply(void 0,n):t.apply(void 0,[e].concat(n))}};e.default=i,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function n(t){var e=Object.keys(t);return e.length?e.reduce(function(e,r){var u=t[r];return u&&(u.value?e[r]=u.value:Array.isArray(u)?e[r]=u.map(function(t){return t.value||n(t)}):e[r]=n(u)),e},{}):void 0};e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(4),o=n(u),i=r(1),a=n(i),s=function(t,e,r,n){var u=r.dispatch,i=r.fields,s=r.startSubmit,f=r.stopSubmit,c=r.submitFailed,l=r.returnRejectedSubmitPromise,d=r.touch,p=r.validate,v=p(e,r);if(d.apply(void 0,i),a.default(v)){var y=function(){var r=t(e,u);return o.default(r)?(s(),r.then(function(t){return f(),t},function(t){return f(t),l?Promise.reject(t):void 0})):r},h=n();return o.default(h)?h.then(y,function(){return c(),l?Promise.reject():Promise.resolve()}):y()}c()};e.default=s,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function(t){return void 0===t?{}:{initial:t,value:t}},n=function u(t){return t?Object.keys(t).reduce(function(e,n){var o=t[n];return Array.isArray(o)?e[n]=o.map(function(t){return"object"==typeof t?u(t):r(t)}):null!==o&&"object"==typeof o?e[n]=u(o):e[n]=r(o),e},{}):t};e.default=n,t.exports=e.default},function(t,e){"use strict";function r(t,e){if(t===e)return!0;if("boolean"==typeof t||"boolean"==typeof e)return t===e;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t&&"object"==typeof t){if(!e||"object"!=typeof e)return!1;var n=Object.keys(t),u=Object.keys(e);if(n.length!==u.length)return!1;for(var o=0;o<u.length;o++){var i=u[o];if(!r(t[i],e[i]))return!1}}else if(t||e)return t===e;return!0}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";e.__esModule=!0;var n=r(5),u=n.PropTypes.any,o=n.PropTypes.bool,i=n.PropTypes.string,a=n.PropTypes.func,s=n.PropTypes.object,f={active:i,asyncValidating:o.isRequired,dirty:o.isRequired,error:u,errors:s,fields:s.isRequired,formKey:u,invalid:o.isRequired,pristine:o.isRequired,submitting:o.isRequired,submitFailed:o.isRequired,valid:o.isRequired,values:s.isRequired,asyncValidate:a.isRequired,destroyForm:a.isRequired,handleSubmit:a.isRequired,initializeForm:a.isRequired,resetForm:a.isRequired,touch:a.isRequired,touchAll:a.isRequired,untouch:a.isRequired,untouchAll:a.isRequired};e.default=f,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(30),o=n(u),i=r(31),a=n(i),s=r(8),f=n(s),c=r(32),l=n(c),d=r(33),p=n(d),v=r(43),y=n(v),h=r(14),m=n(h),g=r(44),b=n(g),_=function O(t,e,r,n,u,i,s,c){for(var d=!0;d;){var v=t,h=e,g=r,_=n,x=u,A=i,S=s,T=c;void 0===g&&(g=""),d=!1;var j=T.asyncBlurFields,R=T.blur,M=T.change,P=T.focus,E=T.form,w=T.initialValues,V=T.readonly,I=T.addArrayValue,C=T.removeArrayValue,F=h.indexOf("."),N=h.indexOf("["),U=h.indexOf("]");if(N>0&&U!==N+1)throw new Error("found [ not followed by ]");if(N>0&&(0>F||F>N)){var q=function(){var t=h.substring(0,N),e=h.substring(U+1);"."===e[0]&&(e=e.substring(1));var r=v&&v[t]||[];_[t]||(_[t]=[],Object.defineProperty(_[t],"addField",{value:function(e,r){return I(g+t,e,r)}}),Object.defineProperty(_[t],"removeField",{value:function(e){return C(g+t,e)}}));var n=_[t];return r.forEach(function(r,u){e&&!n[u]&&(n[u]={});var o=e?n[u]:{},i=O(r,e,""+g+t+"["+u+"]"+(e?".":""),o,x,A,S,T);e||(n[u]=i)}),n.length>r.length&&n.splice(r.length,n.length-r.length),{v:n}}();if("object"==typeof q)return q.v}if(!(F>0)){var D=g+h,k=_[h]||{};if(k.name!==D){var W=a.default(D,M,S),B=m.default(D,w);k.name=D,k.defaultChecked=B===!0,k.defaultValue=B,k.initialValue=B,V||(k.onBlur=o.default(D,R,S,~j.indexOf(D)&&function(t,e){return y.default(A(t,e))}),k.onChange=W,k.onDragStart=f.default(D,function(){return k.value}),k.onDrop=l.default(D,M),k.onFocus=p.default(D,P),k.onUpdate=W),k.valid=!0,k.invalid=!1}var L=(h?v[h]:v)||{},K=m.default(D,x),Y=b.default(k,L,D===E._active,K);return(h||_[h]!==Y)&&(_[h]=Y),Y}var z=h.substring(0,F),H=h.substring(F+1);_[z]||(_[z]={}),t=v[z]||{},e=H,r=g+z+".",n=_[z],u=x,i=A,s=S,c=T,d=!0,j=R=M=P=E=w=V=I=C=F=N=U=q=z=H=void 0}};e.default=_,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n]); }return t},o=r(40),i=n(o),a=r(16),s=n(a),f=r(13),c=n(f),l=function(t,e,r,n){var o=t.fields,a=t.form,f=t.validate,l=c.default(o,a),d=f(l,t),p={},v=d._error||a._error,y=!v,h=!0,m=u({},e);return o.forEach(function(e){var u=i.default(a,e,void 0,m,d,r,n,t);Array.isArray(u)?(y=u.every(function(t){return!t.invalid}),h=u.every(function(t){return!t.dirty}),p=u.filter(function(t){return t.error}).map(function(t){return t.error}),console.info("errors",u,"----",p)):(u.invalid&&(y=!1),u.dirty&&(h=!1),u.error&&(p=s.default(e,u.error,p)))}),Object.defineProperty(m,"_meta",{value:{allPristine:h,allValid:y,values:l,errors:p,formError:v}}),m};e.default=l,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=function(t){return void 0===t||t&&void 0===t.initial?{}:{initial:t.initial,value:t.initial}},n=function(t){return t&&"object"==typeof t&&(void 0!==t.value||void 0!==t.initial)},u=function o(t){return t?Object.keys(t).reduce(function(e,u){var i=t[u];return Array.isArray(i)?e[u]=i.map(function(t){return n(t)?r(t):o(t)}):i&&(n(i)?e[u]=r(i):"object"==typeof i&&null!==i?e[u]=o(i):e[u]=i),e},{}):t};e.default=u,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(4),o=n(u),i=function(){return void 0},a=function(t){return o.default(t)?t.then(i,i):t};e.default=a,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(38),i=n(o),a=r(1),s=n(a),f=function(t,e,r,n){var o={};t.value!==e.value&&(o.value=e.value,o.checked="boolean"==typeof e.value?e.value:void 0);var a=i.default(e.value,e.initial);t.pristine!==a&&(o.dirty=!a,o.pristine=a);var f=n||e.submitError||e.asyncError;f!==t.error&&(o.error=f);var c=s.default(f);t.valid!==c&&(o.invalid=!c,o.valid=c),r!==t.active&&(o.active=r);var l=!!e.touched;l!==t.touched&&(o.touched=l);var d=!!e.visited;return d!==t.visited&&(o.visited=d),Object.keys(o).length?u({},t,o):t};e.default=f,t.exports=e.default},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},u=r(21),o=function(t,e){return t?"function"==typeof t?t.length>1?function(r,o){return n({},t(r,o),u.bindActionCreators(e,r),{dispatch:r})}:function(r){return n({},t(r),u.bindActionCreators(e,r),{dispatch:r})}:function(r){return n({},u.bindActionCreators(t,r),u.bindActionCreators(e,r),{dispatch:r})}:function(t){return n({},u.bindActionCreators(e,t),{dispatch:t})}};e.default=o,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function(t,e){if(t){if("function"!=typeof t)throw new Error("mapStateToProps must be a function");return t.length>1?function(n,u){return r({},t(n,u),{form:e(n)})}:function(n){return r({},t(n),{form:e(n)})}}return function(t){return{form:e(t)}}};e.default=n,t.exports=e.default},function(t,e){function r(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function n(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var u="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();e=t.exports=u?r:n,e.supported=r,e.unsupported=n},function(t,e){function r(t){var e=[];for(var r in t)e.push(r);return e}e=t.exports="function"==typeof Object.keys?Object.keys:r,e.shim=r},function(t,e,r){"use strict";var n=function(t,e,r,n,u,o,i,a){if(!t){var s;if(void 0===e)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[r,n,u,o,i,a],c=0;s=new Error("Invariant Violation: "+e.replace(/%s/g,function(){return f[c++]}))}throw s.framesToPop=1,s}};t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(51),o=n(u);e.default=o.default,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var r=[],n={},u={},o=function a(t){Object.keys(n).forEach(function(e){~n[e].props.indexOf(t)&&(delete n[e].value,a(e))})};return Object.keys(e).forEach(function(o){var i=e[o].fn,a=e[o].params;a.forEach(function(t){~r.indexOf(t)||r.push(t)}),n[o]={props:a},Object.defineProperty(u,o,{get:function(){var e=n[o];if(e&&void 0!==e.value)return e.value;var r=a.map(function(e){return t.props[e]||u[e]}),s=i.apply(void 0,r);return n[o]={props:a,value:s},s}})}),u.componentWillReceiveProps=function(e){var n=[];r.forEach(function(r){i.default(t.props[r],e[r])||n.push(r)}),n.forEach(o)},u}e.__esModule=!0,e.default=u;var o=r(17),i=n(o);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t){var e=i.default(t),r=s.default(t);return{Provider:e,connect:r}}e.__esModule=!0,e.default=u;var o=r(54),i=n(o),a=r(53),s=n(a);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function i(t){return t.displayName||t.name||"Component"}function a(t){var e=t.Component,r=t.PropTypes,n=c.default(r);return function(r,a,f){function c(t,e){var r=t.getState(),n=R?b(r,e):b(r);return _.default(v.default(n),"`mapStateToProps` must return an object. Instead received %s.",n),n}function l(t,e){var r=t.dispatch,n=M?T(r,e):T(r);return _.default(v.default(n),"`mapDispatchToProps` must return an object. Instead received %s.",n),n}function p(t,e,r){var n=j(t,e,r);return _.default(v.default(n),"`mergeProps` must return an object. Instead received %s.",n),n}var y=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],m=Boolean(r),b=r||O,T=v.default(a)?h.default(a):a||x,j=f||A,R=b.length>1,M=T.length>1,P=y.pure,E=void 0===P?!0:P,w=S++;return function(r){var a=function(e){function n(t,r){u(this,n),e.call(this,t,r),this.version=w,this.store=t.store||r.store,_.default(this.store,'Could not find "store" in either the context or '+('props of "'+this.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+this.constructor.displayName+'".')),this.stateProps=c(this.store,t),this.dispatchProps=l(this.store,t),this.state={storeState:null},this.updateState()}return o(n,e),n.prototype.shouldComponentUpdate=function(t,e){if(!E)return this.updateStateProps(t),this.updateDispatchProps(t),this.updateState(t),!0;var r=e.storeState!==this.state.storeState,n=!d.default(t,this.props),u=!1,o=!1;return(r||n&&R)&&(u=this.updateStateProps(t)),n&&M&&(o=this.updateDispatchProps(t)),n||u||o?(this.updateState(t),!0):!1},n.prototype.computeNextState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0];return p(this.stateProps,this.dispatchProps,t)},n.prototype.updateStateProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=c(this.store,t);return d.default(e,this.stateProps)?!1:(this.stateProps=e,!0)},n.prototype.updateDispatchProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=l(this.store,t);return d.default(e,this.dispatchProps)?!1:(this.dispatchProps=e,!0)},n.prototype.updateState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0];this.nextState=this.computeNextState(t)},n.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},n.prototype.trySubscribe=function(){m&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},n.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},n.prototype.componentDidMount=function(){this.trySubscribe()},n.prototype.componentWillUnmount=function(){this.tryUnsubscribe()},n.prototype.handleChange=function(){this.unsubscribe&&this.setState({storeState:this.store.getState()})},n.prototype.getWrappedInstance=function(){return this.refs.wrappedInstance},n.prototype.render=function(){return t.createElement(r,s({ref:"wrappedInstance"},this.nextState))},n}(e);return a.displayName="Connect("+i(r)+")",a.WrappedComponent=r,a.contextTypes={store:n},a.propTypes={store:n},g.default(a,r)}}}e.__esModule=!0;var s=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=a;var f=r(19),c=n(f),l=r(57),d=n(l),p=r(56),v=n(p),y=r(58),h=n(y),m=r(18),g=n(m),b=r(49),_=n(b),O=function(){return{}},x=function(t){return{dispatch:t}},A=function(t,e,r){return s({},r,t,e)},S=0;t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function i(t){var e=t.version;if("string"!=typeof e)return!0;var r=e.split("."),n=parseInt(r[0],10),u=parseInt(r[1],10);return 0===n&&13===u}function a(t){function e(){p||d||(p=!0,console.error("With React 0.14 and later versions, you no longer need to wrap <Provider> child into a function."))}function r(){!p&&d&&(p=!0,console.error("With React 0.13, you need to wrap <Provider> child into a function. This restriction will be removed with React 0.14."))}function n(){v||(v=!0,console.error("<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/rackt/react-redux/releases/tag/v2.0.0 for the migration instructions."))}var a=t.Component,s=t.PropTypes,c=t.Children,l=f.default(s),d=i(t),p=!1,v=!1,y=function(t){function i(e,r){u(this,i),t.call(this,e,r),this.store=e.store}return o(i,t),i.prototype.getChildContext=function(){return{store:this.store}},i.prototype.componentWillReceiveProps=function(t){var e=this.store,r=t.store;e!==r&&n()},i.prototype.render=function(){var t=this.props.children;return"function"==typeof t?(e(),t=t()):r(),c.only(t)},i}(a);return y.childContextTypes={store:l.isRequired},y.propTypes={store:l.isRequired,children:(d?s.func:s.element).isRequired},y}e.__esModule=!0,e.default=a;var s=r(19),f=n(s);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=r(5),o=n(u),i=r(52),a=n(i),s=a.default(o.default),f=s.Provider,c=s.connect;e.Provider=f,e.connect=c},function(t,e){"use strict";function r(t){if(!t||"object"!=typeof t)return!1;var e="function"==typeof t.constructor?Object.getPrototypeOf(t):Object.prototype;if(null===e)return!0;var r=e.constructor;return"function"==typeof r&&r instanceof r&&n(r)===n(Object)}e.__esModule=!0,e.default=r;var n=function(t){return Function.prototype.toString.call(t)};t.exports=e.default},function(t,e){"use strict";function r(t,e){if(t===e)return!0;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var u=Object.prototype.hasOwnProperty,o=0;o<r.length;o++)if(!u.call(e,r[o])||t[r[o]]!==e[r[o]])return!1;return!0}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return function(e){return u.bindActionCreators(t,e)}}e.__esModule=!0,e.default=n;var u=r(21);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(t){return function(r,n){var u=t(r,n),i=u.dispatch,s=[],f={getState:u.getState,dispatch:function(t){return i(t)}};return s=e.map(function(t){return t(f)}),i=a.default.apply(void 0,s)(u.dispatch),o({},u,{dispatch:i})}}}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=u;var i=r(22),a=n(i);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){return function(){return e(t.apply(void 0,arguments))}}function o(t,e){if("function"==typeof t)return u(t,e);if("object"!=typeof t||null===t||void 0===t)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===t?"null":typeof t)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');return a.default(t,function(t){return u(t,e)})}e.__esModule=!0,e.default=o;var i=r(24),a=n(i);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var r=e&&e.type,n=r&&'"'+r.toString()+'"'||"an action";return'Reducer "'+t+'" returned undefined handling '+n+". To ignore an action, you must explicitly return the previous state."}function o(t){Object.keys(t).forEach(function(e){var r=t[e],n=r(void 0,{type:a.ActionTypes.INIT});if("undefined"==typeof n)throw new Error('Reducer "'+e+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var u="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof r(void 0,{type:u}))throw new Error('Reducer "'+e+'" returned undefined when probed with a random type. '+("Don't try to handle "+a.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}function i(t){var e,r=d.default(t,function(t){return"function"==typeof t});try{o(r)}catch(n){e=n}var i=c.default(r,function(){return void 0});return function(t,n){if(void 0===t&&(t=i),e)throw e;var o=!1,a=c.default(r,function(e,r){var i=t[r],a=e(i,n);if("undefined"==typeof a){var s=u(r,n);throw new Error(s)}return o=o||a!==i,a});return o?a:t}}e.__esModule=!0,e.default=i;var a=r(20),s=r(23),f=(n(s),r(24)),c=n(f),l=r(62),d=n(l);t.exports=e.default},function(t,e){"use strict";function r(t,e){return Object.keys(t).reduce(function(r,n){return e(t[n])&&(r[n]=t[n]),r},{})}e.__esModule=!0,e.default=r,t.exports=e.default}])});
src/components/icons/Star.js
edauenhauer/google-drive-copy-folder
import React from 'react'; import Icon from './Icon'; // Credit: https://iconmonstr.com/star-3/ export default function Star(props) { return ( <Icon {...props}> <path d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 1.48 8.279-7.416-3.967-7.417 3.967 1.481-8.279-6.064-5.828 8.332-1.151z" /> </Icon> ); }
ajax/libs/yasqe/2.0.0/yasqe.bundled.min.js
hanbyul-here/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,r,i){function n(s,a){if(!r[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=r[s]={exports:{}};e[s][0].call(p.exports,function(t){var r=e[s][1][t];return n(r?r:t)},p,p.exports,t,e,r,i)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s<i.length;s++)n(i[s]);return n}({1:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var r=e("jquery"),i=e("codemirror"),n=(e("./sparql.js"),e("./utils.js")),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.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){t=l(t);var r=u(i(e,t));return p(r),r},l=function(e){var t=r.extend(!0,{},a.defaults,e);return t},u=function(t){return r(t.getWrapperElement()).addClass("yasqe"),t.autocompleters=e("./autocompleters/autocompleterBase.js")(t),t.options.autocompleters&&t.options.autocompleters.forEach(function(e){YASQE.Autocompleters[e]&&t.autocompleters.init(e,YASQE.Autocompleters[e])}),t.getCompleteToken=function(r,i){return e("./tokenUtils.js").getCompleteToken(t,r,i)},t.getPreviousNonWsToken=function(r,i){return e("./tokenUtils.js").getPreviousNonWsToken(t,r,i)},t.getNextNonWsToken=function(r,i){return e("./tokenUtils.js").getNextNonWsToken(t,r,i)},t.query=function(e){a.executeQuery(t,e)},t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)},t.addPrefix=function(r){return e("./prefixUtils.js").addPrefix(t,r)},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},p=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var i=o.storage.get(t);i&&e.setValue(i)}if(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("cursorActivity",function(e){c(e)}),e.prevQueryValid=!1,h(e),a.positionButtons(e),e.options.consumeShareLink){var s=r.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},c=function(e){e.cursor=r(".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"))},d=null,h=function(t,i){t.queryValid=!0,d&&(d(),d=null),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;if(t.queryType=n.queryType,0==n.OK){if(!t.options.syntaxErrorCheck)return void r(t.getWrapperElement).find(".sp-error").css("color","black");var p=o.svg.getElement(s.warning,{width:"15px",height:"15px"});n.possibleCurrent&&n.possibleCurrent.length>0&&(p.style.zIndex="99999999",e("./tooltip")(t,p,function(){var e=[];return n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+r("<div/>").text(t).html()+"</strong>")}),"This line is invalid. Expected: "+e.join(", ")})),p.style.marginTop="2px",p.style.marginLeft="2px",t.setGutterMarker(a,"gutterErrorBar",p),d=function(){t.markText({line:a,ch:n.errorStartPos},{line:a,ch:n.errorEndPos},"sp-error")},t.queryValid=!1;break}}if(t.prevQueryValid=t.queryValid,i&&null!=n&&void 0!=n.stack){var c=n.stack,h=n.stack.length;h>1?t.queryValid=!1:1==h&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};r.extend(a,i),a.Autocompleters={},a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t},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=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),i=0;t.is(":visible")&&(i=t.outerWidth()),e.buttons.is(":visible")&&e.buttons.css("right",i)},a.createShareLink=function(e){return{query:e.getValue()}},a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)},a.drawButtons=function(e){if(e.buttons=r("<div class='yasqe_buttons'></div>").appendTo(r(e.getWrapperElement())),e.options.createShareLink){var t=r(o.svg.getElement(s.share,{width:"30px",height:"30px"}));t.click(function(i){i.stopPropagation();var n=r("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);r("html").click(function(){n&&n.remove()}),n.click(function(e){e.stopPropagation()});var o=r("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+r.param(e.options.createShareLink(e)));o.focus(function(){var e=r(this);e.select(),e.mouseup(function(){return e.unbind("mouseup"),!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)}if(e.options.sparql.showQueryButton){var i=40,n=40;r("<div class='yasqe_queryButton'></div>").click(function(){r(this).hasClass("query_busy")?(e.xhr&&e.xhr.abort(),a.updateQueryButton(e)):e.query()}).height(i).width(n).appendTo(e.buttons),a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var i=r(e.getWrapperElement()).find(".yasqe_queryButton");0!=i.length&&(t||(t="valid",e.queryValid===!1&&(t="error")),t==e.queryStatus||"busy"!=t&&"valid"!=t&&"error"!=t||(i.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t).append(o.svg.getElement(s[E[t]],{width:"100%",height:"100%"})),e.queryStatus=t))},a.fromTextArea=function(e,t){t=l(t);var r=u(i.fromTextArea(e,t));return p(r),r},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,r=e.getCursor(!1).line,i=Math.min(t,r),n=Math.max(t,r),o=!0,s=i;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=i;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(),r=e.lineCount();e.replaceRange("\n",{line:r-1,ch:e.getLine(r-1).length});for(var i=r;i>t.line;i--){var n=e.getLine(i-1);e.replaceRange(n,{line:i,ch:0},{line:i,ch:e.getLine(i).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};f(e,e.getCursor(!0),t)}else{var r=e.lineCount(),i=e.getTextArea().value.length;f(e,{line:0,ch:0},{line:r,ch:i})}};var f=function(e,t,r){var i=e.indexFromPos(t),n=e.indexFromPos(r),o=m(e.getValue(),i,n);e.operation(function(){e.replaceRange(o,t,r);for(var n=e.posFromIndex(i).line,s=e.posFromIndex(i+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},m=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(""!=r.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];return i.runMode(e,"sparql11",function(e,t){c.push(t);var r=l(e,t);0!=r?(1==r?(u+=e+"\n",p=""):(u+="\n"+e,p=e),c=[]):(p+=e,u+=e),1==c.length&&"sp-ws"==c[0]&&(c=[])}),r.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js").use(a),e("./defaults.js").use(a),a.version={CodeMirror:i.version,YASQE:e("../package.json").version,jquery:r.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":17,"./autocompleters/autocompleterBase.js":18,"./autocompleters/classes.js":19,"./autocompleters/prefixes.js":20,"./autocompleters/properties.js":21,"./autocompleters/variables.js":23,"./defaults.js":24,"./imgs.js":25,"./prefixUtils.js":26,"./sparql.js":27,"./tokenUtils.js":28,"./tooltip":29,"./utils.js":30,codemirror:10,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/hint/show-hint.js":7,"codemirror/addon/runmode/runmode.js":8,"codemirror/addon/search/searchcursor.js":9,jquery:11,"yasgui-utils":14}],2:[function(e){var t=e("jquery");t.deparam=function(e,r){var i={},n={"true":!0,"false":!1,"null":null};return t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=i,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):d=0,2===a.length)if(s=decodeURIComponent(a[1]),r&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s),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(i[l])?i[l].push(s):i[l]=void 0!==i[l]?[i[l],s]:s;else l&&(i[l]=r?void 0:"")}),i}},{jquery:11}],3:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?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,r="<[^<>\"'|{}^\\\x00- ]*>",i="[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=i+"|_",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="("+i+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",h="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",E="("+d+"|"+h+")";"sparql11"==u?(e="("+n+"|:|[0-9]|"+E+")(("+o+"|\\.|:|"+E+")*("+o+"|:|"+E+"))?",t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"):(e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?",t="_:"+e);var f="("+p+")?:",m=f+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",L="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",T="\\+"+x,I="\\+"+N,y="\\+"+L,A="-"+x,S="-"+N,C="-"+L,R="\\\\[tbnrf\\\\\"']",b="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+")*'",O='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+')*"',P="'''(('|'')?([^'\\\\]|"+R+"))*'''",D='"""(("|"")?([^"\\\\]|'+R+'))*"""',_="[\\x20\\x09\\x0D\\x0A]",M="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",w="("+_+"|("+M+"))*",G="\\("+w+"\\)",k="\\["+w+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+_+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+M),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+r),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("^"+L),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("^"+T),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("^"+G),style:"punc"},{name:"ANON",regex:new RegExp("^"+k),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+f),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return B}function r(e){var t=[],r=o[e];if(void 0!=r)for(var i in r)t.push(i.toString());else t.push(e);return t}function i(e,t){function i(){for(var t=null,r=0;r<h.length;++r)if(t=e.match(h[r].regex,!0,!1))return{cat:h[r].name,style:h[r].style,text:t[0]};return(t=e.match(s,!0,!1))?{cat:e.current().toUpperCase(),style:"keyword",text:t[0]}:(t=e.match(a,!0,!1))?{cat:e.current(),style:"punc",text:t[0]}:(t=e.match(/^.[A-Za-z0-9]*/,!0,!1),{cat:"<invalid_token>",style:"error",text:t[0]})}function n(){var r=e.column();t.errorStartPos=r,t.errorEndPos=r+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=i();if("<invalid_token>"==c.cat)return 1==t.OK&&(t.OK=!1,n()),t.complete=!1,c.style;if("WS"==c.cat||"COMMENT"==c.cat)return t.possibleCurrent=t.possibleNext,c.style;for(var d,E=!1,f=c.cat;t.stack.length>0&&f&&t.OK&&!E;)if(d=t.stack.pop(),o[d]){var m=o[d][f];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==f){E=!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,t.storeProperty&&"punc"!=f.cat&&(t.lastProperty=c.text,t.storeProperty=!1)}else t.OK=!1,t.complete=!1,n();return!E&&t.OK&&(t.OK=!1,t.complete=!1,n()),t.possibleCurrent=t.possibleNext,t.possibleNext=r(t.stack[t.stack.length-1]),c.style}function n(t,r){var i=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(r)){for(var o=r.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=E[t.stack[n]];s&&(i+=s,--n)}for(;n>=0;--n){var s=f[t.stack[n]];s&&(i+=s)}return i*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(),h=d.terminal,E={"*[,, 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},f={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1}; return{token:i,startState:function(){return{tokenize:i,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:r(p),possibleNext:r(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}}),e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:10}],4:[function(e,t){t.exports=Trie=function(){this.words=0,this.prefixes=0,this.children=[]},Trie.prototype={insert:function(e,t){if(0!=e.length){var r,i,n=this;if(void 0===t&&(t=0),t===e.length)return void n.words++;n.prefixes++,r=e[t],void 0===n.children[r]&&(n.children[r]=new Trie),i=n.children[r],i.insert(e,t+1)}},remove:function(e,t){if(0!=e.length){var r,i,n=this;if(void 0===t&&(t=0),void 0!==n){if(t===e.length)return void n.words--;n.prefixes--,r=e[t],i=n.children[r],i.remove(e,t+1)}}},update:function(e,t){0!=e.length&&0!=t.length&&(this.remove(e),this.insert(t))},countWord:function(e,t){if(0==e.length)return 0;var r,i,n=this,o=0;return void 0===t&&(t=0),t===e.length?n.words:(r=e[t],i=n.children[r],void 0!==i&&(o=i.countWord(e,t+1)),o)},countPrefix:function(e,t){if(0==e.length)return 0;var r,i,n=this,o=0;if(void 0===t&&(t=0),t===e.length)return n.prefixes;var r=e[t];return i=n.children[r],void 0!==i&&(o=i.countPrefix(e,t+1)),o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,r,i=this,n=[];if(void 0===e&&(e=""),void 0===i)return[];i.words>0&&n.push(e);for(t in i.children)r=i.children[t],n=n.concat(r.getAllWords(e+t));return n},autoComplete:function(e,t){var r,i,n=this;return 0==e.length?void 0===t?n.getAllWords(e):[]:(void 0===t&&(t=0),r=e[t],i=n.children[r],void 0===i?[]:t===e.length-1?i.getAllWords(e):i.autoComplete(e,t+1))}}},{}],5:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?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 r(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,""),document.documentElement.style.overflow="";var r=e.state.fullScreenRestore;t.style.width=r.width,t.style.height=r.height,window.scrollTo(r.scrollLeft,r.scrollTop),e.refresh()}e.defineOption("fullScreen",!1,function(i,n,o){o==e.Init&&(o=!1),!o!=!n&&(n?t(i):r(i))})})},{"../../lib/codemirror":10}],6:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){function t(e,t,i,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(i&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=r(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 r(e,t,r,i,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=r>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=r){var h=e.getLine(d);if(h){var E=r>0?0:h.length-1,f=r>0?h.length:-1;if(!(h.length>o))for(d==t.line&&(E=t.ch-(0>r?1:0));E!=f;E+=r){var m=h.charAt(E);if(p.test(m)&&(void 0===i||e.getTokenTypeAt(s(d,E+1))==i)){var g=a[m];if(">"==g.charAt(1)==r>0)u.push(m);else{if(!u.length)return{pos:s(d,E),ch:m};u.pop()}}}}}return d-r==(r>0?e.lastLine():e.firstLine())?!1:null}function i(e,r,i){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,i);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(!r)return d;setTimeout(d,800)}}function n(e){e.operation(function(){l&&(l(),l=null),l=i(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,r,i){i&&i!=e.Init&&t.off("cursorActivity",n),r&&(t.state.matchBrackets="object"==typeof r?r:{},t.on("cursorActivity",n))}),e.defineExtension("matchBrackets",function(){i(this,!0)}),e.defineExtension("findMatchingBracket",function(e,r,i){return t(this,e,r,i)}),e.defineExtension("scanForBracket",function(e,t,i,n){return r(this,e,t,i,n)})})},{"../../lib/codemirror":10}],7:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?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 r(e){return"string"==typeof e?e:e.text}function i(e,t){function r(e,r){var n;n="string"!=typeof r?function(e){return r(e,t)}:i.hasOwnProperty(r)?i[r]:r,o[e]=n}var i={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?{}:i;if(n)for(var s in n)n.hasOwnProperty(s)&&r(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&r(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 h=p.appendChild(document.createElement("li")),E=c[d],f=s+(d!=this.selectedHint?"":" "+a);null!=E.className&&(f=E.className+" "+f),h.className=f,E.render?E.render(h,o,E):h.appendChild(document.createTextNode(E.displayText||r(E))),h.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),L=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var T=p.getBoundingClientRect(),I=T.bottom-L;if(I>0){var y=T.bottom-T.top,A=m.top-(m.bottom-T.top);if(A-y>0)p.style.top=(v=m.top-y)+"px",x=!1;else if(y>L){p.style.height=L-5+"px",p.style.top=(v=m.bottom-T.top)+"px";var S=u.getCursor();o.from.ch!=S.ch&&(m=u.cursorCoords(S),p.style.left=(g=m.left)+"px",T=p.getBoundingClientRect())}}var C=T.left-N;if(C>0&&(T.right-T.left>N&&(p.style.width=N-5+"px",C-=T.right-T.left-N),p.style.left=(g=m.left-C)+"px"),u.addKeyMap(this.keyMap=i(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})),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();return u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),r=u.getWrapperElement().getBoundingClientRect(),i=v+b.top-e.top,n=i-(window.pageYOffset||(document.documentElement||document.body).scrollTop);return x||(n+=p.offsetHeight),n<=r.top||n>=r.bottom?t.close():(p.style.top=i+"px",void(p.style.left=g+b.left-e.left+"px"))}),e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);t&&null!=t.hintId&&(l.changeActive(t.hintId),l.pick())}),e.on(p,"click",function(e){var r=n(p,e.target||e.srcElement);r&&null!=r.hintId&&(l.changeActive(r.hintId),t.options.completeOnSingleClick&&l.pick())}),e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)}),e.signal(o,"select",c[0],p.firstChild),!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,r){if(!t)return e.showHint(r);r&&r.async&&(t.async=!0);var i={hint:t};if(r)for(var n in r)i[n]=r[n];return e.showHint(i)},e.defineExtension("showHint",function(r){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var i=this.state.completionActive=new t(this,r),n=i.options.hint;if(n)return e.signal(this,"startCompletion",this),n.async?void n(this,function(e){i.showHints(e)},i.options):i.showHints(n(this,i.options))}}),t.prototype={close:function(){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,i){var n=t.list[i];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(r(n),n.from||t.from,n.to||t.to,"complete"),e.signal(t,"pick",n),this.close()},showHints:function(e){return e&&e.list.length&&this.active()?void(this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e)):this.close()},showWidget:function(t){function r(){l||(l=!0,p.close(),p.cm.off("cursorActivity",a),t&&e.signal(t,"close"))}function i(){if(!l){e.signal(t,"update");var r=p.options.hint;r.async?r(p.cm,n,p.options):n(r(p.cm,p.options))}}function n(e){if(t=e,!l){if(!t||!t.list.length)return r();p.widget&&p.widget.close(),p.widget=new o(p,t)}}function s(){u&&(f(u),u=0)}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);e.line!=d.line||t.length-e.ch!=h-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1))?p.close():(u=E(i),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(),h=this.cm.getLine(d.line).length,E=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},f=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a),this.onClose=r},buildOptions:function(e){var t=this.cm.options.hintOptions,r={};for(var i in l)r[i]=l[i];if(t)for(var i in t)void 0!==t[i]&&(r[i]=t[i]);if(e)for(var i in e)void 0!==e[i]&&(r[i]=e[i]);return r}},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;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,r){if(t>=this.data.list.length?t=r?this.data.list.length-1:0:0>t&&(t=r?0:this.data.list.length-1),this.selectedHint!=t){var i=this.hints.childNodes[this.selectedHint];i.className=i.className.replace(" "+a,""),i=this.hints.childNodes[this.selectedHint=t],i.className+=" "+a,i.offsetTop<this.hints.scrollTop?this.hints.scrollTop=i.offsetTop-3:i.offsetTop+i.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=i.offsetTop+i.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],i)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(t,r){var i,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,r);if(s&&s.list.length)return s}else if(i=t.getHelper(t.getCursor(),"hintWords")){if(i)return e.hint.fromList(t,{words:i})}else if(e.hint.anyword)return e.hint.anyword(t,r)}),e.registerHelper("hint","fromList",function(t,r){for(var i=t.getCursor(),n=t.getTokenAt(i),o=[],s=0;s<r.words.length;s++){var a=r.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(i.line,n.start),to:e.Pos(i.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":10}],8:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";e.runMode=function(t,r,i,n){var o=e.getMode(e.defaults,r),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==i.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=i,p=0;u.innerHTML="",i=function(e,t){if("\n"==e)return u.appendChild(document.createTextNode(a?"\r":e)),void(p=0);for(var r="",i=0;;){var n=e.indexOf(" ",i);if(-1==n){r+=e.slice(i),p+=e.length-i;break}p+=n-i,r+=e.slice(i,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)r+=" ";i=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-"),c.appendChild(document.createTextNode(r))}else u.appendChild(document.createTextNode(r))}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),h=0,E=c.length;E>h;++h){h&&i("\n");var f=new e.StringStream(c[h]);for(!f.string&&o.blankLine&&o.blankLine(d);!f.eol();){var m=o.token(f,d);i(f.current(),m,h,f.start,d),f.start=f.pos}}}})},{"../../lib/codemirror":10}],9:[function(t,r,i){!function(n){"object"==typeof i&&"object"==typeof r?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){if(this.atOccurrence=!1,this.doc=e,null==o&&"string"==typeof t&&(o=!1),n=n?e.clipPos(n):i(0,0),this.pos={from:n,to:n},"string"!=typeof t)t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g")),this.matches=function(r,n){if(r){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;if(o=u,s=o.index,l=o.index+(o[0].length||1),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:i(n.line,s),to:i(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)return p=r(l,u,p),{from:i(o.line,p),to:i(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)return p=r(l,u,p)+o.ch,{from:i(o.line,p),to:i(o.line,p+s.length)}}}:function(){};else{var u=s.split("\n");this.matches=function(t,r){var n=l.length-1;if(t){if(r.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(r.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=i(r.line,u[n].length),s=r.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:i(s,d),to:o}}if(!(r.line+(l.length-1)>e.lastLine())){var c=e.getLine(r.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var h=i(r.line,d),s=r.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:h,to:i(s,u[n].length)}}}}}}}function r(e,t,r){if(e.length==t.length)return r;for(var i=Math.min(r,e.length);;){var n=e.slice(0,i).toLowerCase().length;if(r>n)++i;else{if(!(n>r))return i;--i}}}var i=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=i(e,0);return r.pos={from:t,to:t},r.atOccurrence=!1,!1}for(var r=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n))return this.atOccurrence=!0,this.pos.match||!0;if(e){if(!n.line)return t(0);n=i(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=i(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 r=e.splitLines(t);this.doc.replaceRange(r,this.pos.from,this.pos.to),this.pos.to=i(this.pos.from.line+r.length-1,r[r.length-1].length+(1==r.length?this.pos.from.ch:0))}}},e.defineExtension("getSearchCursor",function(e,r,i){return new t(this.doc,e,r,i)}),e.defineDocExtension("getSearchCursor",function(e,r,i){return new t(this,e,r,i)}),e.defineExtension("selectMatches",function(t,r){for(var i,n=[],o=this.getSearchCursor(t,this.getCursor("from"),r);(i=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":10}],10:[function(t,r,i){!function(t){if("object"==typeof i&&"object"==typeof r)r.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}}(function(){"use strict";function e(r,i){if(!(this instanceof e))return new e(r,i);this.options=i=i?mo(i):{},mo(_s,i,!1),E(i);var n=i.value;"string"==typeof n&&(n=new ia(n,i.mode)),this.doc=n;var o=this.display=new t(r,n);o.wrapper.CodeMirror=this,p(this),l(this),i.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),i.autofocus&&!ps&&Ar(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new lo},Jo&&11>es&&setTimeout(go(yr,this,!0),20),Rr(this),Po(),Jt(this),this.curOp.forceUpdate=!0,bn(this,n),i.autofocus&&!ps||Ao()==o.input?setTimeout(go(Qr,this),20):Zr(this);for(var s in Ms)Ms.hasOwnProperty(s)&&Ms[s](this,i[s],ws);N(this);for(var a=0;a<Us.length;++a)Us[a](this);tr(this)}function t(e,t){var r=this,i=r.input=Lo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ts?i.style.width="1000px":i.setAttribute("wrap","off"),us&&(i.style.border="1px solid black"),i.setAttribute("autocorrect","off"),i.setAttribute("autocapitalize","off"),i.setAttribute("spellcheck","false"),r.inputDiv=Lo("div",[i],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),r.scrollbarH=Lo("div",[Lo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar"),r.scrollbarV=Lo("div",[Lo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),r.scrollbarFiller=Lo("div",null,"CodeMirror-scrollbar-filler"),r.gutterFiller=Lo("div",null,"CodeMirror-gutter-filler"),r.lineDiv=Lo("div",null,"CodeMirror-code"),r.selectionDiv=Lo("div",null,null,"position: relative; z-index: 1"),r.cursorDiv=Lo("div",null,"CodeMirror-cursors"),r.measure=Lo("div",null,"CodeMirror-measure"),r.lineMeasure=Lo("div",null,"CodeMirror-measure"),r.lineSpace=Lo("div",[r.measure,r.lineMeasure,r.selectionDiv,r.cursorDiv,r.lineDiv],null,"position: relative; outline: none"),r.mover=Lo("div",[Lo("div",[r.lineSpace],"CodeMirror-lines")],null,"position: relative"),r.sizer=Lo("div",[r.mover],"CodeMirror-sizer"),r.heightForcer=Lo("div",null,null,"position: absolute; height: "+ha+"px; width: 1px;"),r.gutters=Lo("div",null,"CodeMirror-gutters"),r.lineGutter=null,r.scroller=Lo("div",[r.sizer,r.heightForcer,r.gutters],"CodeMirror-scroll"),r.scroller.setAttribute("tabIndex","-1"),r.wrapper=Lo("div",[r.inputDiv,r.scrollbarH,r.scrollbarV,r.scrollbarFiller,r.gutterFiller,r.scroller],"CodeMirror"),Jo&&8>es&&(r.gutters.style.zIndex=-1,r.scroller.style.paddingRight=0),us&&(i.style.width="0px"),ts||(r.scroller.draggable=!0),ss&&(r.inputDiv.style.height="1px",r.inputDiv.style.position="absolute"),Jo&&8>es&&(r.scrollbarH.style.minHeight=r.scrollbarV.style.minWidth="18px"),e.appendChild?e.appendChild(r.wrapper):e(r.wrapper),r.viewFrom=r.viewTo=t.first,r.view=[],r.externalMeasured=null,r.viewOffset=0,r.lastSizeC=0,r.updateLineNumbers=null,r.lineNumWidth=r.lineNumInnerWidth=r.lineNumChars=null,r.prevInput="",r.alignWidgets=!1,r.pollingFast=!1,r.poll=new lo,r.cachedCharWidth=r.cachedTextHeight=r.cachedPaddingH=null,r.inaccurateSelection=!1,r.maxLine=null,r.maxLineLength=0,r.maxLineChanged=!1,r.wheelDX=r.wheelDY=r.wheelStartX=r.wheelStartY=null,r.shift=!1,r.selForContextMenu=null}function r(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption),i(t)}function i(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.frontier=e.doc.first,Tt(e,100),e.state.modeGen++,e.curOp&&Er(e)}function n(e){e.options.lineWrapping?(Ro(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth=""):(Co(e.display.wrapper,"CodeMirror-wrap"),h(e)),s(e),Er(e),Vt(e),setTimeout(function(){g(e)},100)}function o(e){var t=Qt(e.display),r=e.options.lineWrapping,i=r&&Math.max(5,e.display.scroller.clientWidth/Zt(e.display)-3);return function(n){if(tn(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 r?o+(Math.ceil(n.text.length/i)||1)*t:o+t}}function s(e){var t=e.doc,r=o(e);t.iter(function(e){var t=r(e);t!=e.height&&_n(e,t)})}function a(e){var t=Ws[e.options.keyMap],r=t.style;e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(r?" cm-keymap-"+r:"")}function l(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Vt(e)}function u(e){p(e),Er(e),setTimeout(function(){x(e)},20)}function p(e){var t=e.display.gutters,r=e.options.gutters;To(t);for(var i=0;i<r.length;++i){var n=r[i],o=t.appendChild(Lo("div",null,"CodeMirror-gutter "+n));"CodeMirror-linenumbers"==n&&(e.display.lineGutter=o,o.style.width=(e.display.lineNumWidth||1)+"px")}t.style.display=i?"":"none",c(e)}function c(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px",e.display.scrollbarH.style.left=e.options.fixedGutter?t+"px":0}function d(e){if(0==e.height)return 0;for(var t,r=e.text.length,i=e;t=Yi(i);){var n=t.find(0,!0);i=n.from.line,r+=n.from.ch-n.to.ch}for(i=e;t=Ki(i);){var n=t.find(0,!0);r-=i.text.length-n.from.ch,i=n.to.line,r+=i.text.length-n.to.ch}return r}function h(e){var t=e.display,r=e.doc;t.maxLine=On(r,r.first),t.maxLineLength=d(t.maxLine),t.maxLineChanged=!0,r.iter(function(e){var r=d(e);r>t.maxLineLength&&(t.maxLineLength=r,t.maxLine=e)})}function E(e){var t=ho(e.gutters,"CodeMirror-linenumbers");-1==t&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function f(e){return e.display.scroller.clientHeight-e.display.wrapper.clientHeight<ha-3}function m(e){var t=e.display.scroller;return{clientHeight:t.clientHeight,barHeight:e.display.scrollbarV.clientHeight,scrollWidth:t.scrollWidth,clientWidth:t.clientWidth,hScrollbarTakesSpace:f(e),barWidth:e.display.scrollbarH.clientWidth,docHeight:Math.round(e.doc.height+Ct(e.display))}}function g(e,t){t||(t=m(e));var r=e.display,i=_o(r.measure),n=t.docHeight+ha,o=t.scrollWidth>t.clientWidth;o&&t.scrollWidth<=t.clientWidth+1&&i>0&&!t.hScrollbarTakesSpace&&(o=!1);var s=n>t.clientHeight;if(s?(r.scrollbarV.style.display="block",r.scrollbarV.style.bottom=o?i+"px":"0",r.scrollbarV.firstChild.style.height=Math.max(0,n-t.clientHeight+(t.barHeight||r.scrollbarV.clientHeight))+"px"):(r.scrollbarV.style.display="",r.scrollbarV.firstChild.style.height="0"),o?(r.scrollbarH.style.display="block",r.scrollbarH.style.right=s?i+"px":"0",r.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||r.scrollbarH.clientWidth)+"px"):(r.scrollbarH.style.display="",r.scrollbarH.firstChild.style.width="0"),o&&s?(r.scrollbarFiller.style.display="block",r.scrollbarFiller.style.height=r.scrollbarFiller.style.width=i+"px"):r.scrollbarFiller.style.display="",o&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(r.gutterFiller.style.display="block",r.gutterFiller.style.height=i+"px",r.gutterFiller.style.width=r.gutters.offsetWidth+"px"):r.gutterFiller.style.display="",!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(0===i){var a=cs&&!as?"12px":"18px";r.scrollbarV.style.minWidth=r.scrollbarH.style.minHeight=a;var l=function(t){eo(t)!=r.scrollbarV&&eo(t)!=r.scrollbarH&&ur(e,Dr)(t)};ua(r.scrollbarV,"mousedown",l),ua(r.scrollbarH,"mousedown",l)}e.state.checkedOverlayScrollbar=!0}}function v(e,t,r){var i=r&&null!=r.top?Math.max(0,r.top):e.scroller.scrollTop;i=Math.floor(i-St(e));var n=r&&null!=r.bottom?r.bottom:i+e.wrapper.clientHeight,o=wn(t,i),s=wn(t,n);if(r&&r.ensure){var a=r.ensure.from.line,l=r.ensure.to.line;if(o>a)return{from:a,to:wn(t,Gn(On(t,a))+e.wrapper.clientHeight)};if(Math.min(l,t.lastLine())>=s)return{from:wn(t,Gn(On(t,l))-e.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(s,o+1)}}function x(e){var t=e.display,r=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var i=T(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=i+"px",s=0;s<r.length;s++)if(!r[s].hidden){e.options.fixedGutter&&r[s].gutter&&(r[s].gutter.style.left=o);var a=r[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=i+n+"px")}}function N(e){if(!e.options.lineNumbers)return!1;var t=e.doc,r=L(e.options,t.first+t.size-1),i=e.display;if(r.length!=i.lineNumChars){var n=i.measure.appendChild(Lo("div",[Lo("div",r)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;return i.lineGutter.style.width="",i.lineNumInnerWidth=Math.max(o,i.lineGutter.offsetWidth-s),i.lineNumWidth=i.lineNumInnerWidth+s,i.lineNumChars=i.lineNumInnerWidth?r.length:-1,i.lineGutter.style.width=i.lineNumWidth+"px",c(e),!0}return!1}function L(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function T(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function I(e,t,r){var i=e.display;this.viewport=t,this.visible=v(i,e.doc,t),this.editorIsHidden=!i.wrapper.offsetWidth,this.wrapperHeight=i.wrapper.clientHeight,this.oldViewFrom=i.viewFrom,this.oldViewTo=i.viewTo,this.oldScrollerWidth=i.scroller.clientWidth,this.force=r,this.dims=P(e)}function y(e,t){var r=e.display,i=e.doc;if(t.editorIsHidden)return mr(e),!1;if(!t.force&&t.visible.from>=r.viewFrom&&t.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&0==Nr(e))return!1;N(e)&&(mr(e),t.dims=P(e));var n=i.first+i.size,o=Math.max(t.visible.from-e.options.viewportMargin,i.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);r.viewFrom<o&&o-r.viewFrom<20&&(o=Math.max(i.first,r.viewFrom)),r.viewTo>s&&r.viewTo-s<20&&(s=Math.min(n,r.viewTo)),gs&&(o=Ji(e.doc,o),s=en(e.doc,s));var a=o!=r.viewFrom||s!=r.viewTo||r.lastSizeC!=t.wrapperHeight;xr(e,o,s),r.viewOffset=Gn(On(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var l=Nr(e);if(!a&&0==l&&!t.force&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return!1;var u=Ao();return l>4&&(r.lineDiv.style.display="none"),D(e,r.updateLineNumbers,t.dims),l>4&&(r.lineDiv.style.display=""),u&&Ao()!=u&&u.offsetHeight&&u.focus(),To(r.cursorDiv),To(r.selectionDiv),a&&(r.lastSizeC=t.wrapperHeight,Tt(e,400)),r.updateLineNumbers=null,!0}function A(e,t){for(var r=t.force,i=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldScrollerWidth!=e.display.scroller.clientWidth)r=!0;else if(r=!1,i&&null!=i.top&&(i={top:Math.min(e.doc.height+Ct(e.display)-ha-e.display.scroller.clientHeight,i.top)}),t.visible=v(e.display,e.doc,i),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!y(e,t))break;b(e);var o=m(e);vt(e),C(e,o),g(e,o)}ro(e,"update",e),(e.display.viewFrom!=t.oldViewFrom||e.display.viewTo!=t.oldViewTo)&&ro(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)}function S(e,t){var r=new I(e,t);if(y(e,r)){b(e),A(e,r);var i=m(e);vt(e),C(e,i),g(e,i)}}function C(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-ha)+"px"}function R(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth<e.display.scroller.clientWidth-1&&(e.display.sizer.style.minHeight=e.display.heightForcer.style.top="0px",e.display.gutters.style.height=t.docHeight+"px")}function b(e){for(var t=e.display,r=t.lineDiv.offsetTop,i=0;i<t.view.length;i++){var n,o=t.view[i];if(!o.hidden){if(Jo&&8>es){var s=o.node.offsetTop+o.node.offsetHeight;n=s-r,r=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;if(2>n&&(n=Qt(t)),(l>.001||-.001>l)&&(_n(o.line,n),O(o.line),o.rest))for(var u=0;u<o.rest.length;u++)O(o.rest[u])}}}function O(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function P(e){for(var t=e.display,r={},i={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s)r[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n,i[e.options.gutters[s]]=o.clientWidth;return{fixedPos:T(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:r,gutterWidth:i,wrapperWidth:t.wrapper.clientWidth}}function D(e,t,r){function i(t){var r=t.nextSibling;return ts&&cs&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),r}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=i(a);var d=o&&null!=t&&u>=t&&c.lineNumber;c.changes&&(ho(c.changes,"gutter")>-1&&(d=!1),_(e,c,u,r)),d&&(To(c.lineNumber),c.lineNumber.appendChild(document.createTextNode(L(e.options,u)))),a=c.node.nextSibling}else{var h=H(e,c,u,r);s.insertBefore(h,a)}u+=c.size}for(;a;)a=i(a)}function _(e,t,r,i){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?k(e,t):"gutter"==o?U(e,t,r,i):"class"==o?B(t):"widget"==o&&V(t,i)}t.changes=null}function M(e){return e.node==e.text&&(e.node=Lo("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),Jo&&8>es&&(e.node.style.zIndex=2)),e.node}function w(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;if(t&&(t+=" CodeMirror-linebackground"),e.background)t?e.background.className=t:(e.background.parentNode.removeChild(e.background),e.background=null);else if(t){var r=M(e);e.background=r.insertBefore(Lo("div",null,t),r.firstChild)}}function G(e,t){var r=e.display.externalMeasured;return r&&r.line==t.line?(e.display.externalMeasured=null,t.measure=r.measure,r.built):gn(e,t)}function k(e,t){var r=t.text.className,i=G(e,t);t.text==t.node&&(t.node=i.pre),t.text.parentNode.replaceChild(i.pre,t.text),t.text=i.pre,i.bgClass!=t.bgClass||i.textClass!=t.textClass?(t.bgClass=i.bgClass,t.textClass=i.textClass,B(t)):r&&(t.text.className=r)}function B(e){w(e),e.line.wrapClass?M(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 U(e,t,r,i){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null);var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=M(t),s=t.gutter=o.insertBefore(Lo("div",null,"CodeMirror-gutter-wrapper","position: absolute; left: "+(e.options.fixedGutter?i.fixedPos:-i.gutterTotalWidth)+"px"),t.text);if(!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(Lo("div",L(e.options,r),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+i.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),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(Lo("div",[u],"CodeMirror-gutter-elt","left: "+i.gutterLeft[l]+"px; width: "+i.gutterWidth[l]+"px"))}}}function V(e,t){e.alignable&&(e.alignable=null);for(var r,i=e.node.firstChild;i;i=r){var r=i.nextSibling;"CodeMirror-linewidget"==i.className&&e.node.removeChild(i)}F(e,t)}function H(e,t,r,i){var n=G(e,t);return t.text=t.node=n.pre,n.bgClass&&(t.bgClass=n.bgClass),n.textClass&&(t.textClass=n.textClass),B(t),U(e,t,r,i),F(t,i),t.node}function F(e,t){if(j(e.line,e,t,!0),e.rest)for(var r=0;r<e.rest.length;r++)j(e.rest[r],e,t,!1)}function j(e,t,r,i){if(e.widgets)for(var n=M(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=Lo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||(l.ignoreEvents=!0),W(a,l,t,r),i&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l),ro(a,"redraw")}}function W(e,t,r,i){if(e.noHScroll){(r.alignable||(r.alignable=[])).push(t);var n=i.wrapperWidth;t.style.left=i.fixedPos+"px",e.coverGutter||(n-=i.gutterTotalWidth,t.style.paddingLeft=i.gutterTotalWidth+"px"),t.style.width=n+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-i.gutterTotalWidth+"px"))}function q(e){return vs(e.line,e.ch)}function z(e,t){return xs(e,t)<0?t:e}function X(e,t){return xs(e,t)<0?e:t}function Y(e,t){this.ranges=e,this.primIndex=t}function K(e,t){this.anchor=e,this.head=t}function $(e,t){var r=e[t];e.sort(function(e,t){return xs(e.from(),t.from())}),t=ho(e,r);for(var i=1;i<e.length;i++){var n=e[i],o=e[i-1];if(xs(o.to(),n.from())>=0){var s=X(o.from(),n.from()),a=z(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=i&&--t,e.splice(--i,2,new K(l?a:s,l?s:a))}}return new Y(e,t)}function Q(e,t){return new Y([new K(e,t||e)],0)}function Z(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function J(e,t){if(t.line<e.first)return vs(e.first,0);var r=e.first+e.size-1;return t.line>r?vs(r,On(e,r).text.length):et(t,On(e,t.line).text.length)}function et(e,t){var r=e.ch;return null==r||r>t?vs(e.line,t):0>r?vs(e.line,0):e}function tt(e,t){return t>=e.first&&t<e.first+e.size}function rt(e,t){for(var r=[],i=0;i<t.length;i++)r[i]=J(e,t[i]);return r}function it(e,t,r,i){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(i){var o=xs(r,n)<0;o!=xs(i,n)<0?(n=r,r=i):o!=xs(r,i)<0&&(r=i)}return new K(n,r)}return new K(i||r,r)}function nt(e,t,r,i){pt(e,new Y([it(e,e.sel.primary(),t,r)],0),i)}function ot(e,t,r){for(var i=[],n=0;n<e.sel.ranges.length;n++)i[n]=it(e,e.sel.ranges[n],t[n],null);var o=$(i,e.sel.primIndex);pt(e,o,r)}function st(e,t,r,i){var n=e.sel.ranges.slice(0);n[t]=r,pt(e,$(n,e.sel.primIndex),i)}function at(e,t,r,i){pt(e,Q(t,r),i)}function lt(e,t){var r={ranges:t.ranges,update:function(t){this.ranges=[];for(var r=0;r<t.length;r++)this.ranges[r]=new K(J(e,t[r].anchor),J(e,t[r].head))}};return ca(e,"beforeSelectionChange",e,r),e.cm&&ca(e.cm,"beforeSelectionChange",e.cm,r),r.ranges!=t.ranges?$(r.ranges,r.ranges.length-1):t}function ut(e,t,r){var i=e.history.done,n=co(i);n&&n.ranges?(i[i.length-1]=t,ct(e,t,r)):pt(e,t,r)}function pt(e,t,r){ct(e,t,r),Wn(e,e.sel,e.cm?e.cm.curOp.id:0/0,r)}function ct(e,t,r){(so(e,"beforeSelectionChange")||e.cm&&so(e.cm,"beforeSelectionChange"))&&(t=lt(e,t));var i=r&&r.bias||(xs(t.primary().head,e.sel.primary().head)<0?-1:1);dt(e,Et(e,t,i,!0)),r&&r.scroll===!1||!e.cm||vi(e.cm)}function dt(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0,oo(e.cm)),ro(e,"cursorActivity",e))}function ht(e){dt(e,Et(e,e.sel,null,!1),fa)}function Et(e,t,r,i){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=ft(e,s.anchor,r,i),l=ft(e,s.head,r,i);(n||a!=s.anchor||l!=s.head)&&(n||(n=t.ranges.slice(0,o)),n[o]=new K(a,l))}return n?$(n,t.primIndex):t}function ft(e,t,r,i){var n=!1,o=t,s=r||1;e.cantEdit=!1;e:for(;;){var a=On(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(i&&(ca(p,"beforeCursorEnter"),p.explicitlyCleared)){if(a.markedSpans){--l;continue}break}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==xs(c,o)&&(c.ch+=s,c.ch<0?c=c.line>e.first?J(e,vs(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?vs(c.line+1,0):null),!c)){if(n)return i?(e.cantEdit=!0,vs(e.first,0)):ft(e,t,r,!0);n=!0,c=t,s=-s}o=c;continue e}}return o}}function mt(e){for(var t=e.display,r=e.doc,i={},n=i.cursors=document.createDocumentFragment(),o=i.selection=document.createDocumentFragment(),s=0;s<r.sel.ranges.length;s++){var a=r.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&xt(e,a,n),l||Nt(e,a,o)}if(e.options.moveInputWithCursor){var u=zt(e,r.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();i.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top)),i.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return i}function gt(e,t){Io(e.display.cursorDiv,t.cursors),Io(e.display.selectionDiv,t.selection),null!=t.teTop&&(e.display.inputDiv.style.top=t.teTop+"px",e.display.inputDiv.style.left=t.teLeft+"px")}function vt(e){gt(e,mt(e))}function xt(e,t,r){var i=zt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=r.appendChild(Lo("div"," ","CodeMirror-cursor"));if(n.style.left=i.left+"px",n.style.top=i.top+"px",n.style.height=Math.max(0,i.bottom-i.top)*e.options.cursorHeight+"px",i.other){var o=r.appendChild(Lo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=i.other.left+"px",o.style.top=i.other.top+"px",o.style.height=.85*(i.other.bottom-i.other.top)+"px"}}function Nt(e,t,r){function i(e,t,r,i){0>t&&(t=0),t=Math.round(t),i=Math.round(i),a.appendChild(Lo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==r?p-e:r)+"px; height: "+(i-t)+"px"))}function n(t,r,n){function o(r,i){return qt(e,vs(t,r),"div",c,i)}var a,l,c=On(s,t),d=c.text.length;return ko(kn(c),r||0,null==n?d:n,function(e,t,s){var c,h,E,f=o(e,"left");if(e==t)c=f,h=E=f.left;else{if(c=o(t-1,"right"),"rtl"==s){var m=f;f=c,c=m}h=f.left,E=c.right}null==r&&0==e&&(h=u),c.top-f.top>3&&(i(h,f.top,null,f.bottom),h=u,f.bottom<c.top&&i(h,f.bottom,null,c.top)),null==n&&t==d&&(E=p),(!a||f.top<a.top||f.top==a.top&&f.left<a.left)&&(a=f),(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c),u+1>h&&(h=u),i(h,c.top,E-h,c.bottom)}),{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Rt(e.display),u=l.left,p=o.lineSpace.offsetWidth-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var h=On(s,c.line),E=On(s,d.line),f=Qi(h)==Qi(E),m=n(c.line,c.ch,f?h.text.length+1:null).end,g=n(d.line,f?0:null,d.ch).start;f&&(m.top<g.top-2?(i(m.right,m.top,null,m.bottom),i(u,g.top,g.left,g.bottom)):i(m.right,m.top,g.left-m.right,m.bottom)),m.bottom<g.top&&i(u,m.bottom,null,g.top)}r.appendChild(a)}function Lt(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var r=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(r=!r)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function Tt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,go(It,e))}function It(e){var t=e.doc;if(t.frontier<t.first&&(t.frontier=t.first),!(t.frontier>=e.display.viewTo)){var r=+new Date+e.options.workTime,i=Hs(t.mode,At(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=hn(e,o,i,!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=Hs(t.mode,i)}else fn(e,o.text,i),o.stateAfter=t.frontier%5==0?Hs(t.mode,i):null;return++t.frontier,+new Date>r?(Tt(e,e.options.workDelay),!0):void 0}),n.length&&lr(e,function(){for(var t=0;t<n.length;t++)fr(e,n[t],"text")})}}function yt(e,t,r){for(var i,n,o=e.doc,s=r?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=On(o,a-1);if(l.stateAfter&&(!r||a<=o.frontier))return a;var u=va(l.text,null,e.options.tabSize);(null==n||i>u)&&(n=a-1,i=u)}return n}function At(e,t,r){var i=e.doc,n=e.display;if(!i.mode.startState)return!0;var o=yt(e,t,r),s=o>i.first&&On(i,o-1).stateAfter;return s=s?Hs(i.mode,s):Fs(i.mode),i.iter(o,t,function(r){fn(e,r.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;r.stateAfter=a?Hs(i.mode,s):null,++o}),r&&(i.frontier=o),s}function St(e){return e.lineSpace.offsetTop}function Ct(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Rt(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Io(e.measure,Lo("pre","x")),r=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,i={left:parseInt(r.paddingLeft),right:parseInt(r.paddingRight)};return isNaN(i.left)||isNaN(i.right)||(e.cachedPaddingH=i),i}function bt(e,t,r){var i=e.options.lineWrapping,n=i&&e.display.scroller.clientWidth;if(!t.measure.heights||i&&t.measure.width!=n){var o=t.measure.heights=[];if(i){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-r.top)}}o.push(r.bottom-r.top)}}function Ot(e,t,r){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var i=0;i<e.rest.length;i++)if(e.rest[i]==t)return{map:e.measure.maps[i],cache:e.measure.caches[i]};for(var i=0;i<e.rest.length;i++)if(Mn(e.rest[i])>r)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function Pt(e,t){t=Qi(t);var r=Mn(t),i=e.display.externalMeasured=new dr(e.doc,t,r);i.lineN=r;var n=i.built=gn(e,i);return i.text=n.pre,Io(e.display.lineMeasure,n.pre),i}function Dt(e,t,r,i){return wt(e,Mt(e,t),r,i)}function _t(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[gr(e,t)];var r=e.display.externalMeasured;return r&&t>=r.lineN&&t<r.lineN+r.size?r:void 0}function Mt(e,t){var r=Mn(t),i=_t(e,r);i&&!i.text?i=null:i&&i.changes&&_(e,i,r,P(e)),i||(i=Pt(e,t));var n=Ot(i,t,r);return{line:t,view:i,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function wt(e,t,r,i,n){t.before&&(r=-1);var o,s=r+(i||"");return t.cache.hasOwnProperty(s)?o=t.cache[s]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(bt(e,t.view,t.rect),t.hasHeights=!0),o=Gt(e,t,r,i),o.bogus||(t.cache[s]=o)),{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Gt(e,t,r,i){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>r?(o=0,s=1,a="left"):c>r?(o=r-p,s=o+1):(u==l.length-3||r==c&&l[u+3]>r)&&(s=c-p,o=s-1,r>=c&&(a="right")),null!=o){if(n=l[u+2],p==c&&i==(n.insertLeft?"left":"right")&&(a=i),"left"==i&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;)n=l[(u-=3)+2],a="left";if("right"==i&&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&&No(t.line.text.charAt(p+o));)--o;for(;c>p+s&&No(t.line.text.charAt(p+s));)++s;if(Jo&&9>es&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(Jo&&e.options.lineWrapping){var h=La(n,o,s).getClientRects();d=h.length?h["right"==i?h.length-1:0]:Is}else d=La(n,o,s).getBoundingClientRect()||Is;if(d.left||d.right||0==o)break;s=o,o-=1,a="right"}Jo&&11>es&&(d=kt(e.display.measure,d))}else{o>0&&(a=i="right");var h;d=e.options.lineWrapping&&(h=n.getClientRects()).length>1?h["right"==i?h.length-1:0]:n.getBoundingClientRect()}if(Jo&&9>es&&!o&&(!d||!d.left&&!d.right)){var E=n.parentNode.getClientRects()[0];d=E?{left:E.left,right:E.left+Zt(e.display),top:E.top,bottom:E.bottom}:Is}for(var f=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(f+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],L={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};return d.left||d.right||(L.bogus=!0),e.options.singleCursorHeightPerLine||(L.rtop=f,L.rbottom=m),L}function kt(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Go(e))return t;var r=screen.logicalXDPI/screen.deviceXDPI,i=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*r,right:t.right*r,top:t.top*i,bottom:t.bottom*i}}function Bt(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Ut(e){e.display.externalMeasure=null,To(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)Bt(e.display.view[t])}function Vt(e){Ut(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function Ht(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Ft(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function jt(e,t,r,i){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=on(t.widgets[n]);r.top+=o,r.bottom+=o}if("line"==i)return r;i||(i="local");var s=Gn(t);if("local"==i?s+=St(e.display):s-=e.display.viewOffset,"page"==i||"window"==i){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==i?0:Ft());var l=a.left+("window"==i?0:Ht());r.left+=l,r.right+=l}return r.top+=s,r.bottom+=s,r}function Wt(e,t,r){if("div"==r)return t;var i=t.left,n=t.top;if("page"==r)i-=Ht(),n-=Ft();else if("local"==r||!r){var o=e.display.sizer.getBoundingClientRect();i+=o.left,n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:i-s.left,top:n-s.top}}function qt(e,t,r,i,n){return i||(i=On(e.doc,t.line)),jt(e,i,Dt(e,i,t.ch,n),r)}function zt(e,t,r,i,n,o){function s(t,s){var a=wt(e,n,t,s?"right":"left",o);return s?a.left=a.right:a.right=a.left,jt(e,i,a,r)}function a(e,t){var r=l[t],i=r.level%2;return e==Bo(r)&&t&&r.level<l[t-1].level?(r=l[--t],e=Uo(r)-(r.level%2?0:1),i=!0):e==Uo(r)&&t<l.length-1&&r.level<l[t+1].level&&(r=l[++t],e=Bo(r)-r.level%2,i=!1),i&&e==r.to&&e>r.from?s(e-1):s(e,i)}i=i||On(e.doc,t.line),n||(n=Mt(e,i));var l=kn(i),u=t.ch;if(!l)return s(u);var p=zo(l,u),c=a(u,p);return null!=wa&&(c.other=a(u,wa)),c}function Xt(e,t){var r=0,t=J(e.doc,t);e.options.lineWrapping||(r=Zt(e.display)*t.ch);var i=On(e.doc,t.line),n=Gn(i)+St(e.display);return{left:r,right:r,top:n,bottom:n+i.height}}function Yt(e,t,r,i){var n=vs(e,t);return n.xRel=i,r&&(n.outside=!0),n}function Kt(e,t,r){var i=e.doc;if(r+=e.display.viewOffset,0>r)return Yt(i.first,0,!0,-1);var n=wn(i,r),o=i.first+i.size-1;if(n>o)return Yt(i.first+i.size-1,On(i,o).text.length,!0,1);0>t&&(t=0);for(var s=On(i,n);;){var a=$t(e,s,n,t,r),l=Ki(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=Mn(s=u.to.line)}}function $t(e,t,r,i,n){function o(i){var n=zt(e,vs(r,i),"line",t,u);return a=!0,s>n.bottom?n.left-l:s<n.top?n.left+l:(a=!1,n.left)}var s=n-Gn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Mt(e,t),p=kn(t),c=t.text.length,d=Vo(t),h=Ho(t),E=o(d),f=a,m=o(h),g=a;if(i>m)return Yt(r,h,g,1);for(;;){if(p?h==d||h==Yo(t,d,1):1>=h-d){for(var v=E>i||m-i>=i-E?d:h,x=i-(v==d?E:m);No(t.text.charAt(v));)++v;var N=Yt(r,v,v==d?f:g,-1>x?-1:x>1?1:0);return N}var L=Math.ceil(c/2),T=d+L;if(p){T=d;for(var I=0;L>I;++I)T=Yo(t,T,1)}var y=o(T);y>i?(h=T,m=y,(g=a)&&(m+=1e3),c=L):(d=T,E=y,f=a,c-=L)}}function Qt(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Ns){Ns=Lo("pre");for(var t=0;49>t;++t)Ns.appendChild(document.createTextNode("x")),Ns.appendChild(Lo("br"));Ns.appendChild(document.createTextNode("x"))}Io(e.measure,Ns);var r=Ns.offsetHeight/50;return r>3&&(e.cachedTextHeight=r),To(e.measure),r||1}function Zt(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=Lo("span","xxxxxxxxxx"),r=Lo("pre",[t]);Io(e.measure,r);var i=t.getBoundingClientRect(),n=(i.right-i.left)/10;return n>2&&(e.cachedCharWidth=n),n||10}function Jt(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:++As},ys?ys.ops.push(e.curOp):e.curOp.ownsGroup=ys={ops:[e.curOp],delayedCallbacks:[]}}function er(e){var t=e.delayedCallbacks,r=0;do{for(;r<t.length;r++)t[r]();for(var i=0;i<e.ops.length;i++){var n=e.ops[i];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(r<t.length)}function tr(e){var t=e.curOp,r=t.ownsGroup;if(r)try{er(r)}finally{ys=null;for(var i=0;i<r.ops.length;i++)r.ops[i].cm.curOp=null;rr(r)}}function rr(e){for(var t=e.ops,r=0;r<t.length;r++)ir(t[r]);for(var r=0;r<t.length;r++)nr(t[r]);for(var r=0;r<t.length;r++)or(t[r]);for(var r=0;r<t.length;r++)sr(t[r]);for(var r=0;r<t.length;r++)ar(t[r])}function ir(e){var t=e.cm,r=t.display;e.updateMaxLine&&h(t),e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<r.viewFrom||e.scrollToPos.to.line>=r.viewTo)||r.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new I(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function nr(e){e.updatedDisplay=e.mustUpdate&&y(e.cm,e.update)}function or(e){var t=e.cm,r=t.display;e.updatedDisplay&&b(t),e.barMeasure=m(t),r.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Dt(t,r.maxLine,r.maxLine.text.length).left+3,e.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+e.adjustWidthTo+ha-r.scroller.clientWidth)),(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=mt(t))}function sr(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft<t.doc.scrollLeft&&Hr(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0),t.display.maxLineChanged=!1),e.newSelectionNodes&&gt(t,e.newSelectionNodes),e.updatedDisplay&&C(t,e.barMeasure),(e.updatedDisplay||e.startHeight!=t.doc.height)&&g(t,e.barMeasure),e.selectionChanged&&Lt(t),t.state.focused&&e.updateInput&&yr(t,e.typing)}function ar(e){var t=e.cm,r=t.display,i=t.doc;if(null!=e.adjustWidthTo&&Math.abs(e.barMeasure.scrollWidth-t.display.scroller.scrollWidth)>1&&g(t),e.updatedDisplay&&A(t,e.update),null==r.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(r.wheelStartX=r.wheelStartY=null),null!=e.scrollTop&&(r.scroller.scrollTop!=e.scrollTop||e.forceScroll)){var n=Math.max(0,Math.min(r.scroller.scrollHeight-r.scroller.clientHeight,e.scrollTop));r.scroller.scrollTop=r.scrollbarV.scrollTop=i.scrollTop=n}if(null!=e.scrollLeft&&(r.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){var o=Math.max(0,Math.min(r.scroller.scrollWidth-r.scroller.clientWidth,e.scrollLeft));r.scroller.scrollLeft=r.scrollbarH.scrollLeft=i.scrollLeft=o,x(t)}if(e.scrollToPos){var s=Ei(t,J(i,e.scrollToPos.from),J(i,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&hi(t,s)}var a=e.maybeHiddenMarkers,l=e.maybeUnhiddenMarkers;if(a)for(var u=0;u<a.length;++u)a[u].lines.length||ca(a[u],"hide");if(l)for(var u=0;u<l.length;++u)l[u].lines.length&&ca(l[u],"unhide");r.wrapper.offsetHeight&&(i.scrollTop=t.display.scroller.scrollTop),e.updatedDisplay&&ts&&(t.options.lineWrapping&&R(t,e.barMeasure),e.barMeasure.scrollWidth>e.barMeasure.clientWidth&&e.barMeasure.scrollWidth<e.barMeasure.clientWidth+1&&!f(t)&&g(t)),e.changeObjs&&ca(t,"changes",t,e.changeObjs)}function lr(e,t){if(e.curOp)return t();Jt(e);try{return t()}finally{tr(e)}}function ur(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Jt(e);try{return t.apply(e,arguments)}finally{tr(e)}}}function pr(e){return function(){if(this.curOp)return e.apply(this,arguments);Jt(this);try{return e.apply(this,arguments)}finally{tr(this)}}}function cr(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Jt(t);try{return e.apply(this,arguments)}finally{tr(t)}}}function dr(e,t,r){this.line=t,this.rest=Zi(t),this.size=this.rest?Mn(co(this.rest))-r+1:1,this.node=this.text=null,this.hidden=tn(e,t)}function hr(e,t,r){for(var i,n=[],o=t;r>o;o=i){var s=new dr(e.doc,On(e.doc,o),o);i=o+s.size,n.push(s)}return n}function Er(e,t,r,i){null==t&&(t=e.doc.first),null==r&&(r=e.doc.first+e.doc.size),i||(i=0);var n=e.display;if(i&&r<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=n.viewTo)gs&&Ji(e.doc,t)<n.viewTo&&mr(e);else if(r<=n.viewFrom)gs&&en(e.doc,r+i)>n.viewFrom?mr(e):(n.viewFrom+=i,n.viewTo+=i);else if(t<=n.viewFrom&&r>=n.viewTo)mr(e);else if(t<=n.viewFrom){var o=vr(e,r,r+i,1);o?(n.view=n.view.slice(o.index),n.viewFrom=o.lineN,n.viewTo+=i):mr(e)}else if(r>=n.viewTo){var o=vr(e,t,t,-1);o?(n.view=n.view.slice(0,o.index),n.viewTo=o.lineN):mr(e)}else{var s=vr(e,t,t,-1),a=vr(e,r,r+i,1);s&&a?(n.view=n.view.slice(0,s.index).concat(hr(e,s.lineN,a.lineN)).concat(n.view.slice(a.index)),n.viewTo+=i):mr(e)}var l=n.externalMeasured;l&&(r<l.lineN?l.lineN+=i:t<l.lineN+l.size&&(n.externalMeasured=null))}function fr(e,t,r){e.curOp.viewChanged=!0;var i=e.display,n=e.display.externalMeasured;if(n&&t>=n.lineN&&t<n.lineN+n.size&&(i.externalMeasured=null),!(t<i.viewFrom||t>=i.viewTo)){var o=i.view[gr(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==ho(s,r)&&s.push(r)}}}function mr(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function gr(e,t){if(t>=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var r=e.display.view,i=0;i<r.length;i++)if(t-=r[i].size,0>t)return i}function vr(e,t,r,i){var n,o=gr(e,t),s=e.display.view;if(!gs||r==e.doc.first+e.doc.size)return{index:o,lineN:r};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(i>0){if(o==s.length-1)return null;n=l+s[o].size-t,o++}else n=l-t;t+=n,r+=n}for(;Ji(e.doc,r)!=r;){if(o==(0>i?0:s.length-1))return null;r+=i*s[o-(0>i?1:0)].size,o+=i}return{index:o,lineN:r}}function xr(e,t,r){var i=e.display,n=i.view;0==n.length||t>=i.viewTo||r<=i.viewFrom?(i.view=hr(e,t,r),i.viewFrom=t):(i.viewFrom>t?i.view=hr(e,t,i.viewFrom).concat(i.view):i.viewFrom<t&&(i.view=i.view.slice(gr(e,t))),i.viewFrom=t,i.viewTo<r?i.view=i.view.concat(hr(e,i.viewTo,r)):i.viewTo>r&&(i.view=i.view.slice(0,gr(e,r)))),i.viewTo=r}function Nr(e){for(var t=e.display.view,r=0,i=0;i<t.length;i++){var n=t[i];n.hidden||n.node&&!n.changes||++r}return r}function Lr(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ir(e),e.state.focused&&Lr(e)})}function Tr(e){function t(){var i=Ir(e);i||r?(e.display.pollingFast=!1,Lr(e)):(r=!0,e.display.poll.set(60,t))}var r=!1;e.display.pollingFast=!0,e.display.poll.set(20,t)}function Ir(e){var t=e.display.input,r=e.display.prevInput,i=e.doc;if(!e.state.focused||Pa(t)&&!r||Cr(e)||e.options.disableInput)return!1;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==r&&!e.somethingSelected())return!1;if(Jo&&es>=9&&e.display.inputHasSelection===n||cs&&/[\uf700-\uf7ff]/.test(n))return yr(e),!1;var o=!e.curOp;o&&Jt(e),e.display.shift=!1,8203!=n.charCodeAt(0)||i.sel!=e.display.selForContextMenu||r||(r="​");for(var s=0,a=Math.min(r.length,n.length);a>s&&r.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Oa(l),p=null;e.state.pasteIncoming&&i.sel.ranges.length>1&&(Ss&&Ss.join("\n")==l?p=i.sel.ranges.length%Ss.length==0&&Eo(Ss,Oa):u.length==i.sel.ranges.length&&(p=Eo(u,function(e){return[e]})));for(var c=i.sel.ranges.length-1;c>=0;c--){var d=i.sel.ranges[c],h=d.from(),E=d.to();s<r.length?h=vs(h.line,h.ch-(r.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(E=vs(E.line,Math.min(On(i,E.line).text.length,E.ch+co(u).length)));var f=e.curOp.updateInput,m={from:h,to:E,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};if(si(e.doc,m),ro(e,"inputRead",e,m),l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||i.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Ds(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Ni(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(On(i,v.line).text.slice(0,v.ch))&&Ni(e,v.line,"smart")}}return vi(e),e.curOp.updateInput=f,e.curOp.typing=!0,n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n,o&&tr(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function yr(e,t){var r,i,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();r=Da&&(o.to().line-o.from().line>100||(i=e.getSelection()).length>1e3);var s=r?"-":i||e.getSelection();e.display.input.value=s,e.state.focused&&Na(e.display.input),Jo&&es>=9&&(e.display.inputHasSelection=s)}else t||(e.display.prevInput=e.display.input.value="",Jo&&es>=9&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=r}function Ar(e){"nocursor"==e.options.readOnly||ps&&Ao()==e.display.input||e.display.input.focus()}function Sr(e){e.state.focused||(Ar(e),Qr(e))}function Cr(e){return e.options.readOnly||e.doc.cantEdit}function Rr(e){function t(){e.state.focused&&setTimeout(go(Ar,e),0)}function r(t){no(e,t)||la(t)}function i(t){if(e.somethingSelected())Ss=e.getSelections(),n.inaccurateSelection&&(n.prevInput="",n.inaccurateSelection=!1,n.input.value=Ss.join("\n"),Na(n.input));else{for(var r=[],i=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:vs(s,0),head:vs(s+1,0)};i.push(a),r.push(e.getRange(a.anchor,a.head))}"cut"==t.type?e.setSelections(i,null,fa):(n.prevInput="",n.input.value=r.join("\n"),Na(n.input)),Ss=r}"cut"==t.type&&(e.state.cutIncoming=!0)}var n=e.display;ua(n.scroller,"mousedown",ur(e,Dr)),Jo&&11>es?ua(n.scroller,"dblclick",ur(e,function(t){if(!no(e,t)){var r=Pr(e,t);if(r&&!kr(e,t)&&!Or(e.display,t)){sa(t);var i=e.findWordAt(r);nt(e.doc,i.anchor,i.head)}}})):ua(n.scroller,"dblclick",function(t){no(e,t)||sa(t)}),ua(n.lineSpace,"selectstart",function(e){Or(n,e)||sa(e)}),fs||ua(n.scroller,"contextmenu",function(t){Jr(e,t)}),ua(n.scroller,"scroll",function(){n.scroller.clientHeight&&(Vr(e,n.scroller.scrollTop),Hr(e,n.scroller.scrollLeft,!0),ca(e,"scroll",e))}),ua(n.scrollbarV,"scroll",function(){n.scroller.clientHeight&&Vr(e,n.scrollbarV.scrollTop)}),ua(n.scrollbarH,"scroll",function(){n.scroller.clientHeight&&Hr(e,n.scrollbarH.scrollLeft)}),ua(n.scroller,"mousewheel",function(t){Fr(e,t)}),ua(n.scroller,"DOMMouseScroll",function(t){Fr(e,t)}),ua(n.scrollbarH,"mousedown",t),ua(n.scrollbarV,"mousedown",t),ua(n.wrapper,"scroll",function(){n.wrapper.scrollTop=n.wrapper.scrollLeft=0}),ua(n.input,"keyup",function(t){Kr.call(e,t)}),ua(n.input,"input",function(){Jo&&es>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),Tr(e)}),ua(n.input,"keydown",ur(e,Xr)),ua(n.input,"keypress",ur(e,$r)),ua(n.input,"focus",go(Qr,e)),ua(n.input,"blur",go(Zr,e)),e.options.dragDrop&&(ua(n.scroller,"dragstart",function(t){Ur(e,t)}),ua(n.scroller,"dragenter",r),ua(n.scroller,"dragover",r),ua(n.scroller,"drop",ur(e,Br))),ua(n.scroller,"paste",function(t){Or(n,t)||(e.state.pasteIncoming=!0,Ar(e),Tr(e))}),ua(n.input,"paste",function(){if(ts&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=n.input.selectionStart,r=n.input.selectionEnd;n.input.value+="$",n.input.selectionEnd=r,n.input.selectionStart=t,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,Tr(e)}),ua(n.input,"cut",i),ua(n.input,"copy",i),ss&&ua(n.sizer,"mouseup",function(){Ao()==n.input&&n.input.blur(),Ar(e)})}function br(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function Or(e,t){for(var r=eo(t);r!=e.wrapper;r=r.parentNode)if(!r||r.ignoreEvents||r.parentNode==e.sizer&&r!=e.mover)return!0}function Pr(e,t,r,i){var n=e.display;if(!r){var o=eo(t);if(o==n.scrollbarH||o==n.scrollbarV||o==n.scrollbarFiller||o==n.gutterFiller)return null}var s,a,l=n.lineSpace.getBoundingClientRect();try{s=t.clientX-l.left,a=t.clientY-l.top}catch(t){return null}var u,p=Kt(e,s,a);if(i&&1==p.xRel&&(u=On(e.doc,p.line).text).length==p.ch){var c=va(u,u.length,e.options.tabSize)-u.length;p=vs(p.line,Math.max(0,Math.round((s-Rt(e.display).left)/Zt(e.display))-c))}return p}function Dr(e){if(!no(this,e)){var t=this,r=t.display;if(r.shift=e.shiftKey,Or(r,e))return void(ts||(r.scroller.draggable=!1,setTimeout(function(){r.scroller.draggable=!0},100)));if(!kr(t,e)){var i=Pr(t,e);switch(window.focus(),to(e)){case 1:i?_r(t,e,i):eo(e)==r.scroller&&sa(e);break;case 2:ts&&(t.state.lastMiddleDown=+new Date),i&&nt(t.doc,i),setTimeout(go(Ar,t),20),sa(e);break;case 3:fs&&Jr(t,e)}}}}function _r(e,t,r){setTimeout(go(Sr,e),0);var i,n=+new Date;Ts&&Ts.time>n-400&&0==xs(Ts.pos,r)?i="triple":Ls&&Ls.time>n-400&&0==xs(Ls.pos,r)?(i="double",Ts={time:n,pos:r}):(i="single",Ls={time:n,pos:r});var o=e.doc.sel,s=cs?t.metaKey:t.ctrlKey;e.options.dragDrop&&ba&&!Cr(e)&&"single"==i&&o.contains(r)>-1&&o.somethingSelected()?Mr(e,t,r,s):wr(e,t,r,i,s)}function Mr(e,t,r,i){var n=e.display,o=ur(e,function(s){ts&&(n.scroller.draggable=!1),e.state.draggingText=!1,pa(document,"mouseup",o),pa(n.scroller,"drop",o),Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10&&(sa(s),i||nt(e.doc,r),Ar(e),Jo&&9==es&&setTimeout(function(){document.body.focus(),Ar(e)},20))});ts&&(n.scroller.draggable=!0),e.state.draggingText=o,n.scroller.dragDrop&&n.scroller.dragDrop(),ua(document,"mouseup",o),ua(n.scroller,"drop",o)}function wr(e,t,r,i,n){function o(t){if(0!=xs(f,t))if(f=t,"rect"==i){for(var n=[],o=e.options.tabSize,s=va(On(u,r.line).text,r.ch,o),a=va(On(u,t.line).text,t.ch,o),l=Math.min(s,a),h=Math.max(s,a),E=Math.min(r.line,t.line),m=Math.min(e.lastLine(),Math.max(r.line,t.line));m>=E;E++){var g=On(u,E).text,v=uo(g,l,o);l==h?n.push(new K(vs(E,v),vs(E,v))):g.length>v&&n.push(new K(vs(E,v),vs(E,uo(g,h,o))))}n.length||n.push(new K(r,r)),pt(u,$(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var x=p,N=x.anchor,L=t;if("single"!=i){if("double"==i)var T=e.findWordAt(t);else var T=new K(vs(t.line,0),J(u,vs(t.line+1,0)));xs(T.anchor,N)>0?(L=T.head,N=X(x.from(),T.anchor)):(L=T.anchor,N=z(x.to(),T.head))}var n=d.ranges.slice(0);n[c]=new K(J(u,N),L),pt(u,$(n,c),ma)}}function s(t){var r=++g,n=Pr(e,t,!0,"rect"==i);if(n)if(0!=xs(n,f)){Sr(e),o(n);var a=v(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(ur(e,function(){g==r&&s(t)}),150)}else{var p=t.clientY<m.top?-20:t.clientY>m.bottom?20:0;p&&setTimeout(ur(e,function(){g==r&&(l.scroller.scrollTop+=p,s(t))}),50)}}function a(t){g=1/0,sa(t),Ar(e),pa(document,"mousemove",x),pa(document,"mouseup",N),u.history.lastSelOrigin=null}var l=e.display,u=e.doc;sa(t);var p,c,d=u.sel;if(n&&!t.shiftKey?(c=u.sel.contains(r),p=c>-1?u.sel.ranges[c]:new K(r,r)):p=u.sel.primary(),t.altKey)i="rect",n||(p=new K(r,r)),r=Pr(e,t,!0,!0),c=-1;else if("double"==i){var h=e.findWordAt(r);p=e.display.shift||u.extend?it(u,p,h.anchor,h.head):h}else if("triple"==i){var E=new K(vs(r.line,0),J(u,vs(r.line+1,0)));p=e.display.shift||u.extend?it(u,p,E.anchor,E.head):E}else p=it(u,p,r);n?c>-1?st(u,c,p,ma):(c=u.sel.ranges.length,pt(u,$(u.sel.ranges.concat([p]),c),{scroll:!1,origin:"*mouse"})):(c=0,pt(u,new Y([p],0),ma),d=u.sel);var f=r,m=l.wrapper.getBoundingClientRect(),g=0,x=ur(e,function(e){to(e)?s(e):a(e)}),N=ur(e,a);ua(document,"mousemove",x),ua(document,"mouseup",N)}function Gr(e,t,r,i,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;i&&sa(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!so(e,r))return Jn(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=wn(e.doc,s),d=e.options.gutters[u];return n(e,r,e,c,d,t),Jn(t)}}}function kr(e,t){return Gr(e,t,"gutterClick",!0,ro)}function Br(e){var t=this;if(!no(t,e)&&!Or(t.display,e)){sa(e),Jo&&(Cs=+new Date);var r=Pr(t,e,!0),i=e.dataTransfer.files;if(r&&!Cr(t))if(i&&i.length&&window.FileReader&&window.File)for(var n=i.length,o=Array(n),s=0,a=function(e,i){var a=new FileReader;a.onload=ur(t,function(){if(o[i]=a.result,++s==n){r=J(t.doc,r);var e={from:r,to:r,text:Oa(o.join("\n")),origin:"paste"};si(t.doc,e),ut(t.doc,Q(r,Ds(e)))}}),a.readAsText(e)},l=0;n>l;++l)a(i[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(r)>-1)return t.state.draggingText(e),void setTimeout(go(Ar,t),20);try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(cs?e.metaKey:e.ctrlKey))var u=t.listSelections();if(ct(t.doc,Q(r,r)),u)for(var l=0;l<u.length;++l)di(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste"),Ar(t)}}catch(e){}}}}function Ur(e,t){if(Jo&&(!e.state.draggingText||+new Date-Cs<100))return void la(t);if(!no(e,t)&&!Or(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.setDragImage&&!os)){var r=Lo("img",null,null,"position: fixed; left: 0; top: 0;");r.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",ns&&(r.width=r.height=1,e.display.wrapper.appendChild(r),r._top=r.offsetTop),t.dataTransfer.setDragImage(r,0,0),ns&&r.parentNode.removeChild(r)}}function Vr(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,$o||S(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbarV.scrollTop!=t&&(e.display.scrollbarV.scrollTop=t),$o&&S(e),Tt(e,100))}function Hr(e,t,r){(r?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,x(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbarH.scrollLeft!=t&&(e.display.scrollbarH.scrollLeft=t))}function Fr(e,t){var r=t.wheelDeltaX,i=t.wheelDeltaY;null==r&&t.detail&&t.axis==t.HORIZONTAL_AXIS&&(r=t.detail),null==i&&t.detail&&t.axis==t.VERTICAL_AXIS?i=t.detail:null==i&&(i=t.wheelDelta);var n=e.display,o=n.scroller;if(r&&o.scrollWidth>o.clientWidth||i&&o.scrollHeight>o.clientHeight){if(i&&cs&&ts)e:for(var s=t.target,a=n.view;s!=o;s=s.parentNode)for(var l=0;l<a.length;l++)if(a[l].node==s){e.display.currentWheelTarget=s;break e}if(r&&!$o&&!ns&&null!=bs)return i&&Vr(e,Math.max(0,Math.min(o.scrollTop+i*bs,o.scrollHeight-o.clientHeight))),Hr(e,Math.max(0,Math.min(o.scrollLeft+r*bs,o.scrollWidth-o.clientWidth))),sa(t),void(n.wheelStartX=null);if(i&&null!=bs){var u=i*bs,p=e.doc.scrollTop,c=p+n.wrapper.clientHeight;0>u?p=Math.max(0,p+u-50):c=Math.min(e.doc.height,c+u+50),S(e,{top:p,bottom:c})}20>Rs&&(null==n.wheelStartX?(n.wheelStartX=o.scrollLeft,n.wheelStartY=o.scrollTop,n.wheelDX=r,n.wheelDY=i,setTimeout(function(){if(null!=n.wheelStartX){var e=o.scrollLeft-n.wheelStartX,t=o.scrollTop-n.wheelStartY,r=t&&n.wheelDY&&t/n.wheelDY||e&&n.wheelDX&&e/n.wheelDX;n.wheelStartX=n.wheelStartY=null,r&&(bs=(bs*Rs+r)/(Rs+1),++Rs)}},200)):(n.wheelDX+=r,n.wheelDY+=i))}}function jr(e,t,r){if("string"==typeof t&&(t=js[t],!t))return!1;e.display.pollingFast&&Ir(e)&&(e.display.pollingFast=!1);var i=e.display.shift,n=!1;try{Cr(e)&&(e.state.suppressEdits=!0),r&&(e.display.shift=!1),n=t(e)!=Ea}finally{e.display.shift=i,e.state.suppressEdits=!1}return n}function Wr(e){var t=e.state.keyMaps.slice(0);return e.options.extraKeys&&t.push(e.options.extraKeys),t.push(e.options.keyMap),t}function qr(e,t){var r=Si(e.options.keyMap),i=r.auto;clearTimeout(Os),i&&!zs(t)&&(Os=setTimeout(function(){Si(e.options.keyMap)==r&&(e.options.keyMap=i.call?i.call(null,e):i,a(e))},50));var n=Xs(t,!0),o=!1;if(!n)return!1;var s=Wr(e);return o=t.shiftKey?qs("Shift-"+n,s,function(t){return jr(e,t,!0)})||qs(n,s,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?jr(e,t):void 0}):qs(n,s,function(t){return jr(e,t)}),o&&(sa(t),Lt(e),ro(e,"keyHandled",e,n,t)),o}function zr(e,t,r){var i=qs("'"+r+"'",Wr(e),function(t){return jr(e,t,!0)});return i&&(sa(t),Lt(e),ro(e,"keyHandled",e,"'"+r+"'",t)),i}function Xr(e){var t=this;if(Sr(t),!no(t,e)){Jo&&11>es&&27==e.keyCode&&(e.returnValue=!1);var r=e.keyCode;t.display.shift=16==r||e.shiftKey;var i=qr(t,e);ns&&(Ps=i?r:null,!i&&88==r&&!Da&&(cs?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=r||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||Yr(t)}}function Yr(e){function t(e){18!=e.keyCode&&e.altKey||(Co(r,"CodeMirror-crosshair"),pa(document,"keyup",t),pa(document,"mouseover",t))}var r=e.display.lineDiv;Ro(r,"CodeMirror-crosshair"),ua(document,"keyup",t),ua(document,"mouseover",t)}function Kr(e){16==e.keyCode&&(this.doc.sel.shift=!1),no(this,e)}function $r(e){var t=this;if(!(no(t,e)||e.ctrlKey&&!e.altKey||cs&&e.metaKey)){var r=e.keyCode,i=e.charCode;if(ns&&r==Ps)return Ps=null,void sa(e);if(!(ns&&(!e.which||e.which<10)||ss)||!qr(t,e)){var n=String.fromCharCode(null==i?r:i);zr(t,e,n)||(Jo&&es>=9&&(t.display.inputHasSelection=null),Tr(t))}}}function Qr(e){"nocursor"!=e.options.readOnly&&(e.state.focused||(ca(e,"focus",e),e.state.focused=!0,Ro(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(yr(e),ts&&setTimeout(go(yr,e,!0),0))),Lr(e),Lt(e))}function Zr(e){e.state.focused&&(ca(e,"blur",e),e.state.focused=!1,Co(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function Jr(e,t){function r(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),r=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​",n.input.selectionStart=1,n.input.selectionEnd=r.length,n.selForContextMenu=e.doc.sel}}function i(){if(n.inputDiv.style.position="relative",n.input.style.cssText=l,Jo&&9>es&&(n.scrollbarV.scrollTop=n.scroller.scrollTop=s),Lr(e),null!=n.input.selectionStart){(!Jo||Jo&&9>es)&&r();var t=0,i=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?ur(e,js.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(i,500):yr(e)};n.detectingSelectAll=setTimeout(i,200)}}if(!no(e,t,"contextmenu")){var n=e.display;if(!Or(n,t)&&!ei(e,t)){var o=Pr(e,t),s=n.scroller.scrollTop;if(o&&!ns){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&ur(e,pt)(e.doc,Q(o),fa);var l=n.input.style.cssText;if(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: "+(Jo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",ts)var u=window.scrollY;if(Ar(e),ts&&window.scrollTo(null,u),yr(e),e.somethingSelected()||(n.input.value=n.prevInput=" "),n.selForContextMenu=e.doc.sel,clearTimeout(n.detectingSelectAll),Jo&&es>=9&&r(),fs){la(t);var p=function(){pa(window,"mouseup",p),setTimeout(i,20)};ua(window,"mouseup",p)}else setTimeout(i,50)}}}}function ei(e,t){return so(e,"gutterContextMenu")?Gr(e,t,"gutterContextMenu",!1,ca):!1}function ti(e,t){if(xs(e,t.from)<0)return e;if(xs(e,t.to)<=0)return Ds(t);var r=e.line+t.text.length-(t.to.line-t.from.line)-1,i=e.ch;return e.line==t.to.line&&(i+=Ds(t).ch-t.to.ch),vs(r,i)}function ri(e,t){for(var r=[],i=0;i<e.sel.ranges.length;i++){var n=e.sel.ranges[i];r.push(new K(ti(n.anchor,t),ti(n.head,t)))}return $(r,e.sel.primIndex)}function ii(e,t,r){return e.line==t.line?vs(r.line,e.ch-t.ch+r.ch):vs(r.line+(e.line-t.line),e.ch)}function ni(e,t,r){for(var i=[],n=vs(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ii(a.from,n,o),u=ii(Ds(a),n,o);if(n=a.to,o=u,"around"==r){var p=e.sel.ranges[s],c=xs(p.head,p.anchor)<0;i[s]=new K(c?u:l,c?l:u)}else i[s]=new K(l,l)}return new Y(i,e.sel.primIndex)}function oi(e,t,r){var i={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};return r&&(i.update=function(t,r,i,n){t&&(this.from=J(e,t)),r&&(this.to=J(e,r)),i&&(this.text=i),void 0!==n&&(this.origin=n)}),ca(e,"beforeChange",e,i),e.cm&&ca(e.cm,"beforeChange",e.cm,i),i.canceled?null:{from:i.from,to:i.to,text:i.text,origin:i.origin}}function si(e,t,r){if(e.cm){if(!e.cm.curOp)return ur(e.cm,si)(e,t,r);if(e.cm.state.suppressEdits)return}if(!(so(e,"beforeChange")||e.cm&&so(e.cm,"beforeChange"))||(t=oi(e,t,!0))){var i=ms&&!r&&Hi(e,t.from,t.to);if(i)for(var n=i.length-1;n>=0;--n)ai(e,{from:i[n].from,to:i[n].to,text:n?[""]:t.text});else ai(e,t)}}function ai(e,t){if(1!=t.text.length||""!=t.text[0]||0!=xs(t.from,t.to)){var r=ri(e,t);Fn(e,t,r,e.cm?e.cm.curOp.id:0/0),pi(e,t,r,Bi(e,t));var i=[];Rn(e,function(e,r){r||-1!=ho(i,e.history)||(Zn(e.history,t),i.push(e.history)),pi(e,t,null,Bi(e,t))})}}function li(e,t,r){if(!e.cm||!e.cm.state.suppressEdits){for(var i,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&&(i=s[l],r?!i.ranges||i.equals(e.sel):i.ranges);l++);if(l!=s.length){for(n.lastOrigin=n.lastSelOrigin=null;i=s.pop(),i.ranges;){if(qn(i,a),r&&!i.equals(e.sel))return void pt(e,i,{clearRedo:!1});o=i}var u=[];qn(o,a),a.push({changes:u,generation:n.generation}),n.generation=i.generation||++n.maxGeneration;for(var p=so(e,"beforeChange")||e.cm&&so(e.cm,"beforeChange"),l=i.changes.length-1;l>=0;--l){var c=i.changes[l];if(c.origin=t,p&&!oi(e,c,!1))return void(s.length=0);u.push(Un(e,c));var d=l?ri(e,c):co(s);pi(e,c,d,Vi(e,c)),!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Ds(c)});var h=[];Rn(e,function(e,t){t||-1!=ho(h,e.history)||(Zn(e.history,c),h.push(e.history)),pi(e,c,null,Vi(e,c))})}}}}function ui(e,t){if(0!=t&&(e.first+=t,e.sel=new Y(Eo(e.sel.ranges,function(e){return new K(vs(e.anchor.line+t,e.anchor.ch),vs(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){Er(e.cm,e.first,e.first-t,t);for(var r=e.cm.display,i=r.viewFrom;i<r.viewTo;i++)fr(e.cm,i,"gutter")}}function pi(e,t,r,i){if(e.cm&&!e.cm.curOp)return ur(e.cm,pi)(e,t,r,i);if(t.to.line<e.first)return void ui(e,t.text.length-1-(t.to.line-t.from.line));if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);ui(e,n),t={from:vs(e.first,0),to:vs(t.to.line+n,t.to.ch),text:[co(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:vs(o,On(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Pn(e,t.from,t.to),r||(r=ri(e,t)),e.cm?ci(e.cm,t,i):An(e,t,i),ct(e,r,fa)}}function ci(e,t,r){var i=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;e.options.lineWrapping||(u=Mn(Qi(On(i,s.line))),i.iter(u,a.line+1,function(e){return e==n.maxLine?(l=!0,!0):void 0})),i.sel.contains(t.from,t.to)>-1&&oo(e),An(i,t,r,o(e)),e.options.lineWrapping||(i.iter(u,s.line+t.text.length,function(e){var t=d(e);t>n.maxLineLength&&(n.maxLine=e,n.maxLineLength=t,n.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),i.frontier=Math.min(i.frontier,s.line),Tt(e,400);var p=t.text.length-(a.line-s.line)-1;s.line!=a.line||1!=t.text.length||yn(e.doc,t)?Er(e,s.line,a.line+1,p):fr(e,s.line,"text");var c=so(e,"changes"),h=so(e,"change");if(h||c){var E={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};h&&ro(e,"change",e,E),c&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(E)}e.display.selForContextMenu=null}function di(e,t,r,i,n){if(i||(i=r),xs(i,r)<0){var o=i;i=r,r=o}"string"==typeof t&&(t=Oa(t)),si(e,{from:r,to:i,text:t,origin:n})}function hi(e,t){var r=e.display,i=r.sizer.getBoundingClientRect(),n=null;if(t.top+i.top<0?n=!0:t.bottom+i.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1),null!=n&&!ls){var o=Lo("div","​",null,"position: absolute; top: "+(t.top-r.viewOffset-St(e.display))+"px; height: "+(t.bottom-t.top+ha)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(n),e.display.lineSpace.removeChild(o)}}function Ei(e,t,r,i){null==i&&(i=0);for(var n=0;5>n;n++){var o=!1,s=zt(e,t),a=r&&r!=t?zt(e,r):s,l=mi(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-i,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+i),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop&&(Vr(e,l.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(o=!0)),null!=l.scrollLeft&&(Hr(e,l.scrollLeft),Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)),!o)return s}}function fi(e,t,r,i,n){var o=mi(e,t,r,i,n);null!=o.scrollTop&&Vr(e,o.scrollTop),null!=o.scrollLeft&&Hr(e,o.scrollLeft)}function mi(e,t,r,i,n){var o=e.display,s=Qt(e.display);0>r&&(r=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-ha,u={};n-r>l&&(n=r+l);var p=e.doc.height+Ct(o),c=s>r,d=n>p-s;if(a>r)u.scrollTop=c?0:r;else if(n>a+l){var h=Math.min(r,(d?p:n)-l);h!=a&&(u.scrollTop=h)}var E=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,f=o.scroller.clientWidth-ha-o.gutters.offsetWidth,m=i-t>f;return m&&(i=t+f),10>t?u.scrollLeft=0:E>t?u.scrollLeft=Math.max(0,t-(m?0:10)):i>f+E-3&&(u.scrollLeft=i+(m?0:10)-f),u}function gi(e,t,r){(null!=t||null!=r)&&xi(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=r&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+r)}function vi(e){xi(e);var t=e.getCursor(),r=t,i=t;e.options.lineWrapping||(r=t.ch?vs(t.line,t.ch-1):t,i=vs(t.line,t.ch+1)),e.curOp.scrollToPos={from:r,to:i,margin:e.options.cursorScrollMargin,isCursor:!0}}function xi(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var r=Xt(e,t.from),i=Xt(e,t.to),n=mi(e,Math.min(r.left,i.left),Math.min(r.top,i.top)-t.margin,Math.max(r.right,i.right),Math.max(r.bottom,i.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Ni(e,t,r,i){var n,o=e.doc;null==r&&(r="add"),"smart"==r&&(o.mode.indent?n=At(e,t):r="prev");var s=e.options.tabSize,a=On(o,t),l=va(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(i||/\S/.test(a.text)){if("smart"==r&&(u=o.mode.indent(n,a.text.slice(p.length),a.text),u==Ea||u>150)){if(!i)return;r="prev"}}else u=0,r="not";"prev"==r?u=t>o.first?va(On(o,t-1).text,null,s):0:"add"==r?u=l+e.options.indentUnit:"subtract"==r?u=l-e.options.indentUnit:"number"==typeof r&&(u=l+r),u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var h=Math.floor(u/s);h;--h)d+=s,c+=" ";if(u>d&&(c+=po(u-d)),c!=p)di(o,c,vs(t,0),vs(t,p.length),"+input");else for(var h=0;h<o.sel.ranges.length;h++){var E=o.sel.ranges[h];if(E.head.line==t&&E.head.ch<p.length){var d=vs(t,p.length);st(o,h,new K(d,d));break}}a.stateAfter=null}function Li(e,t,r,i){var n=t,o=t;return"number"==typeof t?o=On(e,Z(e,t)):n=Mn(t),null==n?null:(i(o,n)&&e.cm&&fr(e.cm,n,r),o)}function Ti(e,t){for(var r=e.doc.sel.ranges,i=[],n=0;n<r.length;n++){for(var o=t(r[n]);i.length&&xs(o.from,co(i).to)<=0;){var s=i.pop();if(xs(s.from,o.from)<0){o.from=s.from;break}}i.push(o)}lr(e,function(){for(var t=i.length-1;t>=0;t--)di(e.doc,"",i[t].from,i[t].to,"+delete");vi(e)})}function Ii(e,t,r,i,n){function o(){var t=a+r;return t<e.first||t>=e.first+e.size?c=!1:(a=t,p=On(e,t))}function s(e){var t=(n?Yo:Ko)(p,l,r,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>r?Ho:Vo)(p):0>r?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=r,p=On(e,a),c=!0;if("char"==i)s();else if("column"==i)s(!0);else if("word"==i||"group"==i)for(var d=null,h="group"==i,E=e.cm&&e.cm.getHelper(t,"wordChars"),f=!0;!(0>r)||s(!f);f=!1){var m=p.text.charAt(l)||"\n",g=vo(m,E)?"w":h&&"\n"==m?"n":!h||/\s/.test(m)?null:"p";if(!h||f||g||(g="s"),d&&d!=g){0>r&&(r=1,s());break}if(g&&(d=g),r>0&&!s(!f))break}var v=ft(e,vs(a,l),u,!0);return c||(v.hitSide=!0),v}function yi(e,t,r,i){var n,o=e.doc,s=t.left;if("page"==i){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+r*(a-(0>r?1.5:.5)*Qt(e.display))}else"line"==i&&(n=r>0?t.bottom+3:t.top-3);for(;;){var l=Kt(e,s,n);if(!l.outside)break;if(0>r?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*r}return l}function Ai(t,r,i,n){e.defaults[t]=r,i&&(Ms[t]=n?function(e,t,r){r!=ws&&i(e,t,r)}:i)}function Si(e){return"string"==typeof e?Ws[e]:e}function Ci(e,t,r,i,n){if(i&&i.shared)return Ri(e,t,r,i,n);if(e.cm&&!e.cm.curOp)return ur(e.cm,Ci)(e,t,r,i,n);var o=new Ks(e,n),s=xs(t,r);if(i&&mo(i,o,!1),s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=Lo("span",[o.replacedWith],"CodeMirror-widget"),i.handleMouseEvents||(o.widgetNode.ignoreEvents=!0),i.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if($i(e,t.line,t,r,o)||t.line!=r.line&&$i(e,r.line,t,r,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");gs=!0}o.addToHistory&&Fn(e,{from:t,to:r,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;if(e.iter(l,r.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&Qi(e)==u.display.maxLine&&(a=!0),o.collapsed&&l!=t.line&&_n(e,0),wi(e,new Di(o,l==t.line?t.ch:null,l==r.line?r.ch:null)),++l}),o.collapsed&&e.iter(t.line,r.line+1,function(t){tn(e,t)&&_n(t,0)}),o.clearOnEnter&&ua(o,"beforeCursorEnter",function(){o.clear()}),o.readOnly&&(ms=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++$s,o.atomic=!0),u){if(a&&(u.curOp.updateMaxLine=!0),o.collapsed)Er(u,t.line,r.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var p=t.line;p<=r.line;p++)fr(u,p,"text");o.atomic&&ht(u.doc),ro(u,"markerAdded",u,o)}return o}function Ri(e,t,r,i,n){i=mo(i),i.shared=!1;var o=[Ci(e,t,r,i,n)],s=o[0],a=i.widgetNode;return Rn(e,function(e){a&&(i.widgetNode=a.cloneNode(!0)),o.push(Ci(e,J(e,t),J(e,r),i,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=co(o)}),new Qs(o,s)}function bi(e){return e.findMarks(vs(e.first,0),e.clipPos(vs(e.lastLine())),function(e){return e.parent})}function Oi(e,t){for(var r=0;r<t.length;r++){var i=t[r],n=i.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(xs(o,s)){var a=Ci(e,o,s,i.primary,i.primary.type);i.markers.push(a),a.parent=i}}}function Pi(e){for(var t=0;t<e.length;t++){var r=e[t],i=[r.primary.doc];Rn(r.primary.doc,function(e){i.push(e)});for(var n=0;n<r.markers.length;n++){var o=r.markers[n];-1==ho(i,o.doc)&&(o.parent=null,r.markers.splice(n--,1))}}}function Di(e,t,r){this.marker=e,this.from=t,this.to=r}function _i(e,t){if(e)for(var r=0;r<e.length;++r){var i=e[r];if(i.marker==t)return i}}function Mi(e,t){for(var r,i=0;i<e.length;++i)e[i]!=t&&(r||(r=[])).push(e[i]);return r}function wi(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}function Gi(e,t,r){if(e)for(var i,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&&(!r||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(i||(i=[])).push(new Di(s,o.from,l?null:o.to))}}return i}function ki(e,t,r){if(e)for(var i,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&&(!r||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(i||(i=[])).push(new Di(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return i}function Bi(e,t){var r=tt(e,t.from.line)&&On(e,t.from.line).markedSpans,i=tt(e,t.to.line)&&On(e,t.to.line).markedSpans;if(!r&&!i)return null;var n=t.from.ch,o=t.to.ch,s=0==xs(t.from,t.to),a=Gi(r,n,s),l=ki(i,o,s),u=1==t.text.length,p=co(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 h=_i(l,d.marker);h?u&&(d.to=null==h.to?null:h.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];if(null!=d.to&&(d.to+=p),null==d.from){var h=_i(a,d.marker);h||(d.from=p,u&&(a||(a=[])).push(d))}else d.from+=p,u&&(a||(a=[])).push(d)}a&&(a=Ui(a)),l&&l!=a&&(l=Ui(l));var E=[a];if(!u){var f,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(f||(f=[])).push(new Di(a[c].marker,null,null));for(var c=0;m>c;++c)E.push(f);E.push(l)}return E}function Ui(e){for(var t=0;t<e.length;++t){var r=e[t];null!=r.from&&r.from==r.to&&r.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Vi(e,t){var r=Yn(e,t),i=Bi(e,t);if(!r)return i;if(!i)return r;for(var n=0;n<r.length;++n){var o=r[n],s=i[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&&(r[n]=s)}return r}function Hi(e,t,r){var i=null;if(e.iter(t.line,r.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var r=e.markedSpans[t].marker;!r.readOnly||i&&-1!=ho(i,r)||(i||(i=[])).push(r)}}),!i)return null;for(var n=[{from:t,to:r}],o=0;o<i.length;++o)for(var s=i[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(xs(u.to,a.from)<0||xs(u.from,a.to)>0)){var p=[l,1],c=xs(u.from,a.from),d=xs(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 Fi(e){var t=e.markedSpans;if(t){for(var r=0;r<t.length;++r)t[r].marker.detachLine(e);e.markedSpans=null}}function ji(e,t){if(t){for(var r=0;r<t.length;++r)t[r].marker.attachLine(e);e.markedSpans=t}}function Wi(e){return e.inclusiveLeft?-1:0}function qi(e){return e.inclusiveRight?1:0}function zi(e,t){var r=e.lines.length-t.lines.length;if(0!=r)return r;var i=e.find(),n=t.find(),o=xs(i.from,n.from)||Wi(e)-Wi(t);if(o)return-o;var s=xs(i.to,n.to)||qi(e)-qi(t);return s?s:t.id-e.id}function Xi(e,t){var r,i=gs&&e.markedSpans;if(i)for(var n,o=0;o<i.length;++o)n=i[o],n.marker.collapsed&&null==(t?n.from:n.to)&&(!r||zi(r,n.marker)<0)&&(r=n.marker);return r}function Yi(e){return Xi(e,!0)}function Ki(e){return Xi(e,!1)}function $i(e,t,r,i,n){var o=On(e,t),s=gs&&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=xs(u.from,r)||Wi(l.marker)-Wi(n),c=xs(u.to,i)||qi(l.marker)-qi(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(xs(u.to,r)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(xs(u.from,i)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function Qi(e){for(var t;t=Yi(e);)e=t.find(-1,!0).line;return e}function Zi(e){for(var t,r;t=Ki(e);)e=t.find(1,!0).line,(r||(r=[])).push(e);return r}function Ji(e,t){var r=On(e,t),i=Qi(r);return r==i?t:Mn(i)}function en(e,t){if(t>e.lastLine())return t;var r,i=On(e,t);if(!tn(e,i))return t;for(;r=Ki(i);)i=r.find(1,!0).line;return Mn(i)+1}function tn(e,t){var r=gs&&t.markedSpans;if(r)for(var i,n=0;n<r.length;++n)if(i=r[n],i.marker.collapsed){if(null==i.from)return!0;if(!i.marker.widgetNode&&0==i.from&&i.marker.inclusiveLeft&&rn(e,t,i))return!0}}function rn(e,t,r){if(null==r.to){var i=r.marker.find(1,!0);return rn(e,i.line,_i(i.line.markedSpans,r.marker))}if(r.marker.inclusiveRight&&r.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o)if(n=t.markedSpans[o],n.marker.collapsed&&!n.marker.widgetNode&&n.from==r.to&&(null==n.to||n.to!=r.from)&&(n.marker.inclusiveLeft||r.marker.inclusiveRight)&&rn(e,t,n))return!0}function nn(e,t,r){Gn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&gi(e,null,r)}function on(e){if(null!=e.height)return e.height;if(!yo(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.getGutterElement().offsetWidth+"px;"),Io(e.cm.display.measure,Lo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function sn(e,t,r,i){var n=new Zs(e,r,i);return n.noHScroll&&(e.display.alignWidgets=!0),Li(e.doc,t,"widget",function(t){var r=t.widgets||(t.widgets=[]);if(null==n.insertAt?r.push(n):r.splice(Math.min(r.length-1,Math.max(0,n.insertAt)),0,n),n.line=t,!tn(e.doc,t)){var i=Gn(t)<e.doc.scrollTop;_n(t,t.height+on(n)),i&&gi(e,null,n.height),e.curOp.forceUpdate=!0}return!0}),n}function an(e,t,r,i){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),Fi(e),ji(e,r);var n=i?i(e):1;n!=e.height&&_n(e,n)}function ln(e){e.parent=null,Fi(e)}function un(e,t){if(e)for(;;){var r=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!r)break;e=e.slice(0,r.index)+e.slice(r.index+r[0].length);var i=r[1]?"bgClass":"textClass";null==t[i]?t[i]=r[2]:new RegExp("(?:^|s)"+r[2]+"(?:$|s)").test(t[i])||(t[i]+=" "+r[2])}return e}function pn(t,r){if(t.blankLine)return t.blankLine(r);if(t.innerMode){var i=e.innerMode(t,r);return i.mode.blankLine?i.mode.blankLine(i.state):void 0}}function cn(e,t,r){for(var i=0;10>i;i++){var n=e.token(t,r);if(t.pos>t.start)return n}throw new Error("Mode "+e.name+" failed to advance stream.")}function dn(t,r,i,n,o,s,a){var l=i.flattenSpans;null==l&&(l=t.options.flattenSpans);var u,p=0,c=null,d=new Ys(r,t.options.tabSize);for(""==r&&un(pn(i,n),s);!d.eol();){if(d.pos>t.options.maxHighlightLength?(l=!1,a&&fn(t,r,n,d.pos),d.pos=r.length,u=null):u=un(cn(i,d,n),s),t.options.addModeClass){var h=e.innerMode(i,n).mode.name;h&&(u="m-"+(u?h+" "+u:h))}l&&c==u||(p<d.start&&o(d.start,c),p=d.start,c=u),d.start=d.pos}for(;p<d.pos;){var E=Math.min(d.pos,p+5e4);o(E,c),p=E}}function hn(e,t,r,i){var n=[e.state.modeGen],o={};dn(e,t.text,e.doc.mode,r,function(e,t){n.push(e,t)},o,i);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;dn(e,t.text,a.mode,!0,function(e,t){for(var r=l;e>u;){var i=n[l];i>e&&n.splice(l,1,e,n[l+1],i),l+=2,u=Math.min(e,i)}if(t)if(a.opaque)n.splice(r,l-r,e,"cm-overlay "+t),l=r+2;else for(;l>r;r+=2){var o=n[r+1];n[r+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function En(e,t){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=hn(e,t,t.stateAfter=At(e,Mn(t)));t.styles=r.styles,r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null)}return t.styles}function fn(e,t,r,i){var n=e.doc.mode,o=new Ys(t,e.options.tabSize);for(o.start=o.pos=i||0,""==t&&pn(n,r);!o.eol()&&o.pos<=e.options.maxHighlightLength;)cn(n,o,r),o.start=o.pos}function mn(e,t){if(!e||/^\s*$/.test(e))return null;var r=t.addModeClass?ta:ea;return r[e]||(r[e]=e.replace(/\S+/g,"cm-$&"))}function gn(e,t){var r=Lo("span",null,null,ts?"padding-right: .1px":null),i={pre:Lo("pre",[r]),content:r,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;i.pos=0,i.addToken=xn,(Jo||ts)&&e.getOption("lineWrapping")&&(i.addToken=Nn(i.addToken)),wo(e.display.measure)&&(o=kn(s))&&(i.addToken=Ln(i.addToken,o)),i.map=[],In(s,i,En(e,s)),s.styleClasses&&(s.styleClasses.bgClass&&(i.bgClass=bo(s.styleClasses.bgClass,i.bgClass||"")),s.styleClasses.textClass&&(i.textClass=bo(s.styleClasses.textClass,i.textClass||""))),0==i.map.length&&i.map.push(0,0,i.content.appendChild(Mo(e.display.measure))),0==n?(t.measure.map=i.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(i.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return ca(e,"renderLine",e,t.line,i.pre),i.pre.className&&(i.textClass=bo(i.pre.className,i.textClass||"")),i}function vn(e){var t=Lo("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t}function xn(e,t,r,i,n,o){if(t){var s=e.cm.options.specialChars,a=!1;if(s.test(t))for(var l=document.createDocumentFragment(),u=0;;){s.lastIndex=u;var p=s.exec(t),c=p?p.index-u:t.length-u;if(c){var d=document.createTextNode(t.slice(u,u+c));l.appendChild(Jo&&9>es?Lo("span",[d]):d),e.map.push(e.pos,e.pos+c,d),e.col+=c,e.pos+=c}if(!p)break;if(u+=c+1," "==p[0]){var h=e.cm.options.tabSize,E=h-e.col%h,d=l.appendChild(Lo("span",po(E),"cm-tab"));e.col+=E}else{var d=e.cm.options.specialCharPlaceholder(p[0]);l.appendChild(Jo&&9>es?Lo("span",[d]):d),e.col+=1}e.map.push(e.pos,e.pos+1,d),e.pos++}else{e.col+=t.length;var l=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,l),Jo&&9>es&&(a=!0),e.pos+=t.length}if(r||i||n||a){var f=r||"";i&&(f+=i),n&&(f+=n);var m=Lo("span",[l],f);return o&&(m.title=o),e.content.appendChild(m)}e.content.appendChild(l)}}function Nn(e){function t(e){for(var t=" ",r=0;r<e.length-2;++r)t+=r%2?" ":" ";return t+=" "}return function(r,i,n,o,s,a){e(r,i.replace(/ {3,}/g,t),n,o,s,a)}}function Ln(e,t){return function(r,i,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=r.pos,u=l+i.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(r,i,n,o,s,a);e(r,i.slice(0,c.to-l),n,o,null,a),o=null,i=i.slice(c.to-l),l=c.to}}}function Tn(e,t,r,i){var n=!i&&r.widgetNode;n&&(e.map.push(e.pos,e.pos+t,n),e.content.appendChild(n)),e.pos+=t}function In(e,t,r){var i=e.markedSpans,n=e.text,o=0;if(i)for(var s,a,l,u,p,c,d=n.length,h=0,E=1,f="",m=0;;){if(m==h){a=l=u=p="",c=null,m=1/0;for(var g=[],v=0;v<i.length;++v){var x=i[v],N=x.marker;x.from<=h&&(null==x.to||x.to>h)?(null!=x.to&&m>x.to&&(m=x.to,l=""),N.className&&(a+=" "+N.className),N.startStyle&&x.from==h&&(u+=" "+N.startStyle),N.endStyle&&x.to==m&&(l+=" "+N.endStyle),N.title&&!p&&(p=N.title),N.collapsed&&(!c||zi(c.marker,N)<0)&&(c=x)):x.from>h&&m>x.from&&(m=x.from),"bookmark"==N.type&&x.from==h&&N.widgetNode&&g.push(N)}if(c&&(c.from||0)==h&&(Tn(t,(null==c.to?d+1:c.to)-h,c.marker,null==c.from),null==c.to))return;if(!c&&g.length)for(var v=0;v<g.length;++v)Tn(t,0,g[v])}if(h>=d)break;for(var L=Math.min(d,m);;){if(f){var T=h+f.length;if(!c){var I=T>L?f.slice(0,L-h):f;t.addToken(t,I,s?s+a:a,u,h+I.length==m?l:"",p)}if(T>=L){f=f.slice(L-h),h=L;break}h=T,u=""}f=n.slice(o,o=r[E++]),s=mn(r[E++],t.cm.options)}}else for(var E=1;E<r.length;E+=2)t.addToken(t,n.slice(o,o=r[E]),mn(r[E+1],t.cm.options))}function yn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==co(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function An(e,t,r,i){function n(e){return r?r[e]:null}function o(e,r,n){an(e,r,n,i),ro(e,"change",e,t)}var s=t.from,a=t.to,l=t.text,u=On(e,s.line),p=On(e,a.line),c=co(l),d=n(l.length-1),h=a.line-s.line;if(yn(e,t)){for(var E=0,f=[];E<l.length-1;++E)f.push(new Js(l[E],n(E),i));o(p,p.text,d),h&&e.remove(s.line,h),f.length&&e.insert(s.line,f)}else if(u==p)if(1==l.length)o(u,u.text.slice(0,s.ch)+c+u.text.slice(a.ch),d);else{for(var f=[],E=1;E<l.length-1;++E)f.push(new Js(l[E],n(E),i));f.push(new Js(c+u.text.slice(a.ch),d,i)),o(u,u.text.slice(0,s.ch)+l[0],n(0)),e.insert(s.line+1,f)}else if(1==l.length)o(u,u.text.slice(0,s.ch)+l[0]+p.text.slice(a.ch),n(0)),e.remove(s.line+1,h);else{o(u,u.text.slice(0,s.ch)+l[0],n(0)),o(p,c+p.text.slice(a.ch),d);for(var E=1,f=[];E<l.length-1;++E)f.push(new Js(l[E],n(E),i));h>1&&e.remove(s.line+1,h-1),e.insert(s.line+1,f)}ro(e,"change",e,t)}function Sn(e){this.lines=e,this.parent=null;for(var t=0,r=0;t<e.length;++t)e[t].parent=this,r+=e[t].height;this.height=r}function Cn(e){this.children=e;for(var t=0,r=0,i=0;i<e.length;++i){var n=e[i];t+=n.chunkSize(),r+=n.height,n.parent=this}this.size=t,this.height=r,this.parent=null}function Rn(e,t,r){function i(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;(!r||l)&&(t(a.doc,l),i(a.doc,e,l))}}}i(e,null,!0)}function bn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,s(e),r(e),e.options.lineWrapping||h(e),e.options.mode=t.modeOption,Er(e)}function On(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var r=e;!r.lines;)for(var i=0;;++i){var n=r.children[i],o=n.chunkSize();if(o>t){r=n;break}t-=o}return r.lines[t]}function Pn(e,t,r){var i=[],n=t.line;return e.iter(t.line,r.line+1,function(e){var o=e.text;n==r.line&&(o=o.slice(0,r.ch)),n==t.line&&(o=o.slice(t.ch)),i.push(o),++n}),i}function Dn(e,t,r){var i=[];return e.iter(t,r,function(e){i.push(e.text)}),i}function _n(e,t){var r=t-e.height;if(r)for(var i=e;i;i=i.parent)i.height+=r}function Mn(e){if(null==e.parent)return null;for(var t=e.parent,r=ho(t.lines,e),i=t.parent;i;t=i,i=i.parent)for(var n=0;i.children[n]!=t;++n)r+=i.children[n].chunkSize();return r+t.first}function wn(e,t){var r=e.first;e:do{for(var i=0;i<e.children.length;++i){var n=e.children[i],o=n.height; if(o>t){e=n;continue e}t-=o,r+=n.chunkSize()}return r}while(!e.lines);for(var i=0;i<e.lines.length;++i){var s=e.lines[i],a=s.height;if(a>t)break;t-=a}return r+i}function Gn(e){e=Qi(e);for(var t=0,r=e.parent,i=0;i<r.lines.length;++i){var n=r.lines[i];if(n==e)break;t+=n.height}for(var o=r.parent;o;r=o,o=r.parent)for(var i=0;i<o.children.length;++i){var s=o.children[i];if(s==r)break;t+=s.height}return t}function kn(e){var t=e.order;return null==t&&(t=e.order=Ga(e.text)),t}function Bn(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 Un(e,t){var r={from:q(t.from),to:Ds(t),text:Pn(e,t.from,t.to)};return zn(e,r,t.from.line,t.to.line+1),Rn(e,function(e){zn(e,r,t.from.line,t.to.line+1)},!0),r}function Vn(e){for(;e.length;){var t=co(e);if(!t.ranges)break;e.pop()}}function Hn(e,t){return t?(Vn(e.done),co(e.done)):e.done.length&&!co(e.done).ranges?co(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),co(e.done)):void 0}function Fn(e,t,r,i){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==i||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Hn(n,n.lastOp==i))){var a=co(o.changes);0==xs(t.from,t.to)&&0==xs(t.from,a.to)?a.to=Ds(t):o.changes.push(Un(e,t))}else{var l=co(n.done);for(l&&l.ranges||qn(e.sel,n.done),o={changes:[Un(e,t)],generation:n.generation},n.done.push(o);n.done.length>n.undoDepth;)n.done.shift(),n.done[0].ranges||n.done.shift()}n.done.push(r),n.generation=++n.maxGeneration,n.lastModTime=n.lastSelTime=s,n.lastOp=n.lastSelOp=i,n.lastOrigin=n.lastSelOrigin=t.origin,a||ca(e,"historyAdded")}function jn(e,t,r,i){var n=t.charAt(0);return"*"==n||"+"==n&&r.ranges.length==i.ranges.length&&r.somethingSelected()==i.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Wn(e,t,r,i){var n=e.history,o=i&&i.origin;r==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||jn(e,o,co(n.done),t))?n.done[n.done.length-1]=t:qn(t,n.done),n.lastSelTime=+new Date,n.lastSelOrigin=o,n.lastSelOp=r,i&&i.clearRedo!==!1&&Vn(n.undone)}function qn(e,t){var r=co(t);r&&r.ranges&&r.equals(e)||t.push(e)}function zn(e,t,r,i){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,r),Math.min(e.first+e.size,i),function(r){r.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=r.markedSpans),++o})}function Xn(e){if(!e)return null;for(var t,r=0;r<e.length;++r)e[r].marker.explicitlyCleared?t||(t=e.slice(0,r)):t&&t.push(e[r]);return t?t.length?t:null:e}function Yn(e,t){var r=t["spans_"+e.id];if(!r)return null;for(var i=0,n=[];i<t.text.length;++i)n.push(Xn(r[i]));return n}function Kn(e,t,r){for(var i=0,n=[];i<e.length;++i){var o=e[i];if(o.ranges)n.push(r?Y.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];if(a.push({from:p.from,to:p.to,text:p.text}),t)for(var c in p)(u=c.match(/^spans_(\d+)$/))&&ho(t,Number(u[1]))>-1&&(co(a)[c]=p[c],delete p[c])}}}return n}function $n(e,t,r,i){r<e.line?e.line+=i:t<e.line&&(e.line=t,e.ch=0)}function Qn(e,t,r,i){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){o.copied||(o=e[n]=o.deepCopy(),o.copied=!0);for(var a=0;a<o.ranges.length;a++)$n(o.ranges[a].anchor,t,r,i),$n(o.ranges[a].head,t,r,i)}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(r<l.from.line)l.from=vs(l.from.line+i,l.from.ch),l.to=vs(l.to.line+i,l.to.ch);else if(t<=l.to.line){s=!1;break}}s||(e.splice(0,n+1),n=0)}}}function Zn(e,t){var r=t.from.line,i=t.to.line,n=t.text.length-(i-r)-1;Qn(e.done,r,i,n),Qn(e.undone,r,i,n)}function Jn(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function eo(e){return e.target||e.srcElement}function to(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),cs&&e.ctrlKey&&1==t&&(t=3),t}function ro(e,t){function r(e){return function(){e.apply(null,o)}}var i=e._handlers&&e._handlers[t];if(i){var n,o=Array.prototype.slice.call(arguments,2);ys?n=ys.delayedCallbacks:da?n=da:(n=da=[],setTimeout(io,0));for(var s=0;s<i.length;++s)n.push(r(i[s]))}}function io(){var e=da;da=null;for(var t=0;t<e.length;++t)e[t]()}function no(e,t,r){return ca(e,r||t.type,e,t),Jn(t)||t.codemirrorIgnore}function oo(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var r=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),i=0;i<t.length;++i)-1==ho(r,t[i])&&r.push(t[i])}function so(e,t){var r=e._handlers&&e._handlers[t];return r&&r.length>0}function ao(e){e.prototype.on=function(e,t){ua(this,e,t)},e.prototype.off=function(e,t){pa(this,e,t)}}function lo(){this.id=null}function uo(e,t,r){for(var i=0,n=0;;){var o=e.indexOf(" ",i);-1==o&&(o=e.length);var s=o-i;if(o==e.length||n+s>=t)return i+Math.min(s,t-n);if(n+=o-i,n+=r-n%r,i=o+1,n>=t)return i}}function po(e){for(;xa.length<=e;)xa.push(co(xa)+" ");return xa[e]}function co(e){return e[e.length-1]}function ho(e,t){for(var r=0;r<e.length;++r)if(e[r]==t)return r;return-1}function Eo(e,t){for(var r=[],i=0;i<e.length;i++)r[i]=t(e[i],i);return r}function fo(e,t){var r;if(Object.create)r=Object.create(e);else{var i=function(){};i.prototype=e,r=new i}return t&&mo(t,r),r}function mo(e,t,r){t||(t={});for(var i in e)!e.hasOwnProperty(i)||r===!1&&t.hasOwnProperty(i)||(t[i]=e[i]);return t}function go(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function vo(e,t){return t?t.source.indexOf("\\w")>-1&&Ia(e)?!0:t.test(e):Ia(e)}function xo(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function No(e){return e.charCodeAt(0)>=768&&ya.test(e)}function Lo(e,t,r,i){var n=document.createElement(e);if(r&&(n.className=r),i&&(n.style.cssText=i),"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 To(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Io(e,t){return To(e).appendChild(t)}function yo(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function Ao(){return document.activeElement}function So(e){return new RegExp("\\b"+e+"\\b\\s*")}function Co(e,t){var r=So(t);r.test(e.className)&&(e.className=e.className.replace(r,""))}function Ro(e,t){So(t).test(e.className)||(e.className+=" "+t)}function bo(e,t){for(var r=e.split(" "),i=0;i<r.length;i++)r[i]&&!So(r[i]).test(t)&&(t+=" "+r[i]);return t}function Oo(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),r=0;r<t.length;r++){var i=t[r].CodeMirror;i&&e(i)}}function Po(){Ra||(Do(),Ra=!0)}function Do(){var e;ua(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,Aa=null,Oo(br)},100))}),ua(window,"blur",function(){Oo(Zr)})}function _o(e){if(null!=Aa)return Aa;var t=Lo("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return Io(e,t),t.offsetWidth&&(Aa=t.offsetHeight-t.clientHeight),Aa||0}function Mo(e){if(null==Sa){var t=Lo("span","​");Io(e,Lo("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Sa=t.offsetWidth<=1&&t.offsetHeight>2&&!(Jo&&8>es))}return Sa?Lo("span","​"):Lo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function wo(e){if(null!=Ca)return Ca;var t=Io(e,document.createTextNode("AخA")),r=La(t,0,1).getBoundingClientRect();if(!r||r.left==r.right)return!1;var i=La(t,1,2).getBoundingClientRect();return Ca=i.right-r.right<3}function Go(e){if(null!=_a)return _a;var t=Io(e,Lo("span","x")),r=t.getBoundingClientRect(),i=La(t,0,1).getBoundingClientRect();return _a=Math.abs(r.left-i.left)>1}function ko(e,t,r,i){if(!e)return i(t,r,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];(s.from<r&&s.to>t||t==r&&s.to==t)&&(i(Math.max(s.from,t),Math.min(s.to,r),1==s.level?"rtl":"ltr"),n=!0)}n||i(t,r,"ltr")}function Bo(e){return e.level%2?e.to:e.from}function Uo(e){return e.level%2?e.from:e.to}function Vo(e){var t=kn(e);return t?Bo(t[0]):0}function Ho(e){var t=kn(e);return t?Uo(co(t)):e.text.length}function Fo(e,t){var r=On(e.doc,t),i=Qi(r);i!=r&&(t=Mn(i));var n=kn(i),o=n?n[0].level%2?Ho(i):Vo(i):0;return vs(t,o)}function jo(e,t){for(var r,i=On(e.doc,t);r=Ki(i);)i=r.find(1,!0).line,t=null;var n=kn(i),o=n?n[0].level%2?Vo(i):Ho(i):i.text.length;return vs(null==t?Mn(i):t,o)}function Wo(e,t){var r=Fo(e,t.line),i=On(e.doc,r.line),n=kn(i);if(!n||0==n[0].level){var o=Math.max(0,i.text.search(/\S/)),s=t.line==r.line&&t.ch<=o&&t.ch;return vs(r.line,s?0:o)}return r}function qo(e,t,r){var i=e[0].level;return t==i?!0:r==i?!1:r>t}function zo(e,t){wa=null;for(var r,i=0;i<e.length;++i){var n=e[i];if(n.from<t&&n.to>t)return i;if(n.from==t||n.to==t){if(null!=r)return qo(e,n.level,e[r].level)?(n.from!=n.to&&(wa=r),i):(n.from!=n.to&&(wa=i),r);r=i}}return r}function Xo(e,t,r,i){if(!i)return t+r;do t+=r;while(t>0&&No(e.text.charAt(t)));return t}function Yo(e,t,r,i){var n=kn(e);if(!n)return Ko(e,t,r,i);for(var o=zo(n,t),s=n[o],a=Xo(e,t,s.level%2?-r:r,i);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to)return zo(n,a)==o?a:(s=n[o+=r],r>0==s.level%2?s.to:s.from);if(s=n[o+=r],!s)return null;a=r>0==s.level%2?Xo(e,s.to,-1,i):Xo(e,s.from,1,i)}}function Ko(e,t,r,i){var n=t+r;if(i)for(;n>0&&No(e.text.charAt(n));)n+=r;return 0>n||n>e.text.length?null:n}var $o=/gecko\/\d/i.test(navigator.userAgent),Qo=/MSIE \d/.test(navigator.userAgent),Zo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Jo=Qo||Zo,es=Jo&&(Qo?document.documentMode||6:Zo[1]),ts=/WebKit\//.test(navigator.userAgent),rs=ts&&/Qt\/\d+\.\d+/.test(navigator.userAgent),is=/Chrome\//.test(navigator.userAgent),ns=/Opera\//.test(navigator.userAgent),os=/Apple Computer/.test(navigator.vendor),ss=/KHTML\//.test(navigator.userAgent),as=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),ls=/PhantomJS/.test(navigator.userAgent),us=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),ps=us||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),cs=us||/Mac/.test(navigator.platform),ds=/win/i.test(navigator.platform),hs=ns&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);hs&&(hs=Number(hs[1])),hs&&hs>=15&&(ns=!1,ts=!0);var Es=cs&&(rs||ns&&(null==hs||12.11>hs)),fs=$o||Jo&&es>=9,ms=!1,gs=!1,vs=e.Pos=function(e,t){return this instanceof vs?(this.line=e,void(this.ch=t)):new vs(e,t)},xs=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};Y.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 r=this.ranges[t],i=e.ranges[t];if(0!=xs(r.anchor,i.anchor)||0!=xs(r.head,i.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new K(q(this.ranges[t].anchor),q(this.ranges[t].head));return new Y(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 r=0;r<this.ranges.length;r++){var i=this.ranges[r];if(xs(t,i.from())>=0&&xs(e,i.to())<=0)return r}return-1}},K.prototype={from:function(){return X(this.anchor,this.head)},to:function(){return z(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var Ns,Ls,Ts,Is={left:0,right:0,top:0,bottom:0},ys=null,As=0,Ss=null,Cs=0,Rs=0,bs=null;Jo?bs=-.53:$o?bs=15:is?bs=-.7:os&&(bs=-1/3);var Os,Ps=null,Ds=e.changeEnd=function(e){return e.text?vs(e.from.line+e.text.length-1,co(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus(),Ar(this),Tr(this)},setOption:function(e,t){var r=this.options,i=r[e];(r[e]!=t||"mode"==e)&&(r[e]=t,Ms.hasOwnProperty(e)&&ur(this,Ms[e])(this,t,i))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](e)},removeKeyMap:function(e){for(var t=this.state.keyMaps,r=0;r<t.length;++r)if(t[r]==e||"string"!=typeof t[r]&&t[r].name==e)return t.splice(r,1),!0},addOverlay:pr(function(t,r){var i=t.token?t:e.getMode(this.options,t);if(i.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:i,modeSpec:t,opaque:r&&r.opaque}),this.state.modeGen++,Er(this)}),removeOverlay:pr(function(e){for(var t=this.state.overlays,r=0;r<t.length;++r){var i=t[r].modeSpec;if(i==e||"string"==typeof e&&i.name==e)return t.splice(r,1),this.state.modeGen++,void Er(this)}}),indentLine:pr(function(e,t,r){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),tt(this.doc,e)&&Ni(this,e,t,r)}),indentSelection:pr(function(e){for(var t=this.doc.sel.ranges,r=-1,i=0;i<t.length;i++){var n=t[i];if(n.empty())n.head.line>r&&(Ni(this,n.head.line,e,!0),r=n.head.line,i==this.doc.sel.primIndex&&vi(this));else{var o=n.from(),s=n.to(),a=Math.max(r,o.line);r=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;r>l;++l)Ni(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[i].from().ch>0&&st(this.doc,i,new K(o,u[i].to()),fa)}}}),getTokenAt:function(e,t){var r=this.doc;e=J(r,e);for(var i=At(this,e.line,t),n=this.doc.mode,o=On(r,e.line),s=new Ys(o.text,this.options.tabSize);s.pos<e.ch&&!s.eol();){s.start=s.pos;var a=cn(n,s,i)}return{start:s.start,end:s.pos,string:s.current(),type:a||null,state:i}},getTokenTypeAt:function(e){e=J(this.doc,e);var t,r=En(this,On(this.doc,e.line)),i=0,n=(r.length-1)/2,o=e.ch;if(0==o)t=r[2];else for(;;){var s=i+n>>1;if((s?r[2*s-1]:0)>=o)n=s;else{if(!(r[2*s+1]<o)){t=r[2*s+2];break}i=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 r=this.doc.mode;return r.innerMode?e.innerMode(r,this.getTokenAt(t).state).mode:r},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var r=[];if(!Vs.hasOwnProperty(t))return Vs;var i=Vs[t],n=this.getModeAt(e);if("string"==typeof n[t])i[n[t]]&&r.push(i[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=i[n[t][o]];s&&r.push(s)}else n.helperType&&i[n.helperType]?r.push(i[n.helperType]):i[n.name]&&r.push(i[n.name]);for(var o=0;o<i._global.length;o++){var a=i._global[o];a.pred(n,this)&&-1==ho(r,a.val)&&r.push(a.val)}return r},getStateAfter:function(e,t){var r=this.doc;return e=Z(r,null==e?r.first+r.size-1:e),At(this,e+1,t)},cursorCoords:function(e,t){var r,i=this.doc.sel.primary();return r=null==e?i.head:"object"==typeof e?J(this.doc,e):e?i.from():i.to(),zt(this,r,t||"page")},charCoords:function(e,t){return qt(this,J(this.doc,e),t||"page")},coordsChar:function(e,t){return e=Wt(this,e,t||"page"),Kt(this,e.left,e.top)},lineAtHeight:function(e,t){return e=Wt(this,{top:e,left:0},t||"page").top,wn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var r=!1,i=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>i&&(e=i,r=!0);var n=On(this.doc,e);return jt(this,n,{top:0,left:0},t||"page").top+(r?this.doc.height-Gn(n):0)},defaultTextHeight:function(){return Qt(this.display)},defaultCharWidth:function(){return Zt(this.display)},setGutterMarker:pr(function(e,t,r){return Li(this.doc,e,"gutter",function(e){var i=e.gutterMarkers||(e.gutterMarkers={});return i[t]=r,!r&&xo(i)&&(e.gutterMarkers=null),!0})}),clearGutter:pr(function(e){var t=this,r=t.doc,i=r.first;r.iter(function(r){r.gutterMarkers&&r.gutterMarkers[e]&&(r.gutterMarkers[e]=null,fr(t,i,"gutter"),xo(r.gutterMarkers)&&(r.gutterMarkers=null)),++i})}),addLineWidget:pr(function(e,t,r){return sn(this,e,t,r)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!tt(this.doc,e))return null;var t=e;if(e=On(this.doc,e),!e)return null}else{var t=Mn(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,r,i,n){var o=this.display;e=zt(this,J(this.doc,e));var s=e.bottom,a=e.left;if(t.style.position="absolute",o.sizer.appendChild(t),"over"==i)s=e.top;else if("above"==i||"near"==i){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==i||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="","right"==n?(a=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=a+"px"),r&&fi(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:pr(Xr),triggerOnKeyPress:pr($r),triggerOnKeyUp:Kr,execCommand:function(e){return js.hasOwnProperty(e)?js[e](this):void 0},findPosH:function(e,t,r,i){var n=1;0>t&&(n=-1,t=-t);for(var o=0,s=J(this.doc,e);t>o&&(s=Ii(this.doc,s,n,r,i),!s.hitSide);++o);return s},moveH:pr(function(e,t){var r=this;r.extendSelectionsBy(function(i){return r.display.shift||r.doc.extend||i.empty()?Ii(r.doc,i.head,e,t,r.options.rtlMoveVisually):0>e?i.from():i.to()},ga)}),deleteH:pr(function(e,t){var r=this.doc.sel,i=this.doc;r.somethingSelected()?i.replaceSelection("",null,"+delete"):Ti(this,function(r){var n=Ii(i,r.head,e,t,!1);return 0>e?{from:n,to:r.head}:{from:r.head,to:n}})}),findPosV:function(e,t,r,i){var n=1,o=i;0>t&&(n=-1,t=-t);for(var s=0,a=J(this.doc,e);t>s;++s){var l=zt(this,a,"div");if(null==o?o=l.left:l.left=o,a=yi(this,l,n,r),a.hitSide)break}return a},moveV:pr(function(e,t){var r=this,i=this.doc,n=[],o=!r.display.shift&&!i.extend&&i.sel.somethingSelected();if(i.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=zt(r,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn),n.push(a.left);var l=yi(r,a,e,t);return"page"==t&&s==i.sel.primary()&&gi(r,null,qt(r,l,"div").top-a.top),l},ga),n.length)for(var s=0;s<i.sel.ranges.length;s++)i.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,r=On(t,e.line).text,i=e.ch,n=e.ch;if(r){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==r.length)&&i?--i:++n;for(var s=r.charAt(i),a=vo(s,o)?function(e){return vo(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!vo(e)};i>0&&a(r.charAt(i-1));)--i;for(;n<r.length&&a(r.charAt(n));)++n}return new K(vs(e.line,i),vs(e.line,n))},toggleOverwrite:function(e){(null==e||e!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?Ro(this.display.cursorDiv,"CodeMirror-overwrite"):Co(this.display.cursorDiv,"CodeMirror-overwrite"),ca(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return Ao()==this.display.input},scrollTo:pr(function(e,t){(null!=e||null!=t)&&xi(this),null!=e&&(this.curOp.scrollLeft=e),null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller,t=ha;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-t,width:e.scrollWidth-t,clientHeight:e.clientHeight-t,clientWidth:e.clientWidth-t}},scrollIntoView:pr(function(e,t){if(null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:vs(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line)xi(this),this.curOp.scrollToPos=e;else{var r=mi(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(r.scrollLeft,r.scrollTop)}}),setSize:pr(function(e,t){function r(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var i=this;null!=e&&(i.display.wrapper.style.width=r(e)),null!=t&&(i.display.wrapper.style.height=r(t)),i.options.lineWrapping&&Ut(this);var n=i.display.viewFrom;i.doc.iter(n,i.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){fr(i,n,"widget");break}++n}),i.curOp.forceUpdate=!0,ca(i,"refresh",this)}),operation:function(e){return lr(this,e)},refresh:pr(function(){var e=this.display.cachedTextHeight;Er(this),this.curOp.forceUpdate=!0,Vt(this),this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop),c(this),(null==e||Math.abs(e-Qt(this.display))>.5)&&s(this),ca(this,"refresh",this)}),swapDoc:pr(function(e){var t=this.doc;return t.cm=null,bn(this,e),Vt(this),yr(this),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,ro(this,"swapDoc",this,t),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}},ao(e);var _s=e.defaults={},Ms=e.optionHandlers={},ws=e.Init={toString:function(){return"CodeMirror.Init"}};Ai("value","",function(e,t){e.setValue(t)},!0),Ai("mode",null,function(e,t){e.doc.modeOption=t,r(e)},!0),Ai("indentUnit",2,r,!0),Ai("indentWithTabs",!1),Ai("smartIndent",!0),Ai("tabSize",4,function(e){i(e),Vt(e),Er(e)},!0),Ai("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),Ai("specialCharPlaceholder",vn,function(e){e.refresh()},!0),Ai("electricChars",!0),Ai("rtlMoveVisually",!ds),Ai("wholeLineUpdateBefore",!0),Ai("theme","default",function(e){l(e),u(e)},!0),Ai("keyMap","default",a),Ai("extraKeys",null),Ai("lineWrapping",!1,n,!0),Ai("gutters",[],function(e){E(e.options),u(e)},!0),Ai("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?T(e.display)+"px":"0",e.refresh()},!0),Ai("coverGutterNextToScrollbar",!1,g,!0),Ai("lineNumbers",!1,function(e){E(e.options),u(e)},!0),Ai("firstLineNumber",1,u,!0),Ai("lineNumberFormatter",function(e){return e},u,!0),Ai("showCursorWhenSelecting",!1,vt,!0),Ai("resetSelectionOnContextMenu",!0),Ai("readOnly",!1,function(e,t){"nocursor"==t?(Zr(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||yr(e))}),Ai("disableInput",!1,function(e,t){t||yr(e)},!0),Ai("dragDrop",!0),Ai("cursorBlinkRate",530),Ai("cursorScrollMargin",0),Ai("cursorHeight",1,vt,!0),Ai("singleCursorHeightPerLine",!0,vt,!0),Ai("workTime",100),Ai("workDelay",100),Ai("flattenSpans",!0,i,!0),Ai("addModeClass",!1,i,!0),Ai("pollInterval",100),Ai("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),Ai("historyEventDelay",1250),Ai("viewportMargin",10,function(e){e.refresh()},!0),Ai("maxHighlightLength",1e4,i,!0),Ai("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),Ai("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),Ai("autofocus",null);var Gs=e.modes={},ks=e.mimeModes={};e.defineMode=function(t,r){e.defaults.mode||"null"==t||(e.defaults.mode=t),arguments.length>2&&(r.dependencies=Array.prototype.slice.call(arguments,2)),Gs[t]=r},e.defineMIME=function(e,t){ks[e]=t},e.resolveMode=function(t){if("string"==typeof t&&ks.hasOwnProperty(t))t=ks[t];else if(t&&"string"==typeof t.name&&ks.hasOwnProperty(t.name)){var r=ks[t.name];"string"==typeof r&&(r={name:r}),t=fo(r,t),t.name=r.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,r){var r=e.resolveMode(r),i=Gs[r.name];if(!i)return e.getMode(t,"text/plain");var n=i(t,r);if(Bs.hasOwnProperty(r.name)){var o=Bs[r.name];for(var s in o)o.hasOwnProperty(s)&&(n.hasOwnProperty(s)&&(n["_"+s]=n[s]),n[s]=o[s])}if(n.name=r.name,r.helperType&&(n.helperType=r.helperType),r.modeProps)for(var s in r.modeProps)n[s]=r.modeProps[s];return n},e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),e.defineMIME("text/plain","null");var Bs=e.modeExtensions={};e.extendMode=function(e,t){var r=Bs.hasOwnProperty(e)?Bs[e]:Bs[e]={};mo(t,r)},e.defineExtension=function(t,r){e.prototype[t]=r},e.defineDocExtension=function(e,t){ia.prototype[e]=t},e.defineOption=Ai;var Us=[];e.defineInitHook=function(e){Us.push(e)};var Vs=e.helpers={};e.registerHelper=function(t,r,i){Vs.hasOwnProperty(t)||(Vs[t]=e[t]={_global:[]}),Vs[t][r]=i},e.registerGlobalHelper=function(t,r,i,n){e.registerHelper(t,r,n),Vs[t]._global.push({pred:i,val:n})};var Hs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var r={};for(var i in t){var n=t[i];n instanceof Array&&(n=n.concat([])),r[i]=n}return r},Fs=e.startState=function(e,t,r){return e.startState?e.startState(t,r):!0};e.innerMode=function(e,t){for(;e.innerMode;){var r=e.innerMode(t);if(!r||r.mode==e)break;t=r.state,e=r.mode}return r||{mode:e,state:t}};var js=e.commands={selectAll:function(e){e.setSelection(vs(e.firstLine(),0),vs(e.lastLine()),fa)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),fa)},killLine:function(e){Ti(e,function(t){if(t.empty()){var r=On(e.doc,t.head.line).text.length;return t.head.ch==r&&t.head.line<e.lastLine()?{from:t.head,to:vs(t.head.line+1,0)}:{from:t.head,to:vs(t.head.line,r)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Ti(e,function(t){return{from:vs(t.from().line,0),to:J(e.doc,vs(t.to().line+1,0))}})},delLineLeft:function(e){Ti(e,function(e){return{from:vs(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Ti(e,function(t){var r=e.charCoords(t.head,"div").top+5,i=e.coordsChar({left:0,top:r},"div");return{from:i,to:t.from()}})},delWrappedLineRight:function(e){Ti(e,function(t){var r=e.charCoords(t.head,"div").top+5,i=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:r},"div");return{from:t.from(),to:i}})},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(vs(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(vs(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Fo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Wo(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return jo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var r=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:r},"div")},ga)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var r=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:r},"div")},ga)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var r=e.charCoords(t.head,"div").top+5,i=e.coordsChar({left:0,top:r},"div");return i.ch<e.getLine(i.line).search(/\S/)?Wo(e,t.head):i},ga)},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=[],r=e.listSelections(),i=e.options.tabSize,n=0;n<r.length;n++){var o=r[n].from(),s=va(e.getLine(o.line),o.ch,i);t.push(new Array(i-s%i+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){lr(e,function(){for(var t=e.listSelections(),r=[],i=0;i<t.length;i++){var n=t[i].head,o=On(e.doc,n.line).text;if(o)if(n.ch==o.length&&(n=new vs(n.line,n.ch-1)),n.ch>0)n=new vs(n.line,n.ch+1),e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),vs(n.line,n.ch-2),n,"+transpose");else if(n.line>e.doc.first){var s=On(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),vs(n.line-1,s.length-1),vs(n.line,1),"+transpose")}r.push(new K(n,n))}e.setSelections(r)})},newlineAndIndent:function(e){lr(e,function(){for(var t=e.listSelections().length,r=0;t>r;r++){var i=e.listSelections()[r];e.replaceRange("\n",i.anchor,i.head,"+input"),e.indentLine(i.from().line+1,null,!0),vi(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ws=e.keyMap={};Ws.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"},Ws.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"},Ws.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"]},Ws.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"},Ws["default"]=cs?Ws.macDefault:Ws.pcDefault;var qs=e.lookupKey=function(e,t,r){function i(t){t=Si(t);var n=t[e];if(n===!1)return"stop";if(null!=n&&r(n))return!0;if(t.nofallthrough)return"stop";var o=t.fallthrough;if(null==o)return!1;if("[object Array]"!=Object.prototype.toString.call(o))return i(o);for(var s=0;s<o.length;++s){var a=i(o[s]);if(a)return a}return!1}for(var n=0;n<t.length;++n){var o=i(t[n]);if(o)return"stop"!=o}},zs=e.isModifierKey=function(e){var t=Ma[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Xs=e.keyName=function(e,t){if(ns&&34==e.keyCode&&e["char"])return!1;var r=Ma[e.keyCode];return null==r||e.altGraphKey?!1:(e.altKey&&(r="Alt-"+r),(Es?e.metaKey:e.ctrlKey)&&(r="Ctrl-"+r),(Es?e.ctrlKey:e.metaKey)&&(r="Cmd-"+r),!t&&e.shiftKey&&(r="Shift-"+r),r) };e.fromTextArea=function(t,r){function i(){t.value=u.getValue()}if(r||(r={}),r.value=t.value,!r.tabindex&&t.tabindex&&(r.tabindex=t.tabindex),!r.placeholder&&t.placeholder&&(r.placeholder=t.placeholder),null==r.autofocus){var n=Ao();r.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form&&(ua(t.form,"submit",i),!r.leaveSubmitMethodAlone)){var o=t.form,s=o.submit;try{var a=o.submit=function(){i(),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)},r);return u.save=i,u.getTextArea=function(){return t},u.toTextArea=function(){u.toTextArea=isNaN,i(),t.parentNode.removeChild(u.getWrapperElement()),t.style.display="",t.form&&(pa(t.form,"submit",i),"function"==typeof t.form.submit&&(t.form.submit=s))},u};var Ys=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};Ys.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 r=t==e;else var r=t&&(e.test?e.test(t):e(t));return r?(++this.pos,t):void 0},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);return t>-1?(this.pos=t,!0):void 0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=va(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?va(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return va(this.string,null,this.tabSize)-(this.lineStart?va(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,r){if("string"!=typeof e){var i=this.string.slice(this.pos).match(e);return i&&i.index>0?null:(i&&t!==!1&&(this.pos+=i[0].length),i)}var n=function(e){return r?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return n(o)==n(e)?(t!==!1&&(this.pos+=e.length),!0):void 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 Ks=e.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};ao(Ks),Ks.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Jt(e),so(this,"clear")){var r=this.find();r&&ro(this,"clear",r.from,r.to)}for(var i=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=_i(s.markedSpans,this);e&&!this.collapsed?fr(e,Mn(s),"text"):e&&(null!=a.to&&(n=Mn(s)),null!=a.from&&(i=Mn(s))),s.markedSpans=Mi(s.markedSpans,a),null==a.from&&this.collapsed&&!tn(this.doc,s)&&e&&_n(s,Qt(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Qi(this.lines[o]),u=d(l);u>e.display.maxLineLength&&(e.display.maxLine=l,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=i&&e&&this.collapsed&&Er(e,i,n+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&ht(e.doc)),e&&ro(e,"markerCleared",e,this),t&&tr(e),this.parent&&this.parent.clear()}},Ks.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var r,i,n=0;n<this.lines.length;++n){var o=this.lines[n],s=_i(o.markedSpans,this);if(null!=s.from&&(r=vs(t?o:Mn(o),s.from),-1==e))return r;if(null!=s.to&&(i=vs(t?o:Mn(o),s.to),1==e))return i}return r&&{from:r,to:i}},Ks.prototype.changed=function(){var e=this.find(-1,!0),t=this,r=this.doc.cm;e&&r&&lr(r,function(){var i=e.line,n=Mn(e.line),o=_t(r,n);if(o&&(Bt(o),r.curOp.selectionChanged=r.curOp.forceUpdate=!0),r.curOp.updateMaxLine=!0,!tn(t.doc,i)&&null!=t.height){var s=t.height;t.height=null;var a=on(t)-s;a&&_n(i,i.height+a)}})},Ks.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=ho(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},Ks.prototype.detachLine=function(e){if(this.lines.splice(ho(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var $s=0,Qs=e.SharedTextMarker=function(e,t){this.markers=e,this.primary=t;for(var r=0;r<e.length;++r)e[r].parent=this};ao(Qs),Qs.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();ro(this,"clear")}},Qs.prototype.find=function(e,t){return this.primary.find(e,t)};var Zs=e.LineWidget=function(e,t,r){if(r)for(var i in r)r.hasOwnProperty(i)&&(this[i]=r[i]);this.cm=e,this.node=t};ao(Zs),Zs.prototype.clear=function(){var e=this.cm,t=this.line.widgets,r=this.line,i=Mn(r);if(null!=i&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(r.widgets=null);var o=on(this);lr(e,function(){nn(e,r,-o),fr(e,i,"widget"),_n(r,Math.max(0,r.height-o))})}},Zs.prototype.changed=function(){var e=this.height,t=this.cm,r=this.line;this.height=null;var i=on(this)-e;i&&lr(t,function(){t.curOp.forceUpdate=!0,nn(t,r,i),_n(r,r.height+i)})};var Js=e.Line=function(e,t,r){this.text=e,ji(this,t),this.height=r?r(this):1};ao(Js),Js.prototype.lineNo=function(){return Mn(this)};var ea={},ta={};Sn.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var r=e,i=e+t;i>r;++r){var n=this.lines[r];this.height-=n.height,ln(n),ro(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,r){this.height+=r,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var i=0;i<t.length;++i)t[i].parent=this},iterN:function(e,t,r){for(var i=e+t;i>e;++e)if(r(this.lines[e]))return!0}},Cn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var r=0;r<this.children.length;++r){var i=this.children[r],n=i.chunkSize();if(n>e){var o=Math.min(t,n-e),s=i.height;if(i.removeInner(e,o),this.height-=s-i.height,n==o&&(this.children.splice(r--,1),i.parent=null),0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof Sn))){var a=[];this.collapse(a),this.children=[new Sn(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,r){this.size+=t.length,this.height+=r;for(var i=0;i<this.children.length;++i){var n=this.children[i],o=n.chunkSize();if(o>=e){if(n.insertInner(e,t,r),n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new Sn(s);n.height-=a.height,this.children.splice(i+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),r=new Cn(t);if(e.parent){e.size-=r.size,e.height-=r.height;var i=ho(e.parent.children,e);e.parent.children.splice(i+1,0,r)}else{var n=new Cn(e.children);n.parent=e,e.children=[n,r],e=n}r.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,r){for(var i=0;i<this.children.length;++i){var n=this.children[i],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,r))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var ra=0,ia=e.Doc=function(e,t,r){if(!(this instanceof ia))return new ia(e,t,r);null==r&&(r=0),Cn.call(this,[new Sn([new Js("",null)])]),this.first=r,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=r;var i=vs(r,0);this.sel=Q(i),this.history=new Bn(null),this.id=++ra,this.modeOption=t,"string"==typeof e&&(e=Oa(e)),An(this,{from:i,to:i,text:e}),pt(this,Q(i),fa)};ia.prototype=fo(Cn.prototype,{constructor:ia,iter:function(e,t,r){r?this.iterN(e-this.first,t-e,r):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var r=0,i=0;i<t.length;++i)r+=t[i].height;this.insertInner(e-this.first,t,r)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Dn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:cr(function(e){var t=vs(this.first,0),r=this.first+this.size-1;si(this,{from:t,to:vs(r,On(this,r).text.length),text:Oa(e),origin:"setValue"},!0),pt(this,Q(t))}),replaceRange:function(e,t,r,i){t=J(this,t),r=r?J(this,r):t,di(this,e,t,r,i)},getRange:function(e,t,r){var i=Pn(this,J(this,e),J(this,t));return r===!1?i:i.join(r||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return tt(this,e)?On(this,e):void 0},getLineNumber:function(e){return Mn(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=On(this,e)),Qi(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return J(this,e)},getCursor:function(e){var t,r=this.sel.primary();return t=null==e||"head"==e?r.head:"anchor"==e?r.anchor:"end"==e||"to"==e||e===!1?r.to():r.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:cr(function(e,t,r){at(this,J(this,"number"==typeof e?vs(e,t||0):e),null,r)}),setSelection:cr(function(e,t,r){at(this,J(this,e),J(this,t||e),r)}),extendSelection:cr(function(e,t,r){nt(this,J(this,e),t&&J(this,t),r)}),extendSelections:cr(function(e,t){ot(this,rt(this,e,t))}),extendSelectionsBy:cr(function(e,t){ot(this,Eo(this.sel.ranges,e),t)}),setSelections:cr(function(e,t,r){if(e.length){for(var i=0,n=[];i<e.length;i++)n[i]=new K(J(this,e[i].anchor),J(this,e[i].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),pt(this,$(n,t),r)}}),addSelection:cr(function(e,t,r){var i=this.sel.ranges.slice(0);i.push(new K(J(this,e),J(this,t||e))),pt(this,$(i,i.length-1),r)}),getSelection:function(e){for(var t,r=this.sel.ranges,i=0;i<r.length;i++){var n=Pn(this,r[i].from(),r[i].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],r=this.sel.ranges,i=0;i<r.length;i++){var n=Pn(this,r[i].from(),r[i].to());e!==!1&&(n=n.join(e||"\n")),t[i]=n}return t},replaceSelection:function(e,t,r){for(var i=[],n=0;n<this.sel.ranges.length;n++)i[n]=e;this.replaceSelections(i,t,r||"+input")},replaceSelections:cr(function(e,t,r){for(var i=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];i[o]={from:s.from(),to:s.to(),text:Oa(e[o]),origin:r}}for(var a=t&&"end"!=t&&ni(this,i,t),o=i.length-1;o>=0;o--)si(this,i[o]);a?ut(this,a):this.cm&&vi(this.cm)}),undo:cr(function(){li(this,"undo")}),redo:cr(function(){li(this,"redo")}),undoSelection:cr(function(){li(this,"undo",!0)}),redoSelection:cr(function(){li(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,r=0,i=0;i<e.done.length;i++)e.done[i].ranges||++t;for(var i=0;i<e.undone.length;i++)e.undone[i].ranges||++r;return{undo:t,redo:r}},clearHistory:function(){this.history=new Bn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Kn(this.history.done),undone:Kn(this.history.undone)}},setHistory:function(e){var t=this.history=new Bn(this.history.maxGeneration);t.done=Kn(e.done.slice(0),null,!0),t.undone=Kn(e.undone.slice(0),null,!0)},addLineClass:cr(function(e,t,r){return Li(this,e,"class",function(e){var i="text"==t?"textClass":"background"==t?"bgClass":"wrapClass";if(e[i]){if(new RegExp("(?:^|\\s)"+r+"(?:$|\\s)").test(e[i]))return!1;e[i]+=" "+r}else e[i]=r;return!0})}),removeLineClass:cr(function(e,t,r){return Li(this,e,"class",function(e){var i="text"==t?"textClass":"background"==t?"bgClass":"wrapClass",n=e[i];if(!n)return!1;if(null==r)e[i]=null;else{var o=n.match(new RegExp("(?:^|\\s+)"+r+"(?:$|\\s+)"));if(!o)return!1;var s=o.index+o[0].length;e[i]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,r){return Ci(this,J(this,e),J(this,t),r,"range")},setBookmark:function(e,t){var r={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};return e=J(this,e),Ci(this,e,e,r,"bookmark")},findMarksAt:function(e){e=J(this,e);var t=[],r=On(this,e.line).markedSpans;if(r)for(var i=0;i<r.length;++i){var n=r[i];(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,r){e=J(this,e),t=J(this,t);var i=[],n=e.line;return 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||r&&!r(l.marker)||i.push(l.marker.parent||l.marker)}++n}),i},getAllMarks:function(){var e=[];return this.iter(function(t){var r=t.markedSpans;if(r)for(var i=0;i<r.length;++i)null!=r[i].from&&e.push(r[i].marker)}),e},posFromIndex:function(e){var t,r=this.first;return this.iter(function(i){var n=i.text.length+1;return n>e?(t=e,!0):(e-=n,void++r)}),J(this,vs(r,t))},indexFromPos:function(e){e=J(this,e);var t=e.ch;return e.line<this.first||e.ch<0?0:(this.iter(this.first,e.line,function(e){t+=e.text.length+1}),t)},copy:function(e){var t=new ia(Dn(this,this.first,this.first+this.size),this.modeOption,this.first);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,r=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<r&&(r=e.to);var i=new ia(Dn(this,t,r),e.mode||this.modeOption,t);return e.sharedHist&&(i.history=this.history),(this.linked||(this.linked=[])).push({doc:i,sharedHist:e.sharedHist}),i.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],Oi(i,bi(this)),i},unlinkDoc:function(t){if(t instanceof e&&(t=t.doc),this.linked)for(var r=0;r<this.linked.length;++r){var i=this.linked[r];if(i.doc==t){this.linked.splice(r,1),t.unlinkDoc(this),Pi(bi(this));break}}if(t.history==this.history){var n=[t.id];Rn(t,function(e){n.push(e.id)},!0),t.history=new Bn(null),t.history.done=Kn(this.history.done,n),t.history.undone=Kn(this.history.undone,n)}},iterLinkedDocs:function(e){Rn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),ia.prototype.eachLine=ia.prototype.iter;var na="iter insert remove copy getEditor".split(" ");for(var oa in ia.prototype)ia.prototype.hasOwnProperty(oa)&&ho(na,oa)<0&&(e.prototype[oa]=function(e){return function(){return e.apply(this.doc,arguments)}}(ia.prototype[oa]));ao(ia);var sa=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},aa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},la=e.e_stop=function(e){sa(e),aa(e)},ua=e.on=function(e,t,r){if(e.addEventListener)e.addEventListener(t,r,!1);else if(e.attachEvent)e.attachEvent("on"+t,r);else{var i=e._handlers||(e._handlers={}),n=i[t]||(i[t]=[]);n.push(r)}},pa=e.off=function(e,t,r){if(e.removeEventListener)e.removeEventListener(t,r,!1);else if(e.detachEvent)e.detachEvent("on"+t,r);else{var i=e._handlers&&e._handlers[t];if(!i)return;for(var n=0;n<i.length;++n)if(i[n]==r){i.splice(n,1);break}}},ca=e.signal=function(e,t){var r=e._handlers&&e._handlers[t];if(r)for(var i=Array.prototype.slice.call(arguments,2),n=0;n<r.length;++n)r[n].apply(null,i)},da=null,ha=30,Ea=e.Pass={toString:function(){return"CodeMirror.Pass"}},fa={scroll:!1},ma={origin:"*mouse"},ga={origin:"+move"};lo.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var va=e.countColumn=function(e,t,r,i,n){null==t&&(t=e.search(/[^\s\u00a0]/),-1==t&&(t=e.length));for(var o=i||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o,s+=r-s%r,o=a+1}},xa=[""],Na=function(e){e.select()};us?Na=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:Jo&&(Na=function(e){try{e.select()}catch(t){}}),[].indexOf&&(ho=function(e,t){return e.indexOf(t)}),[].map&&(Eo=function(e,t){return e.map(t)});var La,Ta=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Ia=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Ta.test(e))},ya=/[\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]/;La=document.createRange?function(e,t,r){var i=document.createRange();return i.setEnd(e,r),i.setStart(e,t),i}:function(e,t,r){var i=document.body.createTextRange();return i.moveToElementText(e.parentNode),i.collapse(!0),i.moveEnd("character",r),i.moveStart("character",t),i},Jo&&11>es&&(Ao=function(){try{return document.activeElement}catch(e){return document.body}});var Aa,Sa,Ca,Ra=!1,ba=function(){if(Jo&&9>es)return!1;var e=Lo("div");return"draggable"in e||"dragDrop"in e}(),Oa=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,r=[],i=e.length;i>=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");-1!=s?(r.push(o.slice(0,s)),t+=s+1):(r.push(o),t=n+1)}return r}:function(e){return e.split(/\r\n?|\n/)},Pa=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(r){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Da=function(){var e=Lo("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),_a=null,Ma={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=Ma,function(){for(var e=0;10>e;e++)Ma[e+48]=Ma[e+96]=String(e);for(var e=65;90>=e;e++)Ma[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Ma[e+111]=Ma[e+63235]="F"+e}();var wa,Ga=function(){function e(e){return 247>=e?r.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?i.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,r){this.level=e,this.from=t,this.to=r}var r="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",i="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(r){if(!n.test(r))return!1;for(var i,p=r.length,c=[],d=0;p>d;++d)c.push(i=e(r.charCodeAt(d)));for(var d=0,h=u;p>d;++d){var i=c[d];"m"==i?c[d]=h:h=i}for(var d=0,E=u;p>d;++d){var i=c[d];"1"==i&&"r"==E?c[d]="n":s.test(i)&&(E=i,"r"==i&&(c[d]="R"))}for(var d=1,h=c[0];p-1>d;++d){var i=c[d];"+"==i&&"1"==h&&"1"==c[d+1]?c[d]="1":","!=i||h!=c[d+1]||"1"!=h&&"n"!=h||(c[d]=h),h=i}for(var d=0;p>d;++d){var i=c[d];if(","==i)c[d]="N";else if("%"==i){for(var f=d+1;p>f&&"%"==c[f];++f);for(var m=d&&"!"==c[d-1]||p>f&&"1"==c[f]?"1":"N",g=d;f>g;++g)c[g]=m;d=f-1}}for(var d=0,E=u;p>d;++d){var i=c[d];"L"==E&&"1"==i?c[d]="L":s.test(i)&&(E=i)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var f=d+1;p>f&&o.test(c[f]);++f);for(var v="L"==(d?c[d-1]:u),x="L"==(p>f?c[f]:u),m=v||x?"L":"R",g=d;f>g;++g)c[g]=m;d=f-1}for(var N,L=[],d=0;p>d;)if(a.test(c[d])){var T=d;for(++d;p>d&&a.test(c[d]);++d);L.push(new t(0,T,d))}else{var I=d,y=L.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&L.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);L.splice(y,0,new t(2,A,g)),I=g}else++g;d>I&&L.splice(y,0,new t(1,I,d))}return 1==L[0].level&&(N=r.match(/^\s+/))&&(L[0].from=N[0].length,L.unshift(new t(0,0,N[0].length))),1==co(L).level&&(N=r.match(/\s+$/))&&(co(L).to-=N[0].length,L.push(new t(0,p-N[0].length,p))),L[0].level!=co(L).level&&L.push(new t(L[0].level,p,p)),L}}();return e.version="4.7.0",e})},{}],11:[function(t,r){!function(e,t){"object"==typeof r&&"object"==typeof r.exports?r.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,r){function i(e){var t=e.length,r=ot.type(e);return"function"===r||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===r||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,r){if(ot.isFunction(t))return ot.grep(e,function(e,i){return!!t.call(e,i,e)!==r});if(t.nodeType)return ot.grep(e,function(e){return e===t!==r});if("string"==typeof t){if(ht.test(t))return ot.filter(t,e,r);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==r})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Lt[e]={};return ot.each(e.match(Nt)||[],function(e,r){t[r]=!0}),t}function a(){ft.addEventListener?(ft.removeEventListener("DOMContentLoaded",l,!1),t.removeEventListener("load",l,!1)):(ft.detachEvent("onreadystatechange",l),t.detachEvent("onload",l))}function l(){(ft.addEventListener||"load"===event.type||"complete"===ft.readyState)&&(a(),ot.ready())}function u(e,t,r){if(void 0===r&&1===e.nodeType){var i="data-"+t.replace(St,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:At.test(r)?ot.parseJSON(r):r}catch(n){}ot.data(e,t,r)}else r=void 0}return r}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,r,i){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]&&(i||l[u].data)||void 0!==r||"string"!=typeof t)return u||(u=a?e[s]=K.pop()||ot.guid++:s),l[u]||(l[u]=a?{}:{toJSON:ot.noop}),("object"==typeof t||"function"==typeof t)&&(i?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t)),o=l[u],i||(o.data||(o.data={}),o=o.data),void 0!==r&&(o[ot.camelCase(t)]=r),"string"==typeof t?(n=o[t],null==n&&(n=o[ot.camelCase(t)])):n=o,n}}function d(e,t,r){if(ot.acceptData(e)){var i,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t&&(i=r?s[a]:s[a].data)){ot.isArray(t)?t=t.concat(ot.map(t,ot.camelCase)):t in i?t=[t]:(t=ot.camelCase(t),t=t in i?[t]:t.split(" ")),n=t.length;for(;n--;)delete i[t[n]];if(r?!p(i):!ot.isEmptyObject(i))return}(r||(delete s[a].data,p(s[a])))&&(o?ot.cleanData([e],!0):it.deleteExpando||s!=s.window?delete s[a]:s[a]=null)}}}function h(){return!0}function E(){return!1}function f(){try{return ft.activeElement}catch(e){}}function m(e){var t=kt.split("|"),r=e.createDocumentFragment();if(r.createElement)for(;t.length;)r.createElement(t.pop());return r}function g(e,t){var r,i,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],r=e.childNodes||e;null!=(i=r[n]);n++)!t||ot.nodeName(i,t)?o.push(i):ot.merge(o,g(i,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){return e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type,e}function L(e){var t=Yt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function T(e,t){for(var r,i=0;null!=(r=e[i]);i++)ot._data(r,"globalEval",!t||ot._data(t[i],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var r,i,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle,s.events={};for(r in a)for(i=0,n=a[r].length;n>i;i++)ot.event.add(t,r,a[r][i])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var r,i,n;if(1===t.nodeType){if(r=t.nodeName.toLowerCase(),!it.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(i in n.events)ot.removeEvent(t,i,n.handle);t.removeAttribute(ot.expando)}"script"===r&&t.text!==e.text?(N(t).text=e.text,L(t)):"object"===r?(t.parentNode&&(t.outerHTML=e.outerHTML),it.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===r&&Pt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===r?t.defaultSelected=t.selected=e.defaultSelected:("input"===r||"textarea"===r)&&(t.defaultValue=e.defaultValue)}}function A(e,r){var i,n=ot(r.createElement(e)).appendTo(r.body),o=t.getDefaultComputedStyle&&(i=t.getDefaultComputedStyle(n[0]))?i.display:ot.css(n[0],"display");return n.detach(),o}function S(e){var t=ft,r=er[e];return r||(r=A(e,t),"none"!==r&&r||(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(),r=A(e,t),Jt.detach()),er[e]=r),r}function C(e,t){return{get:function(){var r=e();if(null!=r)return r?void delete this.get:(this.get=t).apply(this,arguments)}}}function R(e,t){if(t in e)return t;for(var r=t.charAt(0).toUpperCase()+t.slice(1),i=t,n=hr.length;n--;)if(t=hr[n]+r,t in e)return t;return i}function b(e,t){for(var r,i,n,o=[],s=0,a=e.length;a>s;s++)i=e[s],i.style&&(o[s]=ot._data(i,"olddisplay"),r=i.style.display,t?(o[s]||"none"!==r||(i.style.display=""),""===i.style.display&&bt(i)&&(o[s]=ot._data(i,"olddisplay",S(i.nodeName)))):(n=bt(i),(r&&"none"!==r||!n)&&ot._data(i,"olddisplay",n?r:ot.css(i,"display"))));for(s=0;a>s;s++)i=e[s],i.style&&(t&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=t?o[s]||"":"none"));return e}function O(e,t,r){var i=ur.exec(t);return i?Math.max(0,i[1]-(r||0))+(i[2]||"px"):t}function P(e,t,r,i,n){for(var o=r===(i?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2)"margin"===r&&(s+=ot.css(e,r+Rt[o],!0,n)),i?("content"===r&&(s-=ot.css(e,"padding"+Rt[o],!0,n)),"margin"!==r&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))):(s+=ot.css(e,"padding"+Rt[o],!0,n),"padding"!==r&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n)));return s}function D(e,t,r){var i=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=tr(e),s=it.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){if(n=rr(e,t,o),(0>n||null==n)&&(n=e.style[t]),nr.test(n))return n;i=s&&(it.boxSizingReliable()||n===e.style[t]),n=parseFloat(n)||0}return n+P(e,t,r||(s?"border":"content"),i,o)+"px"}function _(e,t,r,i,n){return new _.prototype.init(e,t,r,i,n)}function M(){return setTimeout(function(){Er=void 0}),Er=ot.now()}function w(e,t){var r,i={height:e},n=0;for(t=t?1:0;4>n;n+=2-t)r=Rt[n],i["margin"+r]=i["padding"+r]=e;return t&&(i.opacity=i.width=e),i}function G(e,t,r){for(var i,n=(Nr[t]||[]).concat(Nr["*"]),o=0,s=n.length;s>o;o++)if(i=n[o].call(r,t,e))return i}function k(e,t,r){var i,n,o,s,a,l,u,p,c=this,d={},h=e.style,E=e.nodeType&&bt(e),f=ot._data(e,"fxshow");r.queue||(a=ot._queueHooks(e,"fx"),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()})})),1===e.nodeType&&("height"in t||"width"in t)&&(r.overflow=[h.overflow,h.overflowX,h.overflowY],u=ot.css(e,"display"),p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u,"inline"===p&&"none"===ot.css(e,"float")&&(it.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?h.zoom=1:h.display="inline-block")),r.overflow&&(h.overflow="hidden",it.shrinkWrapBlocks()||c.always(function(){h.overflow=r.overflow[0],h.overflowX=r.overflow[1],h.overflowY=r.overflow[2]}));for(i in t)if(n=t[i],mr.exec(n)){if(delete t[i],o=o||"toggle"===n,n===(E?"hide":"show")){if("show"!==n||!f||void 0===f[i])continue;E=!0}d[i]=f&&f[i]||ot.style(e,i)}else u=void 0;if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(h.display=u);else{f?"hidden"in f&&(E=f.hidden):f=ot._data(e,"fxshow",{}),o&&(f.hidden=!E),E?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(i in d)s=G(E?f[i]:0,i,c),i in f||(f[i]=s.start,E&&(s.end=s.start,s.start="width"===i||"height"===i?1:0))}}function B(e,t){var r,i,n,o,s;for(r in e)if(i=ot.camelCase(r),n=t[i],o=e[r],ot.isArray(o)&&(n=o[1],o=e[r]=o[0]),r!==i&&(e[i]=o,delete e[r]),s=ot.cssHooks[i],s&&"expand"in s){o=s.expand(o),delete e[i];for(r in o)r in e||(e[r]=o[r],t[r]=n)}else t[i]=n}function U(e,t,r){var i,n,o=0,s=xr.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=Er||M(),r=Math.max(0,u.startTime+u.duration-t),i=r/u.duration||0,o=1-i,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);return a.notifyWith(e,[u,o,r]),1>o&&l?r:(a.resolveWith(e,[u]),!1)},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},r),originalProperties:t,originalOptions:r,startTime:Er||M(),duration:r.duration,tweens:[],createTween:function(t,r){var i=ot.Tween(e,u.opts,t,r,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(i),i},stop:function(t){var r=0,i=t?u.tweens.length:0;if(n)return this;for(n=!0;i>r;r++)u.tweens[r].run(1); return t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]),this}}),p=u.props;for(B(p,u.opts.specialEasing);s>o;o++)if(i=xr[o].call(u,e,p,u.opts))return i;return ot.map(p,G,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})),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,r){"string"!=typeof t&&(r=t,t="*");var i,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(r))for(;i=o[n++];)"+"===i.charAt(0)?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(r)):(e[i]=e[i]||[]).push(r)}}function H(e,t,r,i){function n(a){var l;return o[a]=!0,ot.each(e[a]||[],function(e,a){var u=a(t,r,i);return"string"!=typeof u||s||o[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),n(u),!1)}),l}var o={},s=e===Wr;return n(t.dataTypes[0])||!o["*"]&&n("*")}function F(e,t){var r,i,n=ot.ajaxSettings.flatOptions||{};for(i in t)void 0!==t[i]&&((n[i]?e:r||(r={}))[i]=t[i]);return r&&ot.extend(!0,e,r),e}function j(e,t,r){for(var i,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 r)o=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}i||(i=s)}o=o||i}return o?(o!==l[0]&&l.unshift(o),r[o]):void 0}function W(e,t,r,i){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];for(o=p.shift();o;)if(e.responseFields[o]&&(r[e.responseFields[o]]=t),!l&&i&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=p.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(s=u[l+" "+o]||u["* "+o],!s)for(n in u)if(a=n.split(" "),a[1]===o&&(s=u[l+" "+a[0]]||u["* "+a[0]])){s===!0?s=u[n]: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,r,i){var n;if(ot.isArray(t))ot.each(t,function(t,n){r||Yr.test(e)?i(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,r,i)});else if(r||"object"!==ot.type(t))i(e,t);else for(n in t)q(e+"["+n+"]",t[n],r,i)}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,rt=et.hasOwnProperty,it={},nt="1.11.1",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);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,r){return e.call(t,r,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,r=+e+(0>e?t:0);return this.pushStack(r>=0&&t>r?[this[r]]:[])},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,r,i,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[a]||{},a++),"object"==typeof s||ot.isFunction(s)||(s={}),a===l&&(s=this,a--);l>a;a++)if(null!=(n=arguments[a]))for(i in n)e=s[i],r=n[i],s!==r&&(u&&r&&(ot.isPlainObject(r)||(t=ot.isArray(r)))?(t?(t=!1,o=e&&ot.isArray(e)?e:[]):o=e&&ot.isPlainObject(e)?e:{},s[i]=ot.extend(u,o,r)):void 0!==r&&(s[i]=r));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)>=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&&!rt.call(e,"constructor")&&!rt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(it.ownLast)for(t in e)return rt.call(e,t);for(t in e);return void 0===t||rt.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,r){var n,o=0,s=e.length,a=i(e);if(r){if(a)for(;s>o&&(n=t.apply(e[o],r),n!==!1);o++);else for(o in e)if(n=t.apply(e[o],r),n===!1)break}else if(a)for(;s>o&&(n=t.call(e[o],o,e[o]),n!==!1);o++);else for(o in e)if(n=t.call(e[o],o,e[o]),n===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(i(Object(e))?ot.merge(r,"string"==typeof e?[e]:e):Z.call(r,e)),r},inArray:function(e,t,r){var i;if(t){if(J)return J.call(t,e,r);for(i=t.length,r=r?0>r?Math.max(0,i+r):r:0;i>r;r++)if(r in t&&t[r]===e)return r}return-1},merge:function(e,t){for(var r=+t.length,i=0,n=e.length;r>i;)e[n++]=t[i++];if(r!==r)for(;void 0!==t[i];)e[n++]=t[i++];return e.length=n,e},grep:function(e,t,r){for(var i,n=[],o=0,s=e.length,a=!r;s>o;o++)i=!t(e[o],o),i!==a&&n.push(e[o]);return n},map:function(e,t,r){var n,o=0,s=e.length,a=i(e),l=[];if(a)for(;s>o;o++)n=t(e[o],o,r),null!=n&&l.push(n);else for(o in e)n=t(e[o],o,r),null!=n&&l.push(n);return Q.apply([],l)},guid:1,proxy:function(e,t){var r,i,n;return"string"==typeof t&&(n=e[t],t=e,e=n),ot.isFunction(e)?(r=$.call(arguments,2),i=function(){return e.apply(t||this,r.concat($.call(arguments)))},i.guid=e.guid=e.guid||ot.guid++,i):void 0},now:function(){return+new Date},support:it}),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,r,i){var n,o,s,a,l,u,c,h,E,f;if((t?t.ownerDocument||t:V)!==D&&P(t),t=t||D,r=r||[],!e||"string"!=typeof e)return r;if(1!==(a=t.nodeType)&&9!==a)return[];if(M&&!i){if(n=vt.exec(e))if(s=n[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return r;if(o.id===s)return r.push(o),r}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s)return r.push(o),r}else{if(n[2])return J.apply(r,t.getElementsByTagName(e)),r;if((s=n[3])&&L.getElementsByClassName&&t.getElementsByClassName)return J.apply(r,t.getElementsByClassName(s)),r}if(L.qsa&&(!w||!w.test(e))){if(h=c=U,E=t,f=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){for(u=A(e),(c=t.getAttribute("id"))?h=c.replace(Nt,"\\$&"):t.setAttribute("id",h),h="[id='"+h+"'] ",l=u.length;l--;)u[l]=h+d(u[l]);E=xt.test(e)&&p(t.parentNode)||t,f=u.join(",")}if(f)try{return J.apply(r,E.querySelectorAll(f)),r}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,r,i)}function r(){function e(r,i){return t.push(r+" ")>T.cacheLength&&delete e[t.shift()],e[r+" "]=i}var t=[];return e}function i(e){return e[U]=!0,e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(r){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var r=e.split("|"),i=e.length;i--;)T.attrHandle[r[i]]=t}function s(e,t){var r=t&&e,i=r&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(i)return i;if(r)for(;r=r.nextSibling;)if(r===t)return-1;return e?1:-1}function a(e){return function(t){var r=t.nodeName.toLowerCase();return"input"===r&&t.type===e}}function l(e){return function(t){var r=t.nodeName.toLowerCase();return("input"===r||"button"===r)&&t.type===e}}function u(e){return i(function(t){return t=+t,i(function(r,i){for(var n,o=e([],r.length,t),s=o.length;s--;)r[n=o[s]]&&(r[n]=!(i[n]=r[n]))})})}function p(e){return e&&typeof e.getElementsByTagName!==X&&e}function c(){}function d(e){for(var t=0,r=e.length,i="";r>t;t++)i+=e[t].value;return i}function h(e,t,r){var i=t.dir,n=r&&"parentNode"===i,o=F++;return t.first?function(t,r,o){for(;t=t[i];)if(1===t.nodeType||n)return e(t,r,o)}:function(t,r,s){var a,l,u=[H,o];if(s){for(;t=t[i];)if((1===t.nodeType||n)&&e(t,r,s))return!0}else for(;t=t[i];)if(1===t.nodeType||n){if(l=t[U]||(t[U]={}),(a=l[i])&&a[0]===H&&a[1]===o)return u[2]=a[2];if(l[i]=u,u[2]=e(t,r,s))return!0}}}function E(e){return e.length>1?function(t,r,i){for(var n=e.length;n--;)if(!e[n](t,r,i))return!1;return!0}:e[0]}function f(e,r,i){for(var n=0,o=r.length;o>n;n++)t(e,r[n],i);return i}function m(e,t,r,i,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)(o=e[a])&&(!r||r(o,i,n))&&(s.push(o),u&&t.push(a));return s}function g(e,t,r,n,o,s){return n&&!n[U]&&(n=g(n)),o&&!o[U]&&(o=g(o,s)),i(function(i,s,a,l){var u,p,c,d=[],h=[],E=s.length,g=i||f(t||"*",a.nodeType?[a]:a,[]),v=!e||!i&&t?g:m(g,d,e,a,l),x=r?o||(i?e:E||n)?[]:s:v;if(r&&r(v,x,a,l),n)for(u=m(x,h),n(u,[],a,l),p=u.length;p--;)(c=u[p])&&(x[h[p]]=!(v[h[p]]=c));if(i){if(o||e){if(o){for(u=[],p=x.length;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}for(p=x.length;p--;)(c=x[p])&&(u=o?tt.call(i,c):d[p])>-1&&(i[u]=!(s[u]=c))}}else x=m(x===s?x.splice(E,x.length):x),o?o(null,s,x,l):J.apply(s,x)})}function v(e){for(var t,r,i,n=e.length,o=T.relative[e[0].type],s=o||T.relative[" "],a=o?1:0,l=h(function(e){return e===t},s,!0),u=h(function(e){return tt.call(t,e)>-1},s,!0),p=[function(e,r,i){return!o&&(i||r!==R)||((t=r).nodeType?l(e,r,i):u(e,r,i))}];n>a;a++)if(r=T.relative[e[a].type])p=[h(E(p),r)];else{if(r=T.filter[e[a].type].apply(null,e[a].matches),r[U]){for(i=++a;n>i&&!T.relative[e[i].type];i++);return g(a>1&&E(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),r,i>a&&v(e.slice(a,i)),n>i&&v(e=e.slice(i)),n>i&&d(e))}p.push(r)}return E(p)}function x(e,r){var n=r.length>0,o=e.length>0,s=function(i,s,a,l,u){var p,c,d,h=0,E="0",f=i&&[],g=[],v=R,x=i||o&&T.find.TAG("*",u),N=H+=null==v?1:Math.random()||.1,L=x.length;for(u&&(R=s!==D&&s);E!==L&&null!=(p=x[E]);E++){if(o&&p){for(c=0;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(H=N)}n&&((p=!d&&p)&&h--,i&&f.push(p))}if(h+=E,n&&E!==h){for(c=0;d=r[c++];)d(f,g,s,a);if(i){if(h>0)for(;E--;)f[E]||g[E]||(g[E]=Q.call(l));g=m(g)}J.apply(l,g),u&&!i&&g.length>0&&h+r.length>1&&t.uniqueSort(l)}return u&&(H=N,R=v),f};return n?i(s):s}var N,L,T,I,y,A,S,C,R,b,O,P,D,_,M,w,G,k,B,U="sizzle"+-new Date,V=e.document,H=0,F=0,j=r(),W=r(),q=r(),z=function(e,t){return e===t&&(O=!0),0},X="undefined",Y=1<<31,K={}.hasOwnProperty,$=[],Q=$.pop,Z=$.push,J=$.push,et=$.slice,tt=$.indexOf||function(e){for(var t=0,r=this.length;r>t;t++)if(this[t]===e)return t;return-1},rt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",nt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=nt.replace("w","w#"),st="\\["+it+"*("+nt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+it+"*\\]",at=":("+nt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+st+")*)|.*)\\)|)",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(at),ht=new RegExp("^"+ot+"$"),Et={ID:new RegExp("^#("+nt+")"),CLASS:new RegExp("^\\.("+nt+")"),TAG:new RegExp("^("+nt.replace("w","w*")+")"),ATTR:new RegExp("^"+st),PSEUDO:new RegExp("^"+at),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("^(?:"+rt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},ft=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Lt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Tt=function(e,t,r){var i="0x"+t-65536;return i!==i||r?t:0>i?String.fromCharCode(i+65536):String.fromCharCode(i>>10|55296,1023&i|56320)};try{J.apply($=et.call(V.childNodes),V.childNodes),$[V.childNodes.length].nodeType}catch(It){J={apply:$.length?function(e,t){Z.apply(e,et.call(t))}:function(e,t){for(var r=e.length,i=0;e[r++]=t[i++];);e.length=r-1}}}L=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,r=e?e.ownerDocument||e:V,i=r.defaultView;return r!==D&&9===r.nodeType&&r.documentElement?(D=r,_=r.documentElement,M=!y(r),i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",function(){P()},!1):i.attachEvent&&i.attachEvent("onunload",function(){P()})),L.attributes=n(function(e){return e.className="i",!e.getAttribute("className")}),L.getElementsByTagName=n(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),L.getElementsByClassName=gt.test(r.getElementsByClassName)&&n(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),L.getById=n(function(e){return _.appendChild(e).id=U,!r.getElementsByName||!r.getElementsByName(U).length}),L.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==X&&M){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}},T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){var r=typeof e.getAttributeNode!==X&&e.getAttributeNode("id");return r&&r.value===t}}),T.find.TAG=L.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==X?t.getElementsByTagName(e):void 0}:function(e,t){var r,i=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;r=o[n++];)1===r.nodeType&&i.push(r);return i}return o},T.find.CLASS=L.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==X&&M?t.getElementsByClassName(e):void 0},G=[],w=[],(L.qsa=gt.test(r.querySelectorAll))&&(n(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&w.push("[*^$]="+it+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||w.push("\\["+it+"*(?:value|"+rt+")"),e.querySelectorAll(":checked").length||w.push(":checked")}),n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&w.push("name"+it+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||w.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),w.push(",.*:")})),(L.matchesSelector=gt.test(k=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&n(function(e){L.disconnectedMatch=k.call(e,"div"),k.call(e,"[s!='']:x"),G.push("!=",at)}),w=w.length&&new RegExp(w.join("|")),G=G.length&&new RegExp(G.join("|")),t=gt.test(_.compareDocumentPosition),B=t||gt.test(_.contains)?function(e,t){var r=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(r.contains?r.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},z=t?function(e,t){if(e===t)return O=!0,0;var i=!e.compareDocumentPosition-!t.compareDocumentPosition;return i?i:(i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&i||!L.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?tt.call(b,e)-tt.call(b,t):0:4&i?-1:1)}:function(e,t){if(e===t)return O=!0,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?tt.call(b,e)-tt.call(b,t):0;if(o===a)return s(e,t);for(i=e;i=i.parentNode;)l.unshift(i);for(i=t;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},r):D},t.matches=function(e,r){return t(e,null,null,r)},t.matchesSelector=function(e,r){if((e.ownerDocument||e)!==D&&P(e),r=r.replace(ct,"='$1']"),!(!L.matchesSelector||!M||G&&G.test(r)||w&&w.test(r)))try{var i=k.call(e,r);if(i||L.disconnectedMatch||e.document&&11!==e.document.nodeType)return i}catch(n){}return t(r,D,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==D&&P(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var r=T.attrHandle[t.toLowerCase()],i=r&&K.call(T.attrHandle,t.toLowerCase())?r(e,t,!M):void 0;return void 0!==i?i:L.attributes||!M?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,r=[],i=0,n=0;if(O=!L.detectDuplicates,b=!L.sortStable&&e.slice(0),e.sort(z),O){for(;t=e[n++];)t===e[n]&&(i=r.push(n));for(;i--;)e.splice(r[i],1)}return b=null,e},I=t.getText=function(e){var t,r="",i=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)r+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[i++];)r+=I(t);return r},T=t.selectors={cacheLength:50,createPseudo:i,match:Et,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(Lt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(Lt,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]||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,r=!e[6]&&e[2];return Et.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":r&&dt.test(r)&&(t=A(r,!0))&&(t=r.indexOf(")",r.length-t)-r.length)&&(e[0]=e[0].slice(0,t),e[2]=r.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Lt,Tt).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||typeof e.getAttribute!==X&&e.getAttribute("class")||"")})},ATTR:function(e,r,i){return function(n){var o=t.attr(n,e);return null==o?"!="===r:r?(o+="","="===r?o===i:"!="===r?o!==i:"^="===r?i&&0===o.indexOf(i):"*="===r?i&&o.indexOf(i)>-1:"$="===r?i&&o.slice(-i.length)===i:"~="===r?(" "+o+" ").indexOf(i)>-1:"|="===r?o===i||o.slice(0,i.length+1)===i+"-":!1):!0}},CHILD:function(e,t,r,i,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===i&&0===n?function(e){return!!e.parentNode}:function(t,r,l){var u,p,c,d,h,E,f=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;f;){for(c=t;c=c[f];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;E=f="only"===e&&!E&&"nextSibling"}return!0}if(E=[s?m.firstChild:m.lastChild],s&&v){for(p=m[U]||(m[U]={}),u=p[e]||[],h=u[0]===H&&u[1],d=u[0]===H&&u[2],c=h&&m.childNodes[h];c=++h&&c&&c[f]||(d=h=0)||E.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[H,h,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===H)d=u[1];else for(;(c=++h&&c&&c[f]||(d=h=0)||E.pop())&&((a?c.nodeName.toLowerCase()!==g:1!==c.nodeType)||!++d||(v&&((c[U]||(c[U]={}))[e]=[H,d]),c!==t)););return d-=n,d===i||d%i===0&&d/i>=0}}},PSEUDO:function(e,r){var n,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[U]?o(r):o.length>1?(n=[e,e,"",r],T.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,t){for(var i,n=o(e,r),s=n.length;s--;)i=tt.call(e,n[s]),e[i]=!(t[i]=n[s])}):function(e){return o(e,0,n)}):o}},pseudos:{not:i(function(e){var t=[],r=[],n=S(e.replace(lt,"$1"));return n[U]?i(function(e,t,r,i){for(var o,s=n(e,null,i,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,n(t,null,o,r),!r.pop()}}),has:i(function(e){return function(r){return t(e,r).length>0}}),contains:i(function(e){return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:i(function(e){return ht.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(Lt,Tt).toLowerCase(),function(t){var r;do if(r=M?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return r=r.toLowerCase(),r===e||0===r.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var r=e.location&&e.location.hash;return r&&r.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return ft.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,r){return[0>r?r+t:r]}),even:u(function(e,t){for(var r=0;t>r;r+=2)e.push(r);return e}),odd:u(function(e,t){for(var r=1;t>r;r+=2)e.push(r);return e}),lt:u(function(e,t,r){for(var i=0>r?r+t:r;--i>=0;)e.push(i);return e}),gt:u(function(e,t,r){for(var i=0>r?r+t:r;++i<t;)e.push(i);return e})}},T.pseudos.nth=T.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})T.pseudos[N]=l(N);return c.prototype=T.filters=T.pseudos,T.setFilters=new c,A=t.tokenize=function(e,r){var i,n,o,s,a,l,u,p=W[e+" "];if(p)return r?0:p.slice(0);for(a=e,l=[],u=T.preFilter;a;){(!i||(n=ut.exec(a)))&&(n&&(a=a.slice(n[0].length)||a),l.push(o=[])),i=!1,(n=pt.exec(a))&&(i=n.shift(),o.push({value:i,type:n[0].replace(lt," ")}),a=a.slice(i.length));for(s in T.filter)!(n=Et[s].exec(a))||u[s]&&!(n=u[s](n))||(i=n.shift(),o.push({value:i,type:s,matches:n}),a=a.slice(i.length));if(!i)break}return r?a.length:a?t.error(e):W(e,l).slice(0)},S=t.compile=function(e,t){var r,i=[],n=[],o=q[e+" "];if(!o){for(t||(t=A(e)),r=t.length;r--;)o=v(t[r]),o[U]?i.push(o):n.push(o);o=q(e,x(n,i)),o.selector=e}return o},C=t.select=function(e,t,r,i){var n,o,s,a,l,u="function"==typeof e&&e,c=!i&&A(e=u.selector||e);if(r=r||[],1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(s=o[0]).type&&L.getById&&9===t.nodeType&&M&&T.relative[o[1].type]){if(t=(T.find.ID(s.matches[0].replace(Lt,Tt),t)||[])[0],!t)return r;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(n=Et.needsContext.test(e)?0:o.length;n--&&(s=o[n],!T.relative[a=s.type]);)if((l=T.find[a])&&(i=l(s.matches[0].replace(Lt,Tt),xt.test(o[0].type)&&p(t.parentNode)||t))){if(o.splice(n,1),e=i.length&&d(o),!e)return J.apply(r,i),r;break}}return(u||S(e,c))(i,t,!M,r,xt.test(e)&&p(t.parentNode)||t),r},L.sortStable=U.split("").sort(z).join("")===U,L.detectDuplicates=!!O,P(),L.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))}),n(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,r){return r?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),L.attributes&&n(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,r){return r||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),n(function(e){return null==e.getAttribute("disabled")})||o(rt,function(e,t,r){var i;return r?void 0:e[t]===!0?t.toLowerCase():(i=e.getAttributeNode(t))&&i.specified?i.value:null}),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>|)$/,ht=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,r){var i=t[0];return r&&(e=":not("+e+")"),1===t.length&&1===i.nodeType?ot.find.matchesSelector(i,e)?[i]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))},ot.fn.extend({find:function(e){var t,r=[],i=this,n=i.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(i[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,i[t],r);return r=this.pushStack(n>1?ot.unique(r):r),r.selector=this.selector?this.selector+" "+e:e,r},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 Et,ft=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||Et).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ot?t[0]:t,ot.merge(this,ot.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:ft,!0)),dt.test(r[1])&&ot.isPlainObject(t))for(r in t)ot.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}if(i=ft.getElementById(r[2]),i&&i.parentNode){if(i.id!==r[2])return Et.find(e);this.length=1,this[0]=i}return this.context=ft,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ot.isFunction(e)?"undefined"!=typeof Et.ready?Et.ready(e):e(ot):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ot.makeArray(e,this))};gt.prototype=ot.fn,Et=ot(ft);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,r){for(var i=[],n=e[t];n&&9!==n.nodeType&&(void 0===r||1!==n.nodeType||!ot(n).is(r));)1===n.nodeType&&i.push(n),n=n[t];return i},sibling:function(e,t){for(var r=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&r.push(e);return r}}),ot.fn.extend({has:function(e){var t,r=ot(e,this),i=r.length;return this.filter(function(){for(t=0;i>t;t++)if(ot.contains(this,r[t]))return!0})},closest:function(e,t){for(var r,i=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>i;i++)for(r=this[i];r&&r!==t;r=r.parentNode)if(r.nodeType<11&&(s?s.index(r)>-1:1===r.nodeType&&ot.find.matchesSelector(r,e))){o.push(r);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,r){return ot.dir(e,"parentNode",r)},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,r){return ot.dir(e,"nextSibling",r)},prevUntil:function(e,t,r){return ot.dir(e,"previousSibling",r)},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(r,i){var n=ot.map(this,t,r);return"Until"!==e.slice(-5)&&(i=r),i&&"string"==typeof i&&(n=ot.filter(i,n)),this.length>1&&(xt[e]||(n=ot.unique(n)),vt.test(e)&&(n=n.reverse())),this.pushStack(n)}});var Nt=/\S+/g,Lt={};ot.Callbacks=function(e){e="string"==typeof e?Lt[e]||s(e):ot.extend({},e);var t,r,i,n,o,a,l=[],u=!e.once&&[],p=function(s){for(r=e.memory&&s,i=!0,o=a||0,a=0,n=l.length,t=!0;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){r=!1;break}t=!1,l&&(u?u.length&&p(u.shift()):r?l=[]:c.disable())},c={add:function(){if(l){var i=l.length;!function o(t){ot.each(t,function(t,r){var i=ot.type(r);"function"===i?e.unique&&c.has(r)||l.push(r):r&&r.length&&"string"!==i&&o(r)})}(arguments),t?n=l.length:r&&(a=i,p(r))}return this},remove:function(){return l&&ot.each(arguments,function(e,r){for(var i;(i=ot.inArray(r,l,i))>-1;)l.splice(i,1),t&&(n>=i&&n--,o>=i&&o--)}),this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],n=0,this},disable:function(){return l=u=r=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,r||c.disable(),this},locked:function(){return!u},fireWith:function(e,r){return!l||i&&!u||(r=r||[],r=[e,r.slice?r.slice():r],t?u.push(r):p(r)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!i}};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")]],r="pending",i={state:function(){return r},always:function(){return n.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ot.Deferred(function(r){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(r.resolve).fail(r.reject).progress(r.notify):r[o[0]+"With"](this===i?r.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,i):i}},n={};return i.pipe=i.then,ot.each(t,function(e,o){var s=o[2],a=o[3];i[o[1]]=s.add,a&&s.add(function(){r=a},t[1^e][2].disable,t[2][2].lock),n[o[0]]=function(){return n[o[0]+"With"](this===n?i:this,arguments),this},n[o[0]+"With"]=s.fireWith}),i.promise(n),e&&e.call(n,n),n},when:function(e){var t,r,i,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,r,i){return function(n){r[e]=this,i[e]=arguments.length>1?$.call(arguments):n,i===t?l.notifyWith(r,i):--a||l.resolveWith(r,i)}};if(s>1)for(t=new Array(s),r=new Array(s),i=new Array(s);s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,i,o)).fail(l.reject).progress(u(n,r,t)):--a;return a||l.resolveWith(i,o),l.promise()}});var Tt;ot.fn.ready=function(e){return ot.ready.promise().done(e),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(!ft.body)return setTimeout(ot.ready);ot.isReady=!0,e!==!0&&--ot.readyWait>0||(Tt.resolveWith(ft,[ot]),ot.fn.triggerHandler&&(ot(ft).triggerHandler("ready"),ot(ft).off("ready")))}}}),ot.ready.promise=function(e){if(!Tt)if(Tt=ot.Deferred(),"complete"===ft.readyState)setTimeout(ot.ready);else if(ft.addEventListener)ft.addEventListener("DOMContentLoaded",l,!1),t.addEventListener("load",l,!1);else{ft.attachEvent("onreadystatechange",l),t.attachEvent("onload",l);var r=!1;try{r=null==t.frameElement&&ft.documentElement}catch(i){}r&&r.doScroll&&!function n(){if(!ot.isReady){try{r.doScroll("left") }catch(e){return setTimeout(n,50)}a(),ot.ready()}}()}return Tt.promise(e)};var It,yt="undefined";for(It in ot(it))break;it.ownLast="0"!==It,it.inlineBlockNeedsLayout=!1,ot(function(){var e,t,r,i;r=ft.getElementsByTagName("body")[0],r&&r.style&&(t=ft.createElement("div"),i=ft.createElement("div"),i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",r.appendChild(i).appendChild(t),typeof t.style.zoom!==yt&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",it.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(r.style.zoom=1)),r.removeChild(i))}),function(){var e=ft.createElement("div");if(null==it.deleteExpando){it.deleteExpando=!0;try{delete e.test}catch(t){it.deleteExpando=!1}}e=null}(),ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],r=+e.nodeType||1;return 1!==r&&9!==r?!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){return e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando],!!e&&!p(e)},data:function(e,t,r){return c(e,t,r)},removeData:function(e,t){return d(e,t)},_data:function(e,t,r){return c(e,t,r,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ot.fn.extend({data:function(e,t){var r,i,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length&&(n=ot.data(o),1===o.nodeType&&!ot._data(o,"parsedAttrs"))){for(r=s.length;r--;)s[r]&&(i=s[r].name,0===i.indexOf("data-")&&(i=ot.camelCase(i.slice(5)),u(o,i,n[i])));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,r){var i;return e?(t=(t||"fx")+"queue",i=ot._data(e,t),r&&(!i||ot.isArray(r)?i=ot._data(e,t,ot.makeArray(r)):i.push(r)),i||[]):void 0},dequeue:function(e,t){t=t||"fx";var r=ot.queue(e,t),i=r.length,n=r.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};"inprogress"===n&&(n=r.shift(),i--),n&&("fx"===t&&r.unshift("inprogress"),delete o.stop,n.call(e,s,o)),!i&&o&&o.empty.fire()},_queueHooks:function(e,t){var r=t+"queueHooks";return ot._data(e,r)||ot._data(e,r,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue"),ot._removeData(e,r)})})}}),ot.fn.extend({queue:function(e,t){var r=2;return"string"!=typeof e&&(t=e,e="fx",r--),arguments.length<r?ot.queue(this[0],e):void 0===t?this:this.each(function(){var r=ot.queue(this,e,t);ot._queueHooks(this,e),"fx"===e&&"inprogress"!==r[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 r,i=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--i||n.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)r=ot._data(o[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){return e=t||e,"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,r,i,n,o,s){var a=0,l=e.length,u=null==r;if("object"===ot.type(r)){n=!0;for(a in r)ot.access(e,t,a,r[a],!0,o,s)}else if(void 0!==i&&(n=!0,ot.isFunction(i)||(s=!0),u&&(s?(t.call(e,i),t=null):(u=t,t=function(e,t,r){return u.call(ot(e),r)})),t))for(;l>a;a++)t(e[a],r,s?i:i.call(e[a],a,t(e[a],r)));return n?e:u?t.call(e):l?t(e[0],r):o},Pt=/^(?:checkbox|radio)$/i;!function(){var e=ft.createElement("input"),t=ft.createElement("div"),r=ft.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",it.leadingWhitespace=3===t.firstChild.nodeType,it.tbody=!t.getElementsByTagName("tbody").length,it.htmlSerialize=!!t.getElementsByTagName("link").length,it.html5Clone="<:nav></:nav>"!==ft.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,r.appendChild(e),it.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",it.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,r.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",it.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,it.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){it.noCloneEvent=!1}),t.cloneNode(!0).click()),null==it.deleteExpando){it.deleteExpando=!0;try{delete t.test}catch(i){it.deleteExpando=!1}}}(),function(){var e,r,i=ft.createElement("div");for(e in{submit:!0,change:!0,focusin:!0})r="on"+e,(it[e+"Bubbles"]=r in t)||(i.setAttribute(r,"t"),it[e+"Bubbles"]=i.attributes[r].expando===!1);i=null}();var Dt=/^(?:input|select|textarea)$/i,_t=/^key/,Mt=/^(?:mouse|pointer|contextmenu)|click/,wt=/^(?:focusinfocus|focusoutblur)$/,Gt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,r,i,n){var o,s,a,l,u,p,c,d,h,E,f,m=ot._data(e);if(m){for(r.handler&&(l=r,r=l.handler,n=l.selector),r.guid||(r.guid=ot.guid++),(s=m.events)||(s=m.events={}),(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;a--;)o=Gt.exec(t[a])||[],h=f=o[1],E=(o[2]||"").split(".").sort(),h&&(u=ot.event.special[h]||{},h=(n?u.delegateType:u.bindType)||h,u=ot.event.special[h]||{},c=ot.extend({type:h,origType:f,data:i,handler:r,guid:r.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:E.join(".")},l),(d=s[h])||(d=s[h]=[],d.delegateCount=0,u.setup&&u.setup.call(e,i,E,p)!==!1||(e.addEventListener?e.addEventListener(h,p,!1):e.attachEvent&&e.attachEvent("on"+h,p))),u.add&&(u.add.call(e,c),c.handler.guid||(c.handler.guid=r.guid)),n?d.splice(d.delegateCount++,0,c):d.push(c),ot.event.global[h]=!0);e=null}},remove:function(e,t,r,i,n){var o,s,a,l,u,p,c,d,h,E,f,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){for(t=(t||"").match(Nt)||[""],u=t.length;u--;)if(a=Gt.exec(t[u])||[],h=f=a[1],E=(a[2]||"").split(".").sort(),h){for(c=ot.event.special[h]||{},h=(i?c.delegateType:c.bindType)||h,d=p[h]||[],a=a[2]&&new RegExp("(^|\\.)"+E.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;o--;)s=d[o],!n&&f!==s.origType||r&&r.guid!==s.guid||a&&!a.test(s.namespace)||i&&i!==s.selector&&("**"!==i||!s.selector)||(d.splice(o,1),s.selector&&d.delegateCount--,c.remove&&c.remove.call(e,s));l&&!d.length&&(c.teardown&&c.teardown.call(e,E,m.handle)!==!1||ot.removeEvent(e,h,m.handle),delete p[h])}else for(h in p)ot.event.remove(e,h+t[u],r,i,!0);ot.isEmptyObject(p)&&(delete m.handle,ot._removeData(e,"events"))}},trigger:function(e,r,i,n){var o,s,a,l,u,p,c,d=[i||ft],h=rt.call(e,"type")?e.type:e,E=rt.call(e,"namespace")?e.namespace.split("."):[];if(a=p=i=i||ft,3!==i.nodeType&&8!==i.nodeType&&!wt.test(h+ot.event.triggered)&&(h.indexOf(".")>=0&&(E=h.split("."),h=E.shift(),E.sort()),s=h.indexOf(":")<0&&"on"+h,e=e[ot.expando]?e:new ot.Event(h,"object"==typeof e&&e),e.isTrigger=n?2:3,e.namespace=E.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+E.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=i),r=null==r?[e]:ot.makeArray(r,[e]),u=ot.event.special[h]||{},n||!u.trigger||u.trigger.apply(i,r)!==!1)){if(!n&&!u.noBubble&&!ot.isWindow(i)){for(l=u.delegateType||h,wt.test(l+h)||(a=a.parentNode);a;a=a.parentNode)d.push(a),p=a;p===(i.ownerDocument||ft)&&d.push(p.defaultView||p.parentWindow||t)}for(c=0;(a=d[c++])&&!e.isPropagationStopped();)e.type=c>1?l:u.bindType||h,o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle"),o&&o.apply(a,r),o=s&&a[s],o&&o.apply&&ot.acceptData(a)&&(e.result=o.apply(a,r),e.result===!1&&e.preventDefault());if(e.type=h,!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),r)===!1)&&ot.acceptData(i)&&s&&i[h]&&!ot.isWindow(i)){p=i[s],p&&(i[s]=null),ot.event.triggered=h;try{i[h]()}catch(f){}ot.event.triggered=void 0,p&&(i[s]=p)}return e.result}},dispatch:function(e){e=ot.event.fix(e);var t,r,i,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=ot.event.handlers.call(this,e,l),t=0;(n=s[t++])&&!e.isPropagationStopped();)for(e.currentTarget=n.elem,o=0;(i=n.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((ot.event.special[i.origType]||{}).handle||i.handler).apply(n.elem,a),void 0!==r&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var r,i,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)){for(n=[],o=0;a>o;o++)i=t[o],r=i.selector+" ",void 0===n[r]&&(n[r]=i.needsContext?ot(r,this).index(l)>=0:ot.find(r,this,null,[l]).length),n[r]&&n.push(i);n.length&&s.push({elem:l,handlers:n})}return a<t.length&&s.push({elem:this,handlers:t.slice(a)}),s},fix:function(e){if(e[ot.expando])return e;var t,r,i,n=e.type,o=e,s=this.fixHooks[n];for(s||(this.fixHooks[n]=s=Mt.test(n)?this.mouseHooks:_t.test(n)?this.keyHooks:{}),i=s.props?this.props.concat(s.props):this.props,e=new ot.Event(o),t=i.length;t--;)r=i[t],e[r]=o[r];return e.target||(e.target=o.srcElement||ft),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,t){var r,i,n,o=t.button,s=t.fromElement;return null==e.pageX&&null!=t.clientX&&(i=e.target.ownerDocument||ft,n=i.documentElement,r=i.body,e.pageX=t.clientX+(n&&n.scrollLeft||r&&r.scrollLeft||0)-(n&&n.clientLeft||r&&r.clientLeft||0),e.pageY=t.clientY+(n&&n.scrollTop||r&&r.scrollTop||0)-(n&&n.clientTop||r&&r.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),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==f()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===f()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_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,r,i){var n=ot.extend(new ot.Event,r,{type:e,isSimulated:!0,originalEvent:{}});i?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n),n.isDefaultPrevented()&&r.preventDefault()}},ot.removeEvent=ft.removeEventListener?function(e,t,r){e.removeEventListener&&e.removeEventListener(t,r,!1)}:function(e,t,r){var i="on"+t;e.detachEvent&&(typeof e[i]===yt&&(e[i]=null),e.detachEvent(i,r))},ot.Event=function(e,t){return this instanceof ot.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?h:E):this.type=e,t&&ot.extend(this,t),this.timeStamp=e&&e.timeStamp||ot.now(),void(this[ot.expando]=!0)):new ot.Event(e,t)},ot.Event.prototype={isDefaultPrevented:E,isPropagationStopped:E,isImmediatePropagationStopped:E,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=h,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=h,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=h,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 r,i=this,n=e.relatedTarget,o=e.handleObj;return(!n||n!==i&&!ot.contains(i,n))&&(e.type=o.origType,r=o.handler.apply(this,arguments),e.type=t),r}}}),it.submitBubbles||(ot.event.special.submit={setup:function(){return ot.nodeName(this,"form")?!1:void ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,r=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;r&&!ot._data(r,"submitBubbles")&&(ot.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),ot._data(r,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ot.nodeName(this,"form")?!1:void ot.event.remove(this,"._submit")}}),it.changeBubbles||(ot.event.special.change={setup:function(){return Dt.test(this.nodeName)?(("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)})),!1):void ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;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(){return ot.event.remove(this,"._change"),!Dt.test(this.nodeName)}}),it.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var r=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var i=this.ownerDocument||this,n=ot._data(i,t);n||i.addEventListener(e,r,!0),ot._data(i,t,(n||0)+1)},teardown:function(){var i=this.ownerDocument||this,n=ot._data(i,t)-1;n?ot._data(i,t,n):(i.removeEventListener(e,r,!0),ot._removeData(i,t))}}}),ot.fn.extend({on:function(e,t,r,i,n){var o,s;if("object"==typeof e){"string"!=typeof t&&(r=r||t,t=void 0);for(o in e)this.on(o,t,r,e[o],n);return this}if(null==r&&null==i?(i=t,r=t=void 0):null==i&&("string"==typeof t?(i=r,r=void 0):(i=r,r=t,t=void 0)),i===!1)i=E;else if(!i)return this;return 1===n&&(s=i,i=function(e){return ot().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=ot.guid++)),this.each(function(){ot.event.add(this,e,i,r,t)})},one:function(e,t,r,i){return this.on(e,t,r,i,1)},off:function(e,t,r){var i,n;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,ot(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}return(t===!1||"function"==typeof t)&&(r=t,t=void 0),r===!1&&(r=E),this.each(function(){ot.event.remove(this,e,r,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var r=this[0];return r?ot.event.trigger(e,t,r,!0):void 0}});var kt="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("<(?:"+kt+")[\\s/>]","i"),Vt=/^\s+/,Ht=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ft=/<([\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:it.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(ft),Zt=Qt.appendChild(ft.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,r){var i,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(it.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Zt.innerHTML=e.outerHTML,Zt.removeChild(o=Zt.firstChild)),!(it.noCloneEvent&&it.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e)))for(i=g(o),a=g(e),s=0;null!=(n=a[s]);++s)i[s]&&y(n,i[s]);if(t)if(r)for(a=a||g(e),i=i||g(o),s=0;null!=(n=a[s]);s++)I(n,i[s]);else I(e,o);return i=g(o,"script"),i.length>0&&T(i,!l&&g(e,"script")),i=a=n=null,o},buildFragment:function(e,t,r,i){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),h=[],E=0;c>E;E++)if(o=e[E],o||0===o)if("object"===ot.type(o))ot.merge(h,o.nodeType?[o]:o);else if(Wt.test(o)){for(a=a||d.appendChild(t.createElement("div")),l=(Ft.exec(o)||["",""])[1].toLowerCase(),p=$t[l]||$t._default,a.innerHTML=p[1]+o.replace(Ht,"<$1></$2>")+p[2],n=p[0];n--;)a=a.lastChild;if(!it.leadingWhitespace&&Vt.test(o)&&h.push(t.createTextNode(Vt.exec(o)[0])),!it.tbody)for(o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild,n=o&&o.childNodes.length;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(ot.merge(h,a.childNodes),a.textContent="";a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else h.push(t.createTextNode(o));for(a&&d.removeChild(a),it.appendChecked||ot.grep(g(h,"input"),v),E=0;o=h[E++];)if((!i||-1===ot.inArray(o,i))&&(s=ot.contains(o.ownerDocument,o),a=g(d.appendChild(o),"script"),s&&T(a),r))for(n=0;o=a[n++];)Xt.test(o.type||"")&&r.push(o);return a=null,d},cleanData:function(e,t){for(var r,i,n,o,s=0,a=ot.expando,l=ot.cache,u=it.deleteExpando,p=ot.event.special;null!=(r=e[s]);s++)if((t||ot.acceptData(r))&&(n=r[a],o=n&&l[n])){if(o.events)for(i in o.events)p[i]?ot.event.remove(r,i):ot.removeEvent(r,i,o.handle);l[n]&&(delete l[n],u?delete r[a]:typeof r.removeAttribute!==yt?r.removeAttribute(a):r[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||ft).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 r,i=e?ot.filter(e,this):this,n=0;null!=(r=i[n]);n++)t||1!==r.nodeType||ot.cleanData(g(r)),r.parentNode&&(t&&ot.contains(r.ownerDocument,r)&&T(g(r,"script")),r.parentNode.removeChild(r));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ot.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.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 ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},r=0,i=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!it.htmlSerialize&&Ut.test(e)||!it.leadingWhitespace&&Vt.test(e)||$t[(Ft.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ht,"<$1></$2>");try{for(;i>r;r++)t=this[r]||{},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];return this.domManip(arguments,function(t){e=this.parentNode,ot.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=Q.apply([],e);var r,i,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],h=ot.isFunction(d);if(h||u>1&&"string"==typeof d&&!it.checkClone&&zt.test(d))return this.each(function(r){var i=p.eq(r);h&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t)});if(u&&(a=ot.buildFragment(e,this[0].ownerDocument,!1,this),r=a.firstChild,1===a.childNodes.length&&(a=r),r)){for(o=ot.map(g(a,"script"),N),n=o.length;u>l;l++)i=a,l!==c&&(i=ot.clone(i,!0,!0),n&&ot.merge(o,g(i,"script"))),t.call(this[l],i,l);if(n)for(s=o[o.length-1].ownerDocument,ot.map(o,L),l=0;n>l;l++)i=o[l],Xt.test(i.type||"")&&!ot._data(i,"globalEval")&&ot.contains(s,i)&&(i.src?ot._evalUrl&&ot._evalUrl(i.src):ot.globalEval((i.text||i.textContent||i.innerHTML||"").replace(Kt,"")));a=r=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 r,i=0,n=[],o=ot(e),s=o.length-1;s>=i;i++)r=i===s?this:this.clone(!0),ot(o[i])[t](r),Z.apply(n,r.get());return this.pushStack(n)}});var Jt,er={};!function(){var e;it.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,r,i;return r=ft.getElementsByTagName("body")[0],r&&r.style?(t=ft.createElement("div"),i=ft.createElement("div"),i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",r.appendChild(i).appendChild(t),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(ft.createElement("div")).style.width="5px",e=3!==t.offsetWidth),r.removeChild(i),e):void 0}}();var tr,rr,ir=/^margin/,nr=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),or=/^(top|right|bottom|left)$/;t.getComputedStyle?(tr=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},rr=function(e,t,r){var i,n,o,s,a=e.style;return r=r||tr(e),s=r?r.getPropertyValue(t)||r[t]:void 0,r&&(""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t)),nr.test(s)&&ir.test(t)&&(i=a.width,n=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=s,s=r.width,a.width=i,a.minWidth=n,a.maxWidth=o)),void 0===s?s:s+""}):ft.documentElement.currentStyle&&(tr=function(e){return e.currentStyle},rr=function(e,t,r){var i,n,o,s,a=e.style;return r=r||tr(e),s=r?r[t]:void 0,null==s&&a&&a[t]&&(s=a[t]),nr.test(s)&&!or.test(t)&&(i=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=i,o&&(n.left=o)),void 0===s?s:s+""||"auto"}),function(){function e(){var e,r,i,n;r=ft.getElementsByTagName("body")[0],r&&r.style&&(e=ft.createElement("div"),i=ft.createElement("div"),i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",r.appendChild(i).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,t.getComputedStyle&&(o="1%"!==(t.getComputedStyle(e,null)||{}).top,s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width,n=e.appendChild(ft.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.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,a&&(n[0].style.display="",n[1].style.display="none",a=0===n[0].offsetHeight),r.removeChild(i))}var r,i,n,o,s,a,l;r=ft.createElement("div"),r.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=r.getElementsByTagName("a")[0],i=n&&n.style,i&&(i.cssText="float:left;opacity:.5",it.opacity="0.5"===i.opacity,it.cssFloat=!!i.cssFloat,r.style.backgroundClip="content-box",r.cloneNode(!0).style.backgroundClip="",it.clearCloneStyle="content-box"===r.style.backgroundClip,it.boxSizing=""===i.boxSizing||""===i.MozBoxSizing||""===i.WebkitBoxSizing,ot.extend(it,{reliableHiddenOffsets:function(){return null==a&&e(),a},boxSizingReliable:function(){return null==s&&e(),s},pixelPosition:function(){return null==o&&e(),o},reliableMarginRight:function(){return null==l&&e(),l}}))}(),ot.swap=function(e,t,r,i){var n,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];n=r.apply(e,i||[]);for(o in t)e.style[o]=s[o];return n};var sr=/alpha\([^)]*\)/i,ar=/opacity\s*=\s*([^)]*)/,lr=/^(none|table(?!-c[ea]).+)/,ur=new RegExp("^("+Ct+")(.*)$","i"),pr=new RegExp("^([+-])=("+Ct+")","i"),cr={position:"absolute",visibility:"hidden",display:"block"},dr={letterSpacing:"0",fontWeight:"400"},hr=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var r=rr(e,"opacity");return""===r?"1":r}}}},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":it.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;if(t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a)),s=ot.cssHooks[t]||ot.cssHooks[a],void 0===r)return s&&"get"in s&&void 0!==(n=s.get(e,!1,i))?n:l[t];if(o=typeof r,"string"===o&&(n=pr.exec(r))&&(r=(n[1]+1)*n[2]+parseFloat(ot.css(e,t)),o="number"),null!=r&&r===r&&("number"!==o||ot.cssNumber[a]||(r+="px"),it.clearCloneStyle||""!==r||0!==t.indexOf("background")||(l[t]="inherit"),!(s&&"set"in s&&void 0===(r=s.set(e,r,i)))))try{l[t]=r}catch(u){}}},css:function(e,t,r,i){var n,o,s,a=ot.camelCase(t);return 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,r)),void 0===o&&(o=rr(e,t,i)),"normal"===o&&t in dr&&(o=dr[t]),""===r||r?(n=parseFloat(o),r===!0||ot.isNumeric(n)?n||0:o):o}}),ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,r,i){return r?lr.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,cr,function(){return D(e,t,i)}):D(e,t,i):void 0},set:function(e,r,i){var n=i&&tr(e);return O(e,r,i?P(e,t,i,it.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}}),it.opacity||(ot.cssHooks.opacity={get:function(e,t){return ar.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var r=e.style,i=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=i&&i.filter||r.filter||"";r.zoom=1,(t>=1||""===t)&&""===ot.trim(o.replace(sr,""))&&r.removeAttribute&&(r.removeAttribute("filter"),""===t||i&&!i.filter)||(r.filter=sr.test(o)?o.replace(sr,n):o+" "+n)}}),ot.cssHooks.marginRight=C(it.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},rr,[e,"marginRight"]):void 0}),ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(r){for(var i=0,n={},o="string"==typeof r?r.split(" "):[r];4>i;i++)n[e+Rt[i]+t]=o[i]||o[i-2]||o[0];return n}},ir.test(e)||(ot.cssHooks[e+t].set=O)}),ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,r){var i,n,o={},s=0;if(ot.isArray(t)){for(i=tr(e),n=t.length;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,i);return o}return void 0!==r?ot.style(e,t,r):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=_,_.prototype={constructor:_,init:function(e,t,r,i,n,o){this.elem=e,this.prop=r,this.easing=n||"swing",this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=o||(ot.cssNumber[r]?"":"px")},cur:function(){var e=_.propHooks[this.prop];return e&&e.get?e.get(this):_.propHooks._default.get(this)},run:function(e){var t,r=_.propHooks[this.prop];return 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),r&&r.set?r.set(this):_.propHooks._default.set(this),this}},_.prototype.init.prototype=_.prototype,_.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ot.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},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}}},_.propHooks.scrollTop=_.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=_.prototype.init,ot.fx.step={};var Er,fr,mr=/^(?:toggle|show|hide)$/,gr=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vr=/queueHooks$/,xr=[k],Nr={"*":[function(e,t){var r=this.createTween(e,t),i=r.cur(),n=gr.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+i)&&gr.exec(ot.css(r.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3],n=n||[],s=+i||1;do a=a||".5",s/=a,ot.style(r.elem,e,s+o);while(a!==(a=r.cur()/i)&&1!==a&&--l)}return n&&(s=r.start=+s||+i||0,r.unit=o,r.end=n[1]?s+(n[1]+1)*n[2]:+n[2]),r}]};ot.Animation=ot.extend(U,{tweener:function(e,t){ot.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var r,i=0,n=e.length;n>i;i++)r=e[i],Nr[r]=Nr[r]||[],Nr[r].unshift(t)},prefilter:function(e,t){t?xr.unshift(e):xr.push(e)}}),ot.speed=function(e,t,r){var i=e&&"object"==typeof e?ot.extend({},e):{complete:r||!r&&t||ot.isFunction(e)&&e,duration:e,easing:r&&t||t&&!ot.isFunction(t)&&t};return i.duration=ot.fx.off?0:"number"==typeof i.duration?i.duration:i.duration in ot.fx.speeds?ot.fx.speeds[i.duration]:ot.fx.speeds._default,(null==i.queue||i.queue===!0)&&(i.queue="fx"),i.old=i.complete,i.complete=function(){ot.isFunction(i.old)&&i.old.call(this),i.queue&&ot.dequeue(this,i.queue)},i},ot.fn.extend({fadeTo:function(e,t,r,i){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,r,i)},animate:function(e,t,r,i){var n=ot.isEmptyObject(e),o=ot.speed(t,r,i),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};return s.finish=s,n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),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&&i(s[n]);else for(n in s)s[n]&&s[n].stop&&vr.test(n)&&i(s[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)&&ot.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,r=ot._data(this),i=r[e+"queue"],n=r[e+"queueHooks"],o=ot.timers,s=i?i.length:0;for(r.finish=!0,ot.queue(this,e,[]),n&&n.stop&&n.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;s>t;t++)i[t]&&i[t].finish&&i[t].finish.call(this); delete r.finish})}}),ot.each(["toggle","show","hide"],function(e,t){var r=ot.fn[t];ot.fn[t]=function(e,i,n){return null==e||"boolean"==typeof e?r.apply(this,arguments):this.animate(w(t,!0),e,i,n)}}),ot.each({slideDown:w("show"),slideUp:w("hide"),slideToggle:w("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,r,i){return this.animate(t,e,r,i)}}),ot.timers=[],ot.fx.tick=function(){var e,t=ot.timers,r=0;for(Er=ot.now();r<t.length;r++)e=t[r],e()||t[r]!==e||t.splice(r--,1);t.length||ot.fx.stop(),Er=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(){fr||(fr=setInterval(ot.fx.tick,ot.fx.interval))},ot.fx.stop=function(){clearInterval(fr),fr=null},ot.fx.speeds={slow:600,fast:200,_default:400},ot.fn.delay=function(e,t){return e=ot.fx?ot.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,r){var i=setTimeout(t,e);r.stop=function(){clearTimeout(i)}})},function(){var e,t,r,i,n;t=ft.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=t.getElementsByTagName("a")[0],r=ft.createElement("select"),n=r.appendChild(ft.createElement("option")),e=t.getElementsByTagName("input")[0],i.style.cssText="top:1px",it.getSetAttribute="t"!==t.className,it.style=/top/.test(i.getAttribute("style")),it.hrefNormalized="/a"===i.getAttribute("href"),it.checkOn=!!e.value,it.optSelected=n.selected,it.enctype=!!ft.createElement("form").enctype,r.disabled=!0,it.optDisabled=!n.disabled,e=ft.createElement("input"),e.setAttribute("value",""),it.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),it.radioValue="t"===e.value}();var Lr=/\r/g;ot.fn.extend({val:function(e){var t,r,i,n=this[0];{if(arguments.length)return i=ot.isFunction(e),this.each(function(r){var n;1===this.nodeType&&(n=i?e.call(this,r,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)return t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(r=t.get(n,"value"))?r:(r=n.value,"string"==typeof r?r.replace(Lr,""):null==r?"":r)}}}),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,r,i=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:i.length,l=0>n?a:o?n:0;a>l;l++)if(r=i[l],!(!r.selected&&l!==n||(it.optDisabled?r.disabled:null!==r.getAttribute("disabled"))||r.parentNode.disabled&&ot.nodeName(r.parentNode,"optgroup"))){if(t=ot(r).val(),o)return t;s.push(t)}return s},set:function(e,t){for(var r,i,n=e.options,o=ot.makeArray(t),s=n.length;s--;)if(i=n[s],ot.inArray(ot.valHooks.option.get(i),o)>=0)try{i.selected=r=!0}catch(a){i.scrollHeight}else i.selected=!1;return r||(e.selectedIndex=-1),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}},it.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tr,Ir,yr=ot.expr.attrHandle,Ar=/^(?:checked|selected)$/i,Sr=it.getSetAttribute,Cr=it.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,r){var i,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===yt?ot.prop(e,t,r):(1===o&&ot.isXMLDoc(e)||(t=t.toLowerCase(),i=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ir:Tr)),void 0===r?i&&"get"in i&&null!==(n=i.get(e,t))?n:(n=ot.find.attr(e,t),null==n?void 0:n):null!==r?i&&"set"in i&&void 0!==(n=i.set(e,r,t))?n:(e.setAttribute(t,r+""),r):void ot.removeAttr(e,t))},removeAttr:function(e,t){var r,i,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;r=o[n++];)i=ot.propFix[r]||r,ot.expr.match.bool.test(r)?Cr&&Sr||!Ar.test(r)?e[i]=!1:e[ot.camelCase("default-"+r)]=e[i]=!1:ot.attr(e,r,""),e.removeAttribute(Sr?r:i)},attrHooks:{type:{set:function(e,t){if(!it.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var r=e.value;return e.setAttribute("type",t),r&&(e.value=r),t}}}}}),Ir={set:function(e,t,r){return t===!1?ot.removeAttr(e,r):Cr&&Sr||!Ar.test(r)?e.setAttribute(!Sr&&ot.propFix[r]||r,r):e[ot.camelCase("default-"+r)]=e[r]=!0,r}},ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var r=yr[t]||ot.find.attr;yr[t]=Cr&&Sr||!Ar.test(t)?function(e,t,i){var n,o;return i||(o=yr[t],yr[t]=n,n=null!=r(e,t,i)?t.toLowerCase():null,yr[t]=o),n}:function(e,t,r){return r?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}}),Cr&&Sr||(ot.attrHooks.value={set:function(e,t,r){return ot.nodeName(e,"input")?void(e.defaultValue=t):Tr&&Tr.set(e,t,r)}}),Sr||(Tr={set:function(e,t,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=t+="","value"===r||t===e.getAttribute(r)?t:void 0}},yr.id=yr.name=yr.coords=function(e,t,r){var i;return r?void 0:(i=e.getAttributeNode(t))&&""!==i.value?i.value:null},ot.valHooks.button={get:function(e,t){var r=e.getAttributeNode(t);return r&&r.specified?r.value:void 0},set:Tr.set},ot.attrHooks.contenteditable={set:function(e,t,r){Tr.set(e,""===t?!1:t,r)}},ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,r){return""===r?(e.setAttribute(t,"auto"),r):void 0}}})),it.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Rr=/^(?:input|select|textarea|button|object)$/i,br=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ot.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,r){var i,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!ot.isXMLDoc(e),o&&(t=ot.propFix[t]||t,n=ot.propHooks[t]),void 0!==r?n&&"set"in n&&void 0!==(i=n.set(e,r,t))?i:e[t]=r:n&&"get"in n&&null!==(i=n.get(e,t))?i:e[t]},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Rr.test(e.nodeName)||br.test(e.nodeName)&&e.href?0:-1}}}}),it.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),it.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this}),it.enctype||(ot.propFix.enctype="encoding");var Or=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,r,i,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)for(t=(e||"").match(Nt)||[];l>a;a++)if(r=this[a],i=1===r.nodeType&&(r.className?(" "+r.className+" ").replace(Or," "):" ")){for(o=0;n=t[o++];)i.indexOf(" "+n+" ")<0&&(i+=n+" ");s=ot.trim(i),r.className!==s&&(r.className=s)}return this},removeClass:function(e){var t,r,i,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)for(t=(e||"").match(Nt)||[];l>a;a++)if(r=this[a],i=1===r.nodeType&&(r.className?(" "+r.className+" ").replace(Or," "):"")){for(o=0;n=t[o++];)for(;i.indexOf(" "+n+" ")>=0;)i=i.replace(" "+n+" "," ");s=e?ot.trim(i):"",r.className!==s&&(r.className=s)}return this},toggleClass:function(e,t){var r=typeof e;return"boolean"==typeof t&&"string"===r?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(r){ot(this).toggleClass(e.call(this,r,this.className,t),t)}:function(){if("string"===r)for(var t,i=0,n=ot(this),o=e.match(Nt)||[];t=o[i++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else(r===yt||"boolean"===r)&&(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+" ",r=0,i=this.length;i>r;r++)if(1===this[r].nodeType&&(" "+this[r].className+" ").replace(Or," ").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,r){return arguments.length>0?this.on(t,null,e,r):this.trigger(t)}}),ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,r){return this.on(e,null,t,r)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,r,i){return this.on(t,e,r,i)},undelegate:function(e,t,r){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",r)}});var Pr=ot.now(),Dr=/\?/,_r=/(,)|(\[|{)|(}|])|"(?:[^"\\\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 r,i=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(_r,function(e,t,n,o){return r&&t&&(i=0),0===i?e:(r=n||t,i+=!o-!n,"")}))?Function("return "+n)():ot.error("Invalid JSON: "+e)},ot.parseXML=function(e){var r,i;if(!e||"string"!=typeof e)return null;try{t.DOMParser?(i=new DOMParser,r=i.parseFromString(e,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(e))}catch(n){r=void 0}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e),r};var Mr,wr,Gr=/#.*$/,kr=/([?&])_=[^&]*/,Br=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ur=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vr=/^(?:GET|HEAD)$/,Hr=/^\/\//,Fr=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,jr={},Wr={},qr="*/".concat("*");try{wr=location.href}catch(zr){wr=ft.createElement("a"),wr.href="",wr=wr.href}Mr=Fr.exec(wr.toLowerCase())||[],ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:wr,type:"GET",isLocal:Ur.test(Mr[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qr,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?F(F(e,ot.ajaxSettings),t):F(ot.ajaxSettings,e)},ajaxPrefilter:V(jr),ajaxTransport:V(Wr),ajax:function(e,t){function r(e,t,r,i){var n,p,g,v,N,T=t;2!==x&&(x=2,a&&clearTimeout(a),u=void 0,s=i||"",L.readyState=e>0?4:0,n=e>=200&&300>e||304===e,r&&(v=j(c,L,r)),v=W(c,v,L,n),n?(c.ifModified&&(N=L.getResponseHeader("Last-Modified"),N&&(ot.lastModified[o]=N),N=L.getResponseHeader("etag"),N&&(ot.etag[o]=N)),204===e||"HEAD"===c.type?T="nocontent":304===e?T="notmodified":(T=v.state,p=v.data,g=v.error,n=!g)):(g=T,(e||!T)&&(T="error",0>e&&(e=0))),L.status=e,L.statusText=(t||T)+"",n?E.resolveWith(d,[p,T,L]):E.rejectWith(d,[L,T,g]),L.statusCode(m),m=void 0,l&&h.trigger(n?"ajaxSuccess":"ajaxError",[L,c,n?p:g]),f.fireWith(d,[L,T]),l&&(h.trigger("ajaxComplete",[L,c]),--ot.active||ot.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var i,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,h=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,E=ot.Deferred(),f=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",L={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p)for(p={};t=Br.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 r=e.toLowerCase();return x||(e=v[r]=v[r]||e,g[e]=t),this},overrideMimeType:function(e){return x||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else L.always(e[L.status]);return this},abort:function(e){var t=e||N;return u&&u.abort(t),r(0,t),this}};if(E.promise(L).complete=f.add,L.success=L.done,L.error=L.fail,c.url=((e||c.url||wr)+"").replace(Gr,"").replace(Hr,Mr[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""],null==c.crossDomain&&(i=Fr.exec(c.url.toLowerCase()),c.crossDomain=!(!i||i[1]===Mr[1]&&i[2]===Mr[2]&&(i[3]||("http:"===i[1]?"80":"443"))===(Mr[3]||("http:"===Mr[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional)),H(jr,c,t,L),2===x)return L;l=c.global,l&&0===ot.active++&&ot.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Vr.test(c.type),o=c.url,c.hasContent||(c.data&&(o=c.url+=(Dr.test(o)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=kr.test(o)?o.replace(kr,"$1_="+Pr++):o+(Dr.test(o)?"&":"?")+"_="+Pr++)),c.ifModified&&(ot.lastModified[o]&&L.setRequestHeader("If-Modified-Since",ot.lastModified[o]),ot.etag[o]&&L.setRequestHeader("If-None-Match",ot.etag[o])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&L.setRequestHeader("Content-Type",c.contentType),L.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qr+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)L.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,L,c)===!1||2===x))return L.abort();N="abort";for(n in{success:1,error:1,complete:1})L[n](c[n]);if(u=H(Wr,c,t,L)){L.readyState=1,l&&h.trigger("ajaxSend",[L,c]),c.async&&c.timeout>0&&(a=setTimeout(function(){L.abort("timeout")},c.timeout));try{x=1,u.send(g,r)}catch(T){if(!(2>x))throw T;r(-1,T)}}else r(-1,"No Transport");return L},getJSON:function(e,t,r){return ot.get(e,t,r,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}}),ot.each(["get","post"],function(e,t){ot[t]=function(e,r,i,n){return ot.isFunction(r)&&(n=n||i,i=r,r=void 0),ot.ajax({url:e,type:t,dataType:n,data:r,success:i})}}),ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}}),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),r=t.contents();r.length?r.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(r){ot(this).wrapAll(t?e.call(this,r):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||!it.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))},ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xr=/%20/g,Yr=/\[\]$/,Kr=/\r?\n/g,$r=/^(?:submit|button|image|reset|file)$/i,Qr=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var r,i=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional),ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(r in e)q(r,e[r],t,n);return i.join("&").replace(Xr,"+")},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")&&Qr.test(this.nodeName)&&!$r.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var r=ot(this).val();return null==r?null:ot.isArray(r)?ot.map(r,function(e){return{name:t.name,value:e.replace(Kr,"\r\n")}}):{name:t.name,value:r.replace(Kr,"\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 Zr=0,Jr={},ei=ot.ajaxSettings.xhr();t.ActiveXObject&&ot(t).on("unload",function(){for(var e in Jr)Jr[e](void 0,!0)}),it.cors=!!ei&&"withCredentials"in ei,ei=it.ajax=!!ei,ei&&ot.ajaxTransport(function(e){if(!e.crossDomain||it.cors){var t;return{send:function(r,i){var n,o=e.xhr(),s=++Zr;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest");for(n in r)void 0!==r[n]&&o.setRequestHeader(n,r[n]+"");o.send(e.hasContent&&e.data||null),t=function(r,n){var a,l,u;if(t&&(n||4===o.readyState))if(delete Jr[s],t=void 0,o.onreadystatechange=ot.noop,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&&i(a,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Jr[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){return ot.globalEval(e),e}}}),ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,r=ft.head||ot("head")[0]||ft.documentElement;return{send:function(i,n){t=ft.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,r){(r||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,r||n(200,"success"))},r.insertBefore(t,r.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var ti=[],ri=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=ti.pop()||ot.expando+"_"+Pr++;return this[e]=!0,e}}),ot.ajaxPrefilter("json jsonp",function(e,r,i){var n,o,s,a=e.jsonp!==!1&&(ri.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ri.test(e.data)&&"data");return a||"jsonp"===e.dataTypes[0]?(n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(ri,"$1"+n):e.jsonp!==!1&&(e.url+=(Dr.test(e.url)?"&":"?")+e.jsonp+"="+n),e.converters["script json"]=function(){return s||ot.error(n+" was not called"),s[0]},e.dataTypes[0]="json",o=t[n],t[n]=function(){s=arguments},i.always(function(){t[n]=o,e[n]&&(e.jsonpCallback=r.jsonpCallback,ti.push(n)),s&&ot.isFunction(o)&&o(s[0]),s=o=void 0}),"script"):void 0}),ot.parseHTML=function(e,t,r){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(r=t,t=!1),t=t||ft;var i=dt.exec(e),n=!r&&[];return i?[t.createElement(i[1])]:(i=ot.buildFragment([e],t,n),n&&n.length&&ot(n).remove(),ot.merge([],i.childNodes))};var ii=ot.fn.load;ot.fn.load=function(e,t,r){if("string"!=typeof e&&ii)return ii.apply(this,arguments);var i,n,o,s=this,a=e.indexOf(" ");return a>=0&&(i=ot.trim(e.slice(a,e.length)),e=e.slice(0,a)),ot.isFunction(t)?(r=t,t=void 0):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(i?ot("<div>").append(ot.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,n||[e.responseText,t,e])}),this},ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var ni=t.document.documentElement;ot.offset={setOffset:function(e,t,r){var i,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,u?(i=c.position(),s=i.top,n=i.left):(s=parseFloat(o)||0,n=parseFloat(l)||0),ot.isFunction(t)&&(t=t.call(e,r,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,r,i={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o)return t=o.documentElement,ot.contains(t,n)?(typeof n.getBoundingClientRect!==yt&&(i=n.getBoundingClientRect()),r=Y(o),{top:i.top+(r.pageYOffset||t.scrollTop)-(t.clientTop||0),left:i.left+(r.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):i},position:function(){if(this[0]){var e,t,r={top:0,left:0},i=this[0];return"fixed"===ot.css(i,"position")?t=i.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ot.nodeName(e[0],"html")||(r=e.offset()),r.top+=ot.css(e[0],"borderTopWidth",!0),r.left+=ot.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-ot.css(i,"marginTop",!0),left:t.left-r.left-ot.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||ni;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||ni})}}),ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var r=/Y/.test(t);ot.fn[e]=function(i){return Ot(this,function(e,i,n){var o=Y(e);return void 0===n?o?t in o?o[t]:o.document.documentElement[i]:e[i]:void(o?o.scrollTo(r?ot(o).scrollLeft():n,r?n:ot(o).scrollTop()):e[i]=n)},e,i,arguments.length,null)}}),ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(it.pixelPosition,function(e,r){return r?(r=rr(e,t),nr.test(r)?ot(e).position()[t]+"px":r):void 0})}),ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(r,i){ot.fn[i]=function(i,n){var o=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||n===!0?"margin":"border");return Ot(this,function(t,r,i){var n;return ot.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(n=t.documentElement,Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])):void 0===i?ot.css(t,r,s):ot.style(t,r,i,s)},t,o?i: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 oi=t.jQuery,si=t.$;return ot.noConflict=function(e){return t.$===ot&&(t.$=si),e&&t.jQuery===ot&&(t.jQuery=oi),ot},typeof r===yt&&(t.jQuery=t.$=ot),ot})},{}],12:[function(t,r){!function(t){function i(){try{return u in t&&t[u]}catch(e){return!1}}function n(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(s),c.appendChild(s),s.addBehavior("#default#userData"),s.load(u);var r=e.apply(a,t);return c.removeChild(s),r}}function o(e){return e.replace(/^d/,"___$&").replace(E,"___")}var s,a={},l=t.document,u="localStorage",p="script";if(a.disabled=!1,a.set=function(){},a.get=function(){},a.remove=function(){},a.clear=function(){},a.transact=function(e,t,r){var i=a.get(e);null==r&&(r=t,t=null),"undefined"==typeof i&&(i=t||{}),r(i),a.set(e,i)},a.getAll=function(){},a.forEach=function(){},a.serialize=function(e){return JSON.stringify(e)},a.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},i())s=t[u],a.set=function(e,t){return void 0===t?a.remove(e):(s.setItem(e,a.serialize(t)),t)},a.get=function(e){return a.deserialize(s.getItem(e))},a.remove=function(e){s.removeItem(e)},a.clear=function(){s.clear()},a.getAll=function(){var e={};return a.forEach(function(t,r){e[t]=r}),e},a.forEach=function(e){for(var t=0;t<s.length;t++){var r=s.key(t);e(r,a.get(r))}};else if(l.documentElement.addBehavior){var c,d;try{d=new ActiveXObject("htmlfile"),d.open(),d.write("<"+p+">document.w=window</"+p+'><iframe src="/favicon.ico"></iframe>'),d.close(),c=d.w.frames[0].document,s=c.createElement("div")}catch(h){s=l.createElement("div"),c=l.body}var E=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=n(function(e,t,r){return t=o(t),void 0===r?a.remove(t):(e.setAttribute(t,a.serialize(r)),e.save(u),r)}),a.get=n(function(e,t){return t=o(t),a.deserialize(e.getAttribute(t))}),a.remove=n(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),a.clear=n(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var r,i=0;r=t[i];i++)e.removeAttribute(r.name);e.save(u)}),a.getAll=function(){var e={};return a.forEach(function(t,r){e[t]=r}),e},a.forEach=n(function(e,t){for(var r,i=e.XMLDocument.documentElement.attributes,n=0;r=i[n];++n)t(r.name,a.deserialize(e.getAttribute(r.name)))})}try{var f="__storejs__";a.set(f,f),a.get(f)!=f&&(a.disabled=!0),a.remove(f)}catch(h){a.disabled=!0}a.enabled=!a.disabled,"undefined"!=typeof r&&r.exports&&this.module!==r?r.exports=a:"function"==typeof e&&e.amd?e(a):t.store=a}(Function("return this")())},{}],13:[function(e,t){t.exports={name:"yasgui-utils",version:"1.4.1",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"}}},{}],14:[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":13,"./storage.js":15,"./svg.js":16}],15:[function(e,t){{var r=e("store"),i={day:function(){return 864e5},month:function(){30*i.day()},year:function(){12*i.month()}};t.exports={set:function(e,t,n){"string"==typeof n&&(n=i[n]()),t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement)),r.set(e,{val:t,exp:n,time:(new Date).getTime()})},get:function(e){var t=r.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:12}],16:[function(e,t){t.exports={draw:function(e,r,i){if(e){var n=t.exports.getElement(r,i);n&&(e.append?e.append(n):e.appendChild(n))}},getElement:function(e,t){if(e&&0==e.indexOf("<svg")){t.width||(t.width="100%"),t.height||(t.height="100%");var r=new DOMParser,i=r.parseFromString(e,"text/xml"),n=i.documentElement,o=document.createElement("div");return o.style.display="inline-block",o.style.width=t.width,o.style.height=t.height,o.appendChild(n),o}return!1}}},{}],17:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.0.0",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.0","gulp-notify":"^1.2.5","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^0.2.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","browserify-shim":"^3.8.0","gulp-sourcemaps":"^1.2.4",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2"},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.2.0","twitter-bootstrap-3.0.0":"^3.0.0","yasgui-utils":"^1.4.1","gulp-minify-css":"^0.3.11"},"browserify-shim":{jquery:"global:jQuery",codemirror:"global:CodeMirror","../../lib/codemirror":"global:CodeMirror"}}},{}],18:[function(e,t){var r=e("jquery"),i=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e){var t={},a={},l={};e.on("cursorActivity",function(){c(!0)}),e.on("change",function(){var i=[];for(var n in t)t[n].is(":visible")&&i.push(t[n]);if(i.length>0){var o=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),s=0;o.is(":visible")&&(s=o.outerWidth()),i.forEach(function(e){e.css("right",s)})}});var u=function(t,r){l[t.name]=new o;for(var s=0;s<r.length;s++)l[t.name].insert(r[s]);var a=i.getPersistencyId(e,t.persistent);a&&n.storage.set(a,r,"month")},p=function(t,r){var o=a[t]=new r(e);if(o.name=t,o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&u(o,e)};if(o.get instanceof Array)s(o.get);else{var l=null,p=i.getPersistencyId(e,o.persistent);p&&(l=n.storage.get(p)),l&&l.length>0?s(l):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},c=function(t){if(!e.somethingSelected()){var r=function(r){if(t&&(!r.autoShow||!r.bulk&&r.async))return!1;var i={closeCharacters:/(?=a)b/,completeSingle:!1};!r.bulk&&r.async&&(i.async=!0);{var n=function(e,t){return d(r,t)};YASQE.showHint(e,n,i)}return!0};for(var i in a){var n=a[i];if(n.isValidCompletionPosition)if(n.isValidCompletionPosition()){if(!n.callbacks||!n.callbacks.validPosition||n.callbacks.validPosition(e,n)!==!1){var o=r(n);if(o)break}}else n.callbacks&&n.callbacks.invalidPosition&&n.callbacks.invalidPosition(e,n)}}},d=function(t,r){var i=function(e){var r=e.autocompletionString||e.string,i=[];if(l[t.name])i=l[t.name].autoComplete(r);else if("function"==typeof t.get&&0==t.async)i=t.get(r);else if("object"==typeof t.get)for(var n=r.length,o=0;o<t.get.length;o++){var s=t.get[o];s.slice(0,n)==r&&i.push(s)}return h(i,t,e)},n=e.getCompleteToken();if(t.preProcessToken&&(n=t.preProcessToken(n)),n){if(t.bulk||!t.async)return i(n);var o=function(e){r(h(e,t,n))};t.get(n,o)}},h=function(t,r,i){for(var n=[],o=0;o<t.length;o++){var a=t[o];r.postProcessToken&&(a=r.postProcessToken(i,a)),n.push({text:a,displayText:a,hint:s})}var l=e.getCursor(),u={completionToken:i.string,list:n,from:{line:l.line,ch:i.start},to:{line:l.line,ch:i.end}};if(r.callbacks)for(var p in r.callbacks)r.callbacks[p]&&e.on(u,p,r.callbacks[p]);return u};return{init:p,completers:a,notifications:{getEl:function(e){return r(t[e.name])},show:function(e,i){i.autoshow||(t[i.name]||(t[i.name]=r("<div class='completionNotification'></div>")),t[i.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(r(e.getWrapperElement())))},hide:function(e,r){t[r.name]&&t[r.name].hide()}},autoComplete:c,getTrie:function(e){return"string"==typeof e?l[e]:l[e.name]}}};var s=function(e,t,r){r.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(r.text,t.from,t.to)}},{"../../lib/trie.js":4,"../utils.js":30,jquery:11,"yasgui-utils":14}],19:[function(e,t){t.exports=function(t){return{isValidCompletionPosition:function(){var e=t.getCompleteToken();if(0==e.string.indexOf("?"))return!1;var r=t.getCursor(),i=t.getPreviousNonWsToken(r.line,e);return"a"==i.string?!0:"rdf:type"==i.string?!0:"rdfs:domain"==i.string?!0:"rdfs:range"==i.string?!0:!1 },get:function(r,i){return e("./utils").fetchFromLov(t,this,r,i)},preProcessToken:function(r){return e("./utils.js").preprocessResourceTokenForCompletion(t,r)},postProcessToken:function(r,i){return e("./utils.js").postprocessResourceTokenForCompletion(t,r,i)},async:!0,bulk:!1,autoShow:!1,persistent:"classes",callbacks:{validPosition:t.autocompleters.notifications.show,invalidPosition:t.autocompleters.notifications.hide}}}},{"./utils":22,"./utils.js":22}],20:[function(e,t){var r={"string-2":"prefixed",atom:"var"};t.exports=function(e){e.on("change",function(){i()});var t=function(t){var r=e.getPreviousNonWsToken(e.getCursor().line,t);return r&&r.string&&":"==r.string.slice(-1)&&(t={start:r.start,end:t.end,string:r.string+" "+t.string,state:t.state}),t},i=function(){if(e.autocompleters.getTrie("prefixes")){var t=e.getCursor(),i=e.getTokenAt(t);if("prefixed"==r[i.type]){var n=i.string.indexOf(":");if(-1!==n){var o=e.getNextNonWsToken(t.line).string.toUpperCase(),s=e.getTokenAt({line:t.line,ch:i.start});if("PREFIX"!=o&&("ws"==s.type||null==s.type)){var a=i.string.substring(0,n+1),l=e.getPrefixesFromQuery();if(null==l[a]){var u=e.autocompleters.getTrie("prefixes").autoComplete(a);u.length>0&&e.addPrefix(u[0])}}}}}};return{isValidCompletionPosition:function(){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;if("ws"!=r.type&&(r=e.getCompleteToken()),0==!r.string.indexOf("a")&&-1==$.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var i=e.getNextNonWsToken(t.line);return null==i||"PREFIX"!=i.string.toUpperCase()?!1:!0},get:function(e,t){$.get("http://prefix.cc/popular/all.file.json",function(e){var r=[];for(var i in e)if("bif"!=i){var n=i+": <"+e[i]+">";r.push(n)}r.sort(),t(r)})},preProcessToken:t,async:!0,bulk:!0,autoShow:!0,autoAddDeclaration:!0,persistent:"prefixes"}}},{}],21:[function(e,t){t.exports=function(t){return{isValidCompletionPosition:function(){var e=t.getCompleteToken();if(0==e.string.length)return!1;if(0==e.string.indexOf("?"))return!1;if($.inArray("a",e.state.possibleCurrent)>=0)return!0;var r=t.getCursor(),i=t.getPreviousNonWsToken(r.line,e);return"rdfs:subPropertyOf"==i.string?!0:!1},get:function(r,i){return e("./utils").fetchFromLov(t,this,r,i)},preProcessToken:function(r){return e("./utils.js").preprocessResourceTokenForCompletion(t,r)},postProcessToken:function(r,i){return e("./utils.js").postprocessResourceTokenForCompletion(t,r,i)},async:!0,bulk:!1,autoShow:!1,persistent:"properties",callbacks:{validPosition:t.autocompleters.notifications.show,invalidPosition:t.autocompleters.notifications.hide}}}},{"./utils":22,"./utils.js":22}],22:[function(e,t){var r=e("jquery"),i=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var r=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")&&(t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1),null!=r[t.tokenPrefix]&&(t.tokenPrefixUri=r[t.tokenPrefix])),t.autocompletionString=t.string.trim(),0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var i in r)if(r.hasOwnProperty(i)&&0==t.string.indexOf(i)){t.autocompletionString=r[i],t.autocompletionString+=t.string.substring(i.length);break}return 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)),t},o=function(e,t,r){return r=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+r.substring(t.tokenPrefixUri.length):"<"+r+">"},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length)return t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!"),!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?"+r.param(l)};c();var d=function(){l.page++,c()},h=function(){r.get(p,function(e){for(var i=0;i<e.results.length;i++)u.push(r.isArray(e.results[i].uri)&&e.results[i].uri.length>0?e.results[i].uri[0]:e.results[i].uri);u.length<e.total_results&&u.length<a?(d(),h()):(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(r("<span>Fetchting autocompletions &nbsp;</span>")).append(r(i.svg.getElement(e("../imgs.js").loader,{width:"18px",height:"18px"})).css("vertical-align","middle")),h()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":25,"./utils.js":22,jquery:11,"yasgui-utils":14}],23:[function(e,t){t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());return"ws"!=t.type&&(t=e.getCompleteToken(t),t&&0==t.string.indexOf("?"))?!0:!1},get:function(t){if(0==t.trim().length)return[];var r={};$(e.getWrapperElement()).find(".yasqe-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var i=$(this).next(),n=i.attr("class");if(n&&i.attr("class").indexOf("yasqe-atom")>=0&&(e+=i.text()),e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var i=[];for(var n in r)i.push(n);return i.sort(),i},async:!1,bulk:!1,autoShow:!0}}},{}],24:[function(e,t){var r=e("jquery"),i=e("./sparql.js");t.exports={use:function(e){e.defaults=r.extend(e.defaults,{mode:"sparql11",value:"SELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,gutters:["gutterErrorBar","CodeMirror-linenumbers"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":e.autoComplete,"Cmd-Space":e.autoComplete,"Ctrl-D":e.deleteLine,"Ctrl-K":e.deleteLine,"Cmd-D":e.deleteLine,"Cmd-K":e.deleteLine,"Ctrl-/":e.commentLines,"Cmd-/":e.commentLines,"Ctrl-Alt-Down":e.copyLineDown,"Ctrl-Alt-Up":e.copyLineUp,"Cmd-Alt-Down":e.copyLineDown,"Cmd-Alt-Up":e.copyLineUp,"Shift-Ctrl-F":e.doAutoFormat,"Shift-Cmd-F":e.doAutoFormat,"Ctrl-]":e.indentMore,"Cmd-]":e.indentMore,"Ctrl-[":e.indentLess,"Cmd-[":e.indentLess,"Ctrl-S":e.storeQuery,"Cmd-S":e.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:e.createShareLink,consumeShareLink:e.consumeShareLink,persistent:function(e){return"queryVal_"+r(e.getWrapperElement()).closest("[id]").attr("id")},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}},autocompleters:["prefixes","properties","classes","variables"]})}}},{"./sparql.js":27,jquery:11}],25:[function(e,t){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 id="Layer_1"></g><g id="Layer_2"> <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" ><g id="Layer_1" transform="translate(-2.995,-2.411)" /><g id="Layer_2" 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" id="path6" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g3"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 88.184,81.468 c 1.167,1.167 1.167,3.075 0,4.242 l -2.475,2.475 c -1.167,1.167 -3.076,1.167 -4.242,0 l -69.65,-69.65 c -1.167,-1.167 -1.167,-3.076 0,-4.242 l 2.476,-2.476 c 1.167,-1.167 3.076,-1.167 4.242,0 l 69.649,69.651 z" id="path5" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g7"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 18.532,88.184 c -1.167,1.166 -3.076,1.166 -4.242,0 l -2.475,-2.475 c -1.167,-1.166 -1.167,-3.076 0,-4.242 l 69.65,-69.651 c 1.167,-1.167 3.075,-1.167 4.242,0 l 2.476,2.476 c 1.166,1.167 1.166,3.076 0,4.242 l -69.651,69.65 z" id="path9" /></g></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 id="Captions"></g><g id="Your_Icon"> <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" id="Icons" 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 id="ShareThis" 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 id="g3" 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" id="path5" 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" id="path7" 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" id="path9" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>'}},{}],26:[function(e,t){var r=function(e,t){for(var r=null,i=0,o=e.lineCount(),s=0;o>s;s++){var a=e.getNextNonWsToken(s);null==a||"PREFIX"!=a.string&&"BASE"!=a.string||(r=a,i=s)}if(null==r)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=n(e,i);e.replaceRange("\n"+l+"PREFIX "+t,{line:i})}},i=function(e){for(var t={},r=e.lineCount(),i=0;r>i;i++){var n=e.getNextNonWsToken(i);if(null!=n&&"PREFIX"==n.string.toUpperCase()){var o=e.getNextNonWsToken(i,n.end+1);if(o){var s=e.getNextNonWsToken(i,o.end+1);if(null!=o&&o.string.length>0&&null!=s&&s.string.length>0){var a=s.string;0==a.indexOf("<")&&(a=a.substring(1)),">"==a.slice(-1)&&(a=a.substring(0,a.length-1)),t[o.string]=a}}}}return t},n=function(e,t,r){void 0==r&&(r=1);var i=e.getTokenAt({line:t,ch:r});return null==i||void 0==i||"ws"!=i.type?"":i.string+n(e,t,i.end+1)};t.exports={addPrefix:r,getPrefixesFromQuery:i}},{}],27:[function(e,t){var r=e("jquery");t.exports={use:function(e){e.executeQuery=function(t,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{},a=t.getQueryMode();if(t.options.sparql&&(s=r.extend({},t.options.sparql,s)),s.endpoint&&0!=s.endpoint.length){var l={url:"function"==typeof s.endpoint?s.endpoint(t):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(t):s.requestMethod,data:[{name:a,value:t.getValue()}],headers:{Accept:i(t,s)}},u=!1;if(s.callbacks)for(var p in s.callbacks)s.callbacks[p]&&(u=!0,l[p]=s.callbacks[p]);if(u||o){if(o&&(l.complete=o),s.namedGraphs&&s.namedGraphs.length>0)for(var c="query"==a?"named-graph-uri":"using-named-graph-uri ",d=0;d<s.namedGraphs.length;d++)l.data.push({name:c,value:s.namedGraphs[d]});if(s.defaultGraphs&&s.defaultGraphs.length>0)for(var c="query"==a?"default-graph-uri":"using-graph-uri ",d=0;d<s.defaultGraphs.length;d++)l.data.push({name:c,value:s.defaultGraphs[d]});s.headers&&!r.isEmptyObject(s.headers)&&r.extend(l.headers,s.headers),s.args&&s.args.length>0&&r.merge(l.data,s.args),e.updateQueryButton(t,"busy");var h=function(){e.updateQueryButton(t)};if(l.complete){var E=l.complete;l.complete=function(e,t){E(e,t),h()}}else l.complete=h;t.xhr=r.ajax(l)}}}}};var i=function(e,t){var r=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())r="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var i=e.getQueryType();r="DESCRIBE"==i||"CONSTRUCT"==i?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else r="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return r}},{jquery:11}],28:[function(e,t){var r=function(e,t,i){i||(i=e.getCursor()),t||(t=e.getTokenAt(i));var n=e.getTokenAt({line:i.line,ch:t.start});return null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type?(t.start=n.start,t.string=n.string+t.string,r(e,t,{line:i.line,ch:n.start})):null!=t.type&&"ws"==t.type?(t.start=t.start+1,t.string=t.string.substring(1),t):t},i=function(e,t,r){var n=e.getTokenAt({line:t,ch:r.start});return null!=n&&"ws"==n.type&&(n=i(e,t,n)),n},n=function(e,t,r){void 0==r&&(r=1);var i=e.getTokenAt({line:t,ch:r});return null==i||void 0==i||i.end<r?null:"ws"==i.type?n(e,t,i.end+1):i};t.exports={getPreviousNonWsToken:i,getCompleteToken:r,getNextNonWsToken:n}},{}],29:[function(e,t){{var r=e("jquery");e("./utils.js")}t.exports=function(e,t,i){var n,t=r(t);t.hover(function(){"function"==typeof i&&(i=i()),n=r("<div>").addClass("yasqe_tooltip").html(i).appendTo(t),o()},function(){r(".yasqe_tooltip").remove()});var o=function(){r(e.getWrapperElement()).offset().top>=n.offset().top&&(n.css("bottom","auto"),n.css("top","26px"))}}},{"./utils.js":30,jquery:11}],30:[function(e,t){var r=function(e,t){var r=!1;try{void 0!==e[t]&&(r=!0)}catch(i){}return r},i=function(e,t){var r=null;return t&&(r="string"==typeof t?t:t(e)),r},n=function(){function e(e){var t,r,i;return t=$(e).offset(),r=$(e).width(),i=$(e).height(),[[t.left,t.left+r],[t.top,t.top+i]]}function t(e,t){var r,i;return r=e[0]<t[0]?e:t,i=e[0]<t[0]?t:e,r[1]>i[0]||r[0]===i[0]}return function(r,i){var n=e(r),o=e(i);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:i,elementsOverlap:n}},{}]},{},[1])(1)}); //# sourceMappingURL=yasqe.bundled.min.js.map
bai/src/components/Workshops/index.js
blackinai/blackinai.github.io
import { ButtonBase, Container } from '@material-ui/core/'; import { withStyles } from '@material-ui/core/styles'; import PropTypes from 'prop-types'; import React from 'react'; import Typography from '../Typography'; const styles = (theme) => ({ root: { marginTop: theme.spacing(8), marginBottom: theme.spacing(4), }, images: { marginTop: theme.spacing(8), display: 'flex', flexWrap: 'wrap', }, imageWrapper: { position: 'relative', display: 'block', padding: 0, borderRadius: 0, height: '40vh', [theme.breakpoints.down('sm')]: { width: '100% !important', height: 100, }, '&:hover': { zIndex: 1, }, '&:hover $imageBackdrop': { opacity: 0.15, }, '&:hover $imageMarked': { opacity: 0, }, '&:hover $imageTitle': { border: '4px solid currentColor', }, }, imageButton: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: theme.palette.common.white, }, imageSrc: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundSize: 'cover', backgroundPosition: 'center 40%', }, imageBackdrop: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, background: theme.palette.common.black, opacity: 0.5, transition: theme.transitions.create('opacity'), }, imageTitle: { position: 'relative', padding: `${theme.spacing(2)}px ${theme.spacing(4)}px 14px`, }, imageMarked: { height: 3, width: 18, background: theme.palette.common.white, position: 'absolute', bottom: -2, left: 'calc(50% - 9px)', transition: theme.transitions.create('opacity'), }, }); function Workshops(props) { const { classes } = props; const workshops = [ { img: require('./../../assets/img/general/convention_centre_sydney.jpeg'), title: 'Black in AI 2021', width: '100%', url: '/#/workshop/bai2021', }, { img: require('./../../assets/img/general/vancouver_neurips_2020.jpg'), title: 'Black in AI 2020', width: '100%', url: 'https://blackinai2020.vercel.app/', }, { img: require('./../../assets/img/general/vancouver_convention_center.jpg'), title: 'Black in AI 2019', width: '30%', url: '/#/workshop/bai2019', }, { img: require('./../../assets/img/general/montreal_convention_centre.jpg'), title: 'Black in AI 2018', width: '40%', url: '/#/workshop/bai2018', }, { img: require('./../../assets/img/general/renaissance_long_beach_hotel.jpg'), title: 'Black in AI 2017', width: '30%', url: '/#/workshop/bai2017', }, ]; return ( <Container className={classes.root} component="section"> <Typography variant="h4" marked="center" align="center" component="h2"> Black in AI Workshops </Typography> <div className={classes.images}> {workshops.map((key) => ( <ButtonBase key={key.title} href={key.url} className={classes.imageWrapper} style={{ width: key.width,}}> <div className={classes.imageSrc} style={{ backgroundImage: `url(${key.img})`}} /> <div className={classes.imageBackdrop} /> <div className={classes.imageButton} > <Typography component="h3" variant="h6" color="inherit" className={classes.imageTitle} > {key.title} <div className={classes.imageMarked} /> </Typography> </div> </ButtonBase> ))} </div> </Container> ); } Workshops.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Workshops);
index.js
jaredpalmer/react-storybook-jsxstyle
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/svg-icons/action/open-in-browser.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOpenInBrowser = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/> </SvgIcon> ); ActionOpenInBrowser = pure(ActionOpenInBrowser); ActionOpenInBrowser.displayName = 'ActionOpenInBrowser'; ActionOpenInBrowser.muiName = 'SvgIcon'; export default ActionOpenInBrowser;
Libraries/Modal/Modal.js
aljs/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 Modal * @flow */ 'use strict'; const AppContainer = require('AppContainer'); const I18nManager = require('I18nManager'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const StyleSheet = require('StyleSheet'); const View = require('View'); const deprecatedPropType = require('deprecatedPropType'); const requireNativeComponent = require('requireNativeComponent'); const RCTModalHostView = requireNativeComponent('RCTModalHostView', null); /** * The Modal component is a simple way to present content above an enclosing view. * * _Note: If you need more control over how to present modals over the rest of your app, * then consider using a top-level Navigator._ * * ```javascript * import React, { Component } from 'react'; * import { Modal, Text, TouchableHighlight, View } from 'react-native'; * * class ModalExample extends Component { * * state = { * modalVisible: false, * } * * setModalVisible(visible) { * this.setState({modalVisible: visible}); * } * * render() { * return ( * <View style={{marginTop: 22}}> * <Modal * animationType={"slide"} * transparent={false} * visible={this.state.modalVisible} * onRequestClose={() => {alert("Modal has been closed.")}} * > * <View style={{marginTop: 22}}> * <View> * <Text>Hello World!</Text> * * <TouchableHighlight onPress={() => { * this.setModalVisible(!this.state.modalVisible) * }}> * <Text>Hide Modal</Text> * </TouchableHighlight> * * </View> * </View> * </Modal> * * <TouchableHighlight onPress={() => { * this.setModalVisible(true) * }}> * <Text>Show Modal</Text> * </TouchableHighlight> * * </View> * ); * } * } * ``` */ class Modal extends React.Component { static propTypes = { /** * The `animationType` prop controls how the modal animates. * * - `slide` slides in from the bottom * - `fade` fades into view * - `none` appears without an animation * * Default is set to `none`. */ animationType: PropTypes.oneOf(['none', 'slide', 'fade']), /** * The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background. */ transparent: PropTypes.bool, /** * The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window. * @platform android */ hardwareAccelerated: PropTypes.bool, /** * The `visible` prop determines whether your modal is visible. */ visible: PropTypes.bool, /** * The `onRequestClose` callback is called when the user taps the hardware back button. * @platform android */ onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func, /** * The `onShow` prop allows passing a function that will be called once the modal has been shown. */ onShow: PropTypes.func, animated: deprecatedPropType( PropTypes.bool, 'Use the `animationType` prop instead.' ), /** * The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations. * On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field. * @platform ios */ supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])), /** * The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed. * The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation. * @platform ios */ onOrientationChange: PropTypes.func, }; static defaultProps = { visible: true, hardwareAccelerated: false, }; static contextTypes = { rootTag: PropTypes.number, }; render(): ?React.Element<any> { if (this.props.visible === false) { return null; } const containerStyles = { backgroundColor: this.props.transparent ? 'transparent' : 'white', }; let animationType = this.props.animationType; if (!animationType) { // manually setting default prop here to keep support for the deprecated 'animated' prop animationType = 'none'; if (this.props.animated) { animationType = 'slide'; } } const innerChildren = __DEV__ ? ( <AppContainer rootTag={this.context.rootTag}> {this.props.children} </AppContainer>) : this.props.children; return ( <RCTModalHostView animationType={animationType} transparent={this.props.transparent} hardwareAccelerated={this.props.hardwareAccelerated} onRequestClose={this.props.onRequestClose} onShow={this.props.onShow} style={styles.modal} onStartShouldSetResponder={this._shouldSetResponder} supportedOrientations={this.props.supportedOrientations} onOrientationChange={this.props.onOrientationChange} > <View style={[styles.container, containerStyles]}> {innerChildren} </View> </RCTModalHostView> ); } // We don't want any responder events bubbling out of the modal. _shouldSetResponder(): boolean { return true; } } const side = I18nManager.isRTL ? 'right' : 'left'; const styles = StyleSheet.create({ modal: { position: 'absolute', }, container: { position: 'absolute', [side] : 0, top: 0, } }); module.exports = Modal;
vendor/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer/Template/js/jquery.min.js
jburgui/proyecto2.0
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
client/src/components/ListOfProjects/ListOfProjects.js
karthijey/calltocode.org
import React from 'react' import PropTypes from 'prop-types' import styles from './ListOfProjects.css' import projects from '../../data/projects.json' import emailApiClient from '../../api/email' import { connect } from 'react-redux' function ListOfProjects (props) { const liClassName = props.loggedIn ? styles.listOrgLoggedIn : styles.listOrg const projectListItems = projects.map((project, index) => { return ( <li key={index} className={liClassName} onClick={props.loggedIn ? mailToOrganization(project) : null}> Name:{project.name} Role:{project.role} </li> ) }) return ( <section className={styles.orgSection}> <h1 className={styles.title}>Apply Below</h1> <ul> {projectListItems} </ul> </section> ) } function mailToOrganization (project) { return () => { const {email, name, role} = project const projectInfo = {email, name, role} emailApiClient.send(projectInfo) } } function mapStateToProps (state) { return { loggedIn: state.login.loggedIn } } ListOfProjects.propTypes = { loggedIn: PropTypes.bool.isRequired } export default connect(mapStateToProps)(ListOfProjects)
admin-frontend/src/components/login.js
BarcampBangalore/hashbeam
import gql from 'graphql-tag'; import React from 'react'; import { Mutation } from 'react-apollo'; import { Redirect } from 'react-router-dom'; import { Button, Card, Form, Header, Message } from 'semantic-ui-react'; import styled from 'styled-components/macro'; const HorizontalCentered = styled.div` display: flex; flex-direction: column; align-items: center; `; const LoginCard = styled(Card)` &&& { padding: 16px; margin-top: 32px; } `; const LoginButton = styled(Button).attrs({ primary: true })` &&& { width: 100%; } `; const ErrorMessage = styled(Message).attrs({ negative: true })` margin-top: 32px; `; const LOGIN_USER_MUTATION = gql` mutation Login($username: String!, $password: String!) { authenticate(username: $username, password: $password) { token } } `; class Login extends React.Component { state = { username: '', password: '' }; render() { if (localStorage.getItem('token')) { return <Redirect to="/" />; } return ( <Mutation mutation={LOGIN_USER_MUTATION} onCompleted={({ authenticate: { token } }) => { localStorage.setItem('token', token); this.props.history.push('/'); }} > {(authenticate, { loading, error }) => ( <HorizontalCentered> <LoginCard> <Header as="h2">Hashbeam Admin</Header> <Form onSubmit={e => { e.preventDefault(); authenticate({ variables: { username: this.state.username, password: this.state.password } }); }} > <Form.Field> <input placeholder="Username" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} /> </Form.Field> <Form.Field> <input type="password" placeholder="Password" value={this.state.password} onChange={e => this.setState({ password: e.target.value })} /> </Form.Field> <LoginButton type="submit" loading={loading}> Login </LoginButton> </Form> </LoginCard> {error && ( <ErrorMessage> {error.graphQLErrors ? error.graphQLErrors[0].message : 'Network Error'} </ErrorMessage> )} </HorizontalCentered> )} </Mutation> ); } } export default Login;
ajax/libs/forerunnerdb/1.3.647/fdb-core+persist.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_('./core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Persist":28,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":34}],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":27,"./Shared":33}],4:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._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: 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', { dataSet: 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 hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback(); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(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.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', { dataSet: [doc] }, { index: index }); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { 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.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Index2d":10,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":26,"./Path":27,"./ReactorIO":31,"./Shared":33}],6:[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.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":33}],7:[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":14,"./Overload":26,"./Shared":33}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":14,"./Overload":26,"./Shared":33}],9:[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; },{}],10:[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":9,"./Path":27,"./Shared":33}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * 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":27,"./Shared":33}],12:[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":27,"./Shared":33}],13:[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":33}],14:[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":25,"./Shared":33}],15:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],16:[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 }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],17:[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; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return this.jStringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":26,"./Serialiser":32}],18:[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; },{}],19:[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":26}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],21:[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; },{}],22:[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; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":26}],24:[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; },{}],25:[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":27,"./Shared":33}],26:[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; },{}],27:[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":33}],28:[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":5,"./CollectionGroup":6,"./PersistCompress":29,"./PersistCrypto":30,"./Shared":33,"async":35,"localforage":71}],29:[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":33,"pako":72}],30:[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":33,"crypto-js":44}],31:[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":33}],32:[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) { if (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; },{}],33:[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.647', 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":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Tags":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":26}],34:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],35:[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":70}],36:[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":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],37:[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":38}],38:[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; })); },{}],39:[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":38}],40:[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":38}],41:[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":38,"./hmac":43,"./sha1":62}],42:[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":37,"./core":38}],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) { (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":38}],44:[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":36,"./cipher-core":37,"./core":38,"./enc-base64":39,"./enc-utf16":40,"./evpkdf":41,"./format-hex":42,"./hmac":43,"./lib-typedarrays":45,"./md5":46,"./mode-cfb":47,"./mode-ctr":49,"./mode-ctr-gladman":48,"./mode-ecb":50,"./mode-ofb":51,"./pad-ansix923":52,"./pad-iso10126":53,"./pad-iso97971":54,"./pad-nopadding":55,"./pad-zeropadding":56,"./pbkdf2":57,"./rabbit":59,"./rabbit-legacy":58,"./rc4":60,"./ripemd160":61,"./sha1":62,"./sha224":63,"./sha256":64,"./sha3":65,"./sha384":66,"./sha512":67,"./tripledes":68,"./x64-core":69}],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 () { // 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":38}],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 (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":38}],47:[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":37,"./core":38}],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) { /** @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":37,"./core":38}],49:[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":37,"./core":38}],50:[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":37,"./core":38}],51:[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":37,"./core":38}],52:[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":37,"./core":38}],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) { /** * 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":37,"./core":38}],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) { /** * 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":37,"./core":38}],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) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":37,"./core":38}],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) { /** * 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":37,"./core":38}],57:[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":38,"./hmac":43,"./sha1":62}],58:[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":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],59:[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":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],60:[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":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],61:[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":38}],62:[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":38}],63:[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":38,"./sha256":64}],64:[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":38}],65:[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":38,"./x64-core":69}],66:[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":38,"./sha512":67,"./x64-core":69}],67:[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":38,"./x64-core":69}],68:[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":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],69:[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":38}],70:[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; }; },{}],71:[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":70}],72:[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":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[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":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[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":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[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); },{}],76:[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":75}],77:[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; },{}],78:[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 }; },{}],79:[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; },{}],80:[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":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[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; },{}],82:[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; }; },{}],83:[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":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[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":75}],85:[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) */ }; },{}],86:[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":75}],87:[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]);
docs/app/Examples/modules/Dropdown/Content/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ContributionPrompt from 'docs/app/Components/ComponentDoc/ContributionPrompt' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const DropdownContentExamples = () => ( <ExampleSection title='Content'> <ComponentExample title='Header' description='A dropdown menu can contain a header.' examplePath='modules/Dropdown/Content/DropdownExampleHeader' /> <ComponentExample title='Divider' description='A dropdown menu can contain dividers to separate related content.' examplePath='modules/Dropdown/Content/DropdownExampleDivider' /> <ComponentExample title='Icon' description='A dropdown menu can contain an icon.' examplePath='modules/Dropdown/Content/DropdownExampleIcon' /> <ComponentExample title='Description' description='A dropdown menu can contain a description.' examplePath='modules/Dropdown/Content/DropdownExampleDescription' /> <ComponentExample title='Label' description='A dropdown menu can contain a label.' examplePath='modules/Dropdown/Content/DropdownExampleLabel' /> <ComponentExample title='Message' description='A dropdown menu can contain a message.' examplePath='modules/Dropdown/Content/DropdownExampleMessage' /> <ComponentExample title='Floated Content' description='A dropdown menu can contain floated content.' examplePath='modules/Dropdown/Content/DropdownExampleFloatedContent' /> <ComponentExample title='Input' description='A dropdown menu can contain an input.' examplePath='modules/Dropdown/Content/DropdownExampleInput' > <ContributionPrompt> The example below shows the desired markup but is not functional. Needs to be defined via shorthand, which is not yet possible. </ContributionPrompt> </ComponentExample> <ComponentExample title='Image' description='A dropdown menu can contain an image.' examplePath='modules/Dropdown/Content/DropdownExampleImage' /> </ExampleSection> ) export default DropdownContentExamples
src/components/FormPersonaCarro.js
aurigadl/EnvReactAsk
import React from 'react' import SelectInput from './SelectInput.js' import {remoteData} from '../utils/mrequest'; import {Card , Form , Input , Col, message, Row, Button, Icon} from 'antd'; const FormItem = Form.Item; var FormPersonaCarro = Form.create()(React.createClass({ getInitialState: function () { return { childSelV: undefined, childSelT: '', option:[ {mod:{key:1, label:'Conductor'}, person:[]}, {mod:{key:3, label:'Supervisor'}, person:[]} ], newOption: 0, initialValue: {}, }; }, getRemoteData : function(parreq){ remoteData(parreq, (data) => { var dataArray = []; for (var x in data.result) { let mod = data.result[x].mod; let per = data.result[x].person; var _mod = {key:mod.id, label:mod.name}; var _per = {key:per.id, label:per.name}; dataArray.push({mod: _mod, person: _per}); //if element exist then set values if(dataArray.length === 1){ this.props.form.setFieldsValue({ input_person_0:_per, input_modal_0:_mod }); } } if(dataArray.length > 0){ this.setState({ option: dataArray }); }else{ this.setState({ option: [{mod:[], person:[]}] }); } }, (err) => { message.warning('NO se encontraron datos para cargar') } ); }, handleSelect: function (childSelV, childSelT) { this.setState({ childSelV: childSelV, childSelT: childSelT }); if (childSelV != undefined) { var params = {'id': childSelV}; var parreq = { method: 'GET', url: 'apiFuec/idPersonCar', params: params }; this.getRemoteData(parreq); } else { this.setState({ option: [ {mod:{key:1, label:'Conductor'}, person:[]}, {mod:{key:3, label:'Supervisor'}, person:[]} ] }) } }, handleReset: function (e) { this.setState({ childSelV: undefined, childSelT: '', option: [ {mod:{key:1, label:'Conductor'}, person:[]}, {mod:{key:3, label:'Supervisor'}, person:[]} ] }); this.props.form.setFieldsValue({ input_uno:[], input_modal_0:{key:1, label:'Conductor'}, input_person_0:[], }); }, handleSubmitForm: function (e) { e.preventDefault(); const form = this.props.form; const childV = this.state.childSelV; form.validateFields((err, val) => { if (!err) { const data=[] let i=0; do{ let per_id = eval(`val.input_person_${i}`).key; let mod_id = eval(`val.input_modal_${i}`).key; data.push({'person': per_id, 'mod': mod_id}); i++; }while(eval(`val.input_person_${i}`) !== undefined) var params = { id: childV , person_car: data }; if (childV !== undefined) { var parreq = { method: 'PUT', url: 'apiFuec/updatePersonCar', params: { 'params': params } }; remoteData(parreq, (data) => { message.success('Se realizo el registro persona, carro y modalidad'); //Update Container this.props.newOptCont(); this.handleReset(); }, (err) => { message.error('NO se realizo el registro' + '\n Error :' + err.message.error) }); } } }) }, addNewRelPerCar: function () { var newOption = this.state.option; newOption.push({mod:[], person:[]}); this.setState({ option: newOption }); }, delRelPerCar: function (i) { var newn = this.state.option; delete newn[i]; var build = newn.filter((a)=>typeof a !== 'undefined') if(build.length == 0){ build.push({mod:[], person:[]}); } this.setState({ option: build }); }, componentWillReceiveProps: function(nextProps) { var next = nextProps.newOption; var prev = this.props.newOption; var next_i = nextProps.initVal; var prev_i = this.props.initVal; if (next != prev){ this.setState({ newOption: this.state.newOption + 1 }); } if (JSON.stringify(next_i) != JSON.stringify(prev_i)){ var params = {'id': next_i.key}; var parreq = { method: 'GET', url: 'apiFuec/idPersonCar', params: params }; this.setState({ initialValue: next_i, childSelV: next_i.key, childSelT: next_i.label }); this.getRemoteData(parreq); } }, render: function () { const { getFieldDecorator} = this.props.form; const {initialValue} = this.state const children = []; const st = this.state.option; var valSelec = ''; if(initialValue){ valSelec = initialValue; } for (let i = 0; i < st.length; i++){ const data = st[i]; children.push( <Row key={i}> <Col span="11"> <FormItem> {getFieldDecorator(`input_person_${i}`,{ initialValue:data.person, rules: [{ type:'object', required: true, message: 'Seleccione un tipo de persona!' }], })( <SelectInput newOption={this.state.newOption} url="apiFuec/allPerson" style={{marginRight: 4}} /> )} </FormItem> </Col> <Col span="1"> <p className="ant-form-split">-</p> </Col> <Col span="11"> <FormItem> {getFieldDecorator(`input_modal_${i}`, { initialValue:data.mod, rules: [{ type:'object', required: true, message: 'Seleccione un tipo de Función!' }], })( <SelectInput url="apiFuec/allModality" style={{marginRight: 8}} /> )} </FormItem> </Col> <Col span="1"> <Icon className="dynamic-delete-button" type="minus-circle-o" disabled={i === 0} onClick={()=>this.delRelPerCar(i)} /> </Col> </Row> ) }; return ( <Card id={this.props.id} title="Relación Carro y Personas" bordered={false}> <Form onSubmit={this.handleSubmitForm}> <Row gutter={15}> <Col span={8}> <FormItem label="Carro"> {getFieldDecorator('input_uno', { initialValue:valSelec, rules: [{ type:'object', required: true, message: 'Seleccione un vehiculo!' }], })( <SelectInput newOption={this.state.newOption} url="apiFuec/allCar" onUserSelect={this.handleSelect} /> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" size="large">Grabar</Button> <Button style={{ marginLeft: 8 }} htmlType="reset" size="large" onClick={this.handleReset}>Limpiar</Button> </FormItem> </Col> <Col span={16}> <div className='ant-form-item-label'> <label className='ant-form-item-required'>Relacion Persona - Función</label> </div> {children} <FormItem> <Button onClick={this.addNewRelPerCar} type="dashed"> <Icon type="plus" /> Agregar Relación </Button> </FormItem> </Col> </Row> </Form> </Card> ) } })); export default FormPersonaCarro;
fields/types/cloudinaryimages/CloudinaryImagesField.js
efernandesng/keystone
import _ from 'underscore'; import React from 'react'; import ReactDOM from 'react-dom'; import Field from '../Field'; import { Button, FormField, FormInput, FormNote } from 'elemental'; import Lightbox from '../../../admin/client/components/Lightbox'; import classnames from 'classnames'; const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml']; const iconClassDeleted = [ 'delete-pending', 'mega-octicon', 'octicon-x' ]; const iconClassQueued = [ 'img-uploading', 'mega-octicon', 'octicon-cloud-upload' ]; var Thumbnail = React.createClass({ displayName: 'CloudinaryImagesFieldThumbnail', propTypes: { deleted: React.PropTypes.bool, height: React.PropTypes.number, isQueued: React.PropTypes.bool, openLightbox: React.PropTypes.func, shouldRenderActionButton: React.PropTypes.bool, toggleDelete: React.PropTypes.func, url: React.PropTypes.string, width: React.PropTypes.number, }, renderActionButton () { if (!this.props.shouldRenderActionButton || this.props.isQueued) return null; return <Button type={this.props.deleted ? 'link-text' : 'link-cancel'} block onClick={this.props.toggleDelete}>{this.props.deleted ? 'Undo' : 'Remove'}</Button>; }, render () { let iconClassName; let { deleted, height, isQueued, url, width, openLightbox } = this.props; let previewClassName = classnames('image-preview', { 'action': (deleted || isQueued) }); let title = (width && height) ? (width + ' × ' + height) : ''; if (deleted) { iconClassName = classnames(iconClassDeleted); } else if (isQueued) { iconClassName = classnames(iconClassQueued); } return ( <div className="image-field image-sortable" title={title}> <div className={previewClassName}> <a href={url} onClick={openLightbox} className="img-thumbnail"> <img style={{ height: '90' }} className="img-load" src={url} /> <span className={iconClassName} /> </a> </div> {this.renderActionButton()} </div> ); } }); module.exports = Field.create({ getInitialState () { var thumbnails = []; var self = this; _.each(this.props.value, function (item) { self.pushThumbnail(item, thumbnails); }); return { thumbnails: thumbnails }; }, openLightbox (index) { event.preventDefault(); this.setState({ lightboxIsVisible: true, lightboxImageIndex: index, }); }, closeLightbox () { this.setState({ lightboxIsVisible: false, lightboxImageIndex: null, }); }, renderLightbox () { if (!this.props.value || !this.props.value.length) return; let images = this.props.value.map(image => image.url); return ( <Lightbox images={images} initialImage={this.state.lightboxImageIndex} isOpen={this.state.lightboxIsVisible} onCancel={this.closeLightbox} /> ); }, removeThumbnail (i) { var thumbs = this.state.thumbnails; var thumb = thumbs[i]; if (thumb.props.isQueued) { thumbs[i] = null; } else { thumb.props.deleted = !thumb.props.deleted; } this.setState({ thumbnails: thumbs }); }, pushThumbnail (args, thumbs) { thumbs = thumbs || this.state.thumbnails; var i = thumbs.length; args.toggleDelete = this.removeThumbnail.bind(this, i); args.shouldRenderActionButton = this.shouldRenderField(); args.openLightbox = this.openLightbox.bind(this, i); thumbs.push(<Thumbnail key={i} {...args} />); }, fileFieldNode () { return ReactDOM.findDOMNode(this.refs.fileField); }, getCount (key) { var count = 0; _.each(this.state.thumbnails, function (thumb) { if (thumb && thumb.props[key]) count++; }); return count; }, renderFileField () { if (!this.shouldRenderField()) return null; return <input ref="fileField" type="file" name={this.props.paths.upload} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />; }, clearFiles () { this.fileFieldNode().value = ''; this.setState({ thumbnails: this.state.thumbnails.filter(function (thumb) { return !thumb.props.isQueued; }) }); }, uploadFile (event) { var self = this; var files = event.target.files; _.each(files, function (f) { if (!_.contains(SUPPORTED_TYPES, f.type)) { alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG'); return; } if (window.FileReader) { var fileReader = new FileReader(); fileReader.onload = function (e) { self.pushThumbnail({ isQueued: true, url: e.target.result }); self.forceUpdate(); }; fileReader.readAsDataURL(f); } else { self.pushThumbnail({ isQueued: true, url: '#' }); self.forceUpdate(); } }); }, changeImage () { this.fileFieldNode().click(); }, hasFiles () { return this.refs.fileField && this.fileFieldNode().value; }, renderToolbar () { if (!this.shouldRenderField()) return null; var body = []; var push = function (queueType, alertType, count, action) { if (count <= 0) return; var imageText = count === 1 ? 'image' : 'images'; body.push(<div key={queueType + '-toolbar'} className={queueType + '-queued' + ' u-float-left'}> <FormInput noedit>{count} {imageText} {action}</FormInput> </div>); }; push('upload', 'success', this.getCount('isQueued'), 'selected - save to upload'); push('delete', 'danger', this.getCount('deleted'), 'removed - save to confirm'); var clearFilesButton; if (this.hasFiles()) { clearFilesButton = <Button type="link-cancel" onClick={this.clearFiles} className="ml-5">Clear selection</Button>; } return ( <div className="images-toolbar"> <div className="u-float-left"> <Button onClick={this.changeImage}>Upload Images</Button> {clearFilesButton} </div> {body} </div> ); }, renderPlaceholder () { return ( <div className="image-field image-field--upload" onClick={this.changeImage}> <div className="image-preview"> <span className="img-thumbnail"> <span className="img-dropzone" /> <div className="img-uploading mega-octicon octicon-file-media" /> </span> </div> <div className="image-details"> <span className="image-message">Click to upload</span> </div> </div> ); }, renderContainer () { return ( <div className="images-container"> {this.state.thumbnails} </div> ); }, renderFieldAction () { if (!this.shouldRenderField()) return null; var value = ''; var remove = []; _.each(this.state.thumbnails, function (thumb) { if (thumb && thumb.props.deleted) remove.push(thumb.props.public_id); }); if (remove.length) value = 'remove:' + remove.join(','); return <input ref="action" className="field-action" type="hidden" value={value} name={this.props.paths.action} />; }, renderUploadsField () { if (!this.shouldRenderField()) return null; return <input ref="uploads" className="field-uploads" type="hidden" name={this.props.paths.uploads} />; }, renderNote () { return this.props.note ? <FormNote note={this.props.note} /> : null; }, renderUI () { return ( <FormField label={this.props.label} className="field-type-cloudinaryimages"> {this.renderFieldAction()} {this.renderUploadsField()} {this.renderFileField()} {this.renderContainer()} {this.renderToolbar()} {this.renderNote()} {this.renderLightbox()} </FormField> ); } });
src/router.js
gusdewa/MultiStores
import React from 'react'; /* eslint-disable */ function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i++) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map(key => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
packages/material-ui-icons/src/SmartphoneTwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M7 5h10v14H7z" opacity=".3" /><path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z" /></React.Fragment> , 'SmartphoneTwoTone');
ui/src/transcoding/TranscodingShow.js
cloudsonic/sonic-server
import React from 'react' import { Show, SimpleShowLayout, TextField } from 'react-admin' import { Title } from '../common' import { TranscodingNote } from './TranscodingNote' const TranscodingTitle = ({ record }) => { return <Title subTitle={`Transcoding ${record ? record.name : ''}`} /> } const TranscodingShow = (props) => { return ( <> <TranscodingNote message={'message.transcodingDisabled'} /> <Show title={<TranscodingTitle />} {...props}> <SimpleShowLayout> <TextField source="name" /> <TextField source="targetFormat" /> <TextField source="defaultBitRate" /> <TextField source="command" /> </SimpleShowLayout> </Show> </> ) } export default TranscodingShow
ajax/libs/styled-components/2.2.2/styled-components.js
sashberd/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.styled = global.styled || {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate$2(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } var hyphenate_1 = hyphenate$2; var hyphenate = hyphenate_1; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } var hyphenateStyleName_1 = hyphenateStyleName; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; /*! * isobject <https://github.com/jonschlinkert/isobject> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ var index$1 = function isObject(val) { return val != null && (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && !Array.isArray(val); }; var isObject = index$1; function isObjectObject(o) { return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; } var index = function isPlainObject(o) { var ctor, prot; if (isObjectObject(o) === false) return false; // If has modified constructor ctor = o.constructor; if (typeof ctor !== 'function') return false; // If has modified prototype prot = ctor.prototype; if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; }; // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (index(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName_1(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; var flatten = function flatten(chunks, executionContext) { return chunks.reduce(function (ruleSet, chunk) { /* Remove falsey values */ if (chunk === undefined || chunk === null || chunk === false || chunk === '') return ruleSet; /* Flatten ruleSet */ if (Array.isArray(chunk)) return [].concat(ruleSet, flatten(chunk, executionContext)); /* Handle other components */ // $FlowFixMe not sure how to make this pass if (chunk.hasOwnProperty('styledComponentId')) return [].concat(ruleSet, ['.' + chunk.styledComponentId]); /* Either execute or defer the function */ if (typeof chunk === 'function') { return executionContext ? ruleSet.concat.apply(ruleSet, flatten([chunk(executionContext)], executionContext)) : ruleSet.concat(chunk); } /* Handle objects */ // $FlowFixMe have to add %checks somehow to isPlainObject return ruleSet.concat(index(chunk) ? objToCss(chunk) : chunk.toString()); }, []); }; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var stylis$1 = createCommonjsModule(function (module, exports) { /* * __ ___ * _____/ /___ __/ (_)____ * / ___/ __/ / / / / / ___/ * (__ ) /_/ /_/ / / (__ ) * /____/\__/\__, /_/_/____/ * /____/ * * light - weight css preprocessor @licence MIT */ (function (factory) { /* eslint-disable */ (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module['exports'] = factory(null) : typeof undefined === 'function' && undefined['amd'] ? undefined(factory(null)) : window['stylis'] = factory(null); })( /** @param {*=} options */function factory(options) { /* eslint-disable */ 'use strict'; /** * Notes * * The ['<method name>'] pattern is used to support closure compiler * the jsdoc signatures are also used to the same effect * * ---- * * int + int + int === n4 [faster] * * vs * * int === n1 && int === n2 && int === n3 * * ---- * * switch (int) { case ints...} [faster] * * vs * * if (int == 1 && int === 2 ...) * * ---- * * The (first*n1 + second*n2 + third*n3) format used in the property parser * is a simple way to hash the sequence of characters * taking into account the index they occur in * since any number of 3 character sequences could produce duplicates. * * On the other hand sequences that are directly tied to the index of the character * resolve a far more accurate measure, it's also faster * to evaluate one condition in a switch statement * than three in an if statement regardless of the added math. * * This allows the vendor prefixer to be both small and fast. */ var nullptn = /^\0+/g; /* matches leading null characters */ var formatptn = /[\0\r\f]/g; /* matches new line, null and formfeed characters */ var colonptn = /: */g; /* splits animation rules */ var cursorptn = /zoo|gra/; /* assert cursor varient */ var transformptn = /([,: ])(transform)/g; /* vendor prefix transform, older webkit */ var animationptn = /,+\s*(?![^(]*[)])/g; /* splits multiple shorthand notation animations */ var propertiesptn = / +\s*(?![^(]*[)])/g; /* animation properties */ var elementptn = / *[\0] */g; /* selector elements */ var selectorptn = /,\r+?/g; /* splits selectors */ var andptn = /([\t\r\n ])*\f?&/g; /* match & */ var escapeptn = /:global\(((?:[^\(\)\[\]]*|\[.*\]|\([^\(\)]*\))*)\)/g; /* matches :global(.*) */ var invalidptn = /\W+/g; /* removes invalid characters from keyframes */ var keyframeptn = /@(k\w+)\s*(\S*)\s*/; /* matches @keyframes $1 */ var plcholdrptn = /::(place)/g; /* match ::placeholder varient */ var readonlyptn = /:(read-only)/g; /* match :read-only varient */ var beforeptn = /\s+(?=[{\];=:>])/g; /* matches \s before ] ; = : */ var afterptn = /([[}=:>])\s+/g; /* matches \s after characters [ } = : */ var tailptn = /(\{[^{]+?);(?=\})/g; /* matches tail semi-colons ;} */ var whiteptn = /\s{2,}/g; /* matches repeating whitespace */ var pseudoptn = /([^\(])(:+) */g; /* pseudo element */ var writingptn = /[svh]\w+-[tblr]{2}/; /* match writing mode property values */ var gradientptn = /([\w-]+t\()/g; /* match *gradient property */ var supportsptn = /\(\s*([^]*?)\s*\)/g; /* match supports (groups) */ var propertyptn = /([^]*?);/g; /* match properties leading semicolon */ var selfptn = /-self|flex-/g; /* match flex- and -self in align-self: flex-*; */ /* vendors */ var webkit = '-webkit-'; var moz = '-moz-'; var ms = '-ms-'; /* character codes */ var SEMICOLON = 59; /* ; */ var CLOSEBRACES = 125; /* } */ var OPENBRACES = 123; /* { */ var OPENPARENTHESES = 40; /* ( */ var CLOSEPARENTHESES = 41; /* ) */ var OPENBRACKET = 91; /* [ */ var CLOSEBRACKET = 93; /* ] */ var NEWLINE = 10; /* \n */ var CARRIAGE = 13; /* \r */ var TAB = 9; /* \t */ var AT = 64; /* @ */ var SPACE = 32; /* */ var AND = 38; /* & */ var DASH = 45; /* - */ var UNDERSCORE = 95; /* _ */ var STAR = 42; /* * */ var COMMA = 44; /* , */ var COLON = 58; /* : */ var SINGLEQUOTE = 39; /* ' */ var DOUBLEQUOTE = 34; /* " */ var FOWARDSLASH = 47; /* / */ var GREATERTHAN = 62; /* > */ var PLUS = 43; /* + */ var TILDE = 126; /* ~ */ var NULL = 0; /* \0 */ var FORMFEED = 12; /* \f */ var VERTICALTAB = 11; /* \v */ /* special identifiers */ var KEYFRAME = 107; /* k */ var MEDIA = 109; /* m */ var SUPPORTS = 115; /* s */ var PLACEHOLDER = 112; /* p */ var READONLY = 111; /* o */ var IMPORT = 169; /* <at>i */ var CHARSET = 163; /* <at>c */ var DOCUMENT = 100; /* <at>d */ var column = 1; /* current column */ var line = 1; /* current line numebr */ var pattern = 0; /* :pattern */ var cascade = 1; /* #id h1 h2 vs h1#id h2#id */ var vendor = 1; /* vendor prefix */ var escape = 1; /* escape :global() pattern */ var compress = 0; /* compress output */ var semicolon = 0; /* no/semicolon option */ var preserve = 0; /* preserve empty selectors */ /* empty reference */ var array = []; /* plugins */ var plugins = []; var plugged = 0; /* plugin context */ var POSTS = -2; var PREPS = -1; var UNKWN = 0; var PROPS = 1; var BLCKS = 2; var ATRUL = 3; /* plugin newline context */ var unkwn = 0; /* keyframe animation */ var keyed = 1; var key = ''; /* selector namespace */ var nscopealt = ''; var nscope = ''; /** * Compile * * @param {Array<string>} parent * @param {Array<string>} current * @param {string} body * @param {number} id * @param {number} depth * @return {string} */ function compile(parent, current, body, id, depth) { var bracket = 0; /* brackets [] */ var comment = 0; /* comments /* // or /* */ var parentheses = 0; /* functions () */ var quote = 0; /* quotes '', "" */ var first = 0; /* first character code */ var second = 0; /* second character code */ var code = 0; /* current character code */ var tail = 0; /* previous character code */ var trail = 0; /* character before previous code */ var peak = 0; /* previous non-whitespace code */ var counter = 0; /* count sequence termination */ var context = 0; /* track current context */ var atrule = 0; /* track @at-rule context */ var pseudo = 0; /* track pseudo token index */ var caret = 0; /* current character index */ var format = 0; /* control character formating context */ var insert = 0; /* auto semicolon insertion */ var invert = 0; /* inverted selector pattern */ var length = 0; /* generic length address */ var eof = body.length; /* end of file(length) */ var eol = eof - 1; /* end of file(characters) */ var char = ''; /* current character */ var chars = ''; /* current buffer of characters */ var child = ''; /* next buffer of characters */ var out = ''; /* compiled body */ var children = ''; /* compiled children */ var flat = ''; /* compiled leafs */ var selector; /* generic selector address */ var result; /* generic address */ // ...build body while (caret < eof) { code = body.charCodeAt(caret); if (comment + quote + parentheses + bracket === 0) { // eof varient if (caret === eol) { if (format > 0) { chars = chars.replace(formatptn, ''); } if (chars.trim().length > 0) { switch (code) { case SPACE: case TAB: case SEMICOLON: case CARRIAGE: case NEWLINE: { break; } default: { chars += body.charAt(caret); } } code = SEMICOLON; } } // auto semicolon insertion if (insert === 1) { switch (code) { // false flags case OPENBRACES: case COMMA: { insert = 0; break; } // ignore case TAB: case CARRIAGE: case NEWLINE: case SPACE: { break; } // valid default: { caret--; code = SEMICOLON; } } } // token varient switch (code) { case OPENBRACES: { chars = chars.trim(); first = chars.charCodeAt(0); counter = 1; length = ++caret; while (caret < eof) { code = body.charCodeAt(caret); switch (code) { case OPENBRACES: { counter++; break; } case CLOSEBRACES: { counter--; break; } } if (counter === 0) { break; } caret++; } child = body.substring(length, caret); if (first === NULL) { first = (chars = chars.replace(nullptn, '').trim()).charCodeAt(0); } switch (first) { // @at-rule case AT: { if (format > 0) { chars = chars.replace(formatptn, ''); } second = chars.charCodeAt(1); switch (second) { case DOCUMENT: case MEDIA: case SUPPORTS: { selector = current; break; } default: { selector = array; } } child = compile(current, selector, child, second, depth + 1); length = child.length; // preserve empty @at-rule if (preserve > 0 && length === 0) { length = chars.length; } // execute plugins, @at-rule context if (plugged > 0) { selector = select(array, chars, invert); result = proxy(ATRUL, child, selector, current, line, column, length, second, depth); chars = selector.join(''); if (result !== void 0) { if ((length = (child = result.trim()).length) === 0) { second = 0; child = ''; } } } if (length > 0) { switch (second) { case SUPPORTS: { chars = chars.replace(supportsptn, supports); } case DOCUMENT: case MEDIA: { child = chars + '{' + child + '}'; break; } case KEYFRAME: { chars = chars.replace(keyframeptn, '$1 $2' + (keyed > 0 ? key : '')); child = chars + '{' + child + '}'; child = '@' + (vendor > 0 ? webkit + child + '@' + child : child); break; } default: { child = chars + child; } } } else { child = ''; } break; } // selector default: { child = compile(current, select(current, chars, invert), child, id, depth + 1); } } children += child; // reset context = 0; insert = 0; pseudo = 0; format = 0; invert = 0; atrule = 0; chars = ''; child = ''; code = body.charCodeAt(++caret); break; } case CLOSEBRACES: case SEMICOLON: { chars = (format > 0 ? chars.replace(formatptn, '') : chars).trim(); if ((length = chars.length) > 1) { // monkey-patch missing colon if (pseudo === 0) { first = chars.charCodeAt(0); // first character is a letter or dash, buffer has a space character if (first === DASH || first > 96 && first < 123) { length = (chars = chars.replace(' ', ':')).length; } } // execute plugins, property context if (plugged > 0) { if ((result = proxy(PROPS, chars, current, parent, line, column, out.length, id, depth)) !== void 0) { if ((length = (chars = result.trim()).length) === 0) { chars = '\0\0'; } } } first = chars.charCodeAt(0); second = chars.charCodeAt(1); switch (first + second) { case NULL: { break; } case IMPORT: case CHARSET: { flat += chars + body.charAt(caret); break; } default: { if (chars.charCodeAt(length - 1) === COLON) break; out += property(chars, first, second, chars.charCodeAt(2)); } } } // reset context = 0; insert = 0; pseudo = 0; format = 0; invert = 0; chars = ''; code = body.charCodeAt(++caret); break; } } } // parse characters switch (code) { case CARRIAGE: case NEWLINE: { // auto insert semicolon if (comment + quote + parentheses + bracket + semicolon === 0) { // valid non-whitespace characters that // may precede a newline switch (peak) { case CLOSEPARENTHESES: case SINGLEQUOTE: case DOUBLEQUOTE: case AT: case TILDE: case GREATERTHAN: case STAR: case PLUS: case FOWARDSLASH: case DASH: case COLON: case COMMA: case SEMICOLON: case OPENBRACES: case CLOSEBRACES: { break; } default: { // current buffer has a colon if (pseudo > 0) { insert = 1; } } } } // terminate line comment if (comment === FOWARDSLASH) { comment = 0; } // execute plugins, newline context if (plugged * unkwn > 0) { proxy(UNKWN, chars, current, parent, line, column, out.length, id, depth); } // next line, reset column position column = 1; line++; break; } case SEMICOLON: case CLOSEBRACES: { if (comment + quote + parentheses + bracket === 0) { column++; break; } } default: { // increment column position column++; // current character char = body.charAt(caret); // remove comments, escape functions, strings, attributes and prepare selectors switch (code) { case TAB: case SPACE: { if (quote + bracket === 0) { switch (tail) { case COMMA: case COLON: case TAB: case SPACE: { char = ''; break; } default: { if (code !== SPACE) { char = ' '; } } } } break; } // escape breaking control characters case NULL: { char = '\\0'; break; } case FORMFEED: { char = '\\f'; break; } case VERTICALTAB: { char = '\\v'; break; } // & case AND: { // inverted selector pattern i.e html & if (quote + comment + bracket === 0 && cascade > 0) { invert = 1; format = 1; char = '\f' + char; } break; } // ::p<l>aceholder, l // :read-on<l>y, l case 108: { if (quote + comment + bracket + pattern === 0 && pseudo > 0) { switch (caret - pseudo) { // ::placeholder case 2: { if (tail === PLACEHOLDER && body.charCodeAt(caret - 3) === COLON) { pattern = tail; } } // :read-only case 8: { if (trail === READONLY) { pattern = trail; } } } } break; } // :<pattern> case COLON: { if (quote + comment + bracket === 0) { pseudo = caret; } break; } // selectors case COMMA: { if (comment + parentheses + quote + bracket === 0) { format = 1; char += '\r'; } break; } // quotes case DOUBLEQUOTE: { if (comment === 0) { quote = quote === code ? 0 : quote === 0 ? code : quote; // " last character, add synthetic padding if (caret === eol) { eol++; eof++; } } break; } case SINGLEQUOTE: { if (comment === 0) { quote = quote === code ? 0 : quote === 0 ? code : quote; // ' last character, add synthetic padding if (caret === eol) { eol++; eof++; } } break; } // attributes case OPENBRACKET: { if (quote + comment + parentheses === 0) { bracket++; } break; } case CLOSEBRACKET: { if (quote + comment + parentheses === 0) { bracket--; } break; } // functions case CLOSEPARENTHESES: { if (quote + comment + bracket === 0) { // ) last character, add synthetic padding if (caret === eol) { eol++; eof++; } parentheses--; } break; } case OPENPARENTHESES: { if (quote + comment + bracket === 0) { if (context === 0) { switch (tail * 2 + trail * 3) { // :matches case 533: { break; } // :global, :not, :nth-child etc... default: { counter = 0; context = 1; } } } parentheses++; } break; } case AT: { if (comment + parentheses + quote + bracket + pseudo + atrule === 0) { atrule = 1; } break; } // block/line comments case STAR: case FOWARDSLASH: { if (quote + bracket + parentheses > 0) { break; } switch (comment) { // initialize line/block comment context case 0: { switch (code * 2 + body.charCodeAt(caret + 1) * 3) { // // case 235: { comment = FOWARDSLASH; break; } // /* case 220: { comment = STAR; break; } } break; } // end block comment context case STAR: { if (code === FOWARDSLASH && tail === STAR) { char = ''; comment = 0; } } } } } // ignore comment blocks if (comment === 0) { // aggressive isolation mode, divide each individual selector // including selectors in :not function but excluding selectors in :global function if (cascade + quote + bracket + atrule === 0 && id !== KEYFRAME && code !== SEMICOLON) { switch (code) { case COMMA: case TILDE: case GREATERTHAN: case PLUS: case CLOSEPARENTHESES: case OPENPARENTHESES: { if (context === 0) { // outside of an isolated context i.e nth-child(<...>) switch (tail) { case TAB: case SPACE: case NEWLINE: case CARRIAGE: { char = char + '\0'; break; } default: { char = '\0' + char + (code === COMMA ? '' : '\0'); } } format = 1; } else { // within an isolated context, sleep untill it's terminated switch (code) { case OPENPARENTHESES: { context = ++counter; break; } case CLOSEPARENTHESES: { if ((context = --counter) === 0) { format = 1; char += '\0'; } break; } } } break; } case SPACE: { switch (tail) { case NULL: case OPENBRACES: case CLOSEBRACES: case SEMICOLON: case COMMA: case FORMFEED: case TAB: case SPACE: case NEWLINE: case CARRIAGE: { break; } default: { // ignore in isolated contexts if (context === 0) { format = 1; char += '\0'; } } } } } } // concat buffer of characters chars += char; // previous non-whitespace character code if (code !== SPACE) { peak = code; } } } } // tail character codes trail = tail; tail = code; // visit every character caret++; } length = out.length; // preserve empty selector if (preserve > 0) { if (length === 0 && children.length === 0 && current[0].length === 0 === false) { if (id !== MEDIA || current.length === 1 && (cascade > 0 ? nscopealt : nscope) === current[0]) { length = current.join(',').length + 2; } } } if (length > 0) { // cascade isolation mode? selector = cascade === 0 && id !== KEYFRAME ? isolate(current) : current; // execute plugins, block context if (plugged > 0) { result = proxy(BLCKS, out, selector, parent, line, column, length, id, depth); if (result !== void 0 && (out = result).length === 0) { return flat + out + children; } } out = selector.join(',') + '{' + out + '}'; if (vendor * pattern > 0) { switch (pattern) { // ::read-only case READONLY: { out = out.replace(readonlyptn, ':' + moz + '$1') + out; break; } // ::placeholder case PLACEHOLDER: { out = out.replace(plcholdrptn, '::' + webkit + 'input-$1') + out.replace(plcholdrptn, '::' + moz + '$1') + out.replace(plcholdrptn, ':' + ms + 'input-$1') + out; break; } } pattern = 0; } } return flat + out + children; } /** * Select * * @param {Array<string>} parent * @param {string} current * @param {number} invert * @return {Array<string>} */ function select(parent, current, invert) { var selectors = current.trim().split(selectorptn); var out = selectors; var length = selectors.length; var l = parent.length; switch (l) { // 0-1 parent selectors case 0: case 1: { for (var i = 0, selector = l === 0 ? '' : parent[0] + ' '; i < length; ++i) { out[i] = scope(selector, out[i], invert, l).trim(); } break; } // >2 parent selectors, nested default: { for (var i = 0, j = 0, out = []; i < length; ++i) { for (var k = 0; k < l; ++k) { out[j++] = scope(parent[k] + ' ', selectors[i], invert, l).trim(); } } } } return out; } /** * Scope * * @param {string} parent * @param {string} current * @param {number} invert * @param {number} level * @return {string} */ function scope(parent, current, invert, level) { var selector = current; var code = selector.charCodeAt(0); // trim leading whitespace if (code < 33) { code = (selector = selector.trim()).charCodeAt(0); } switch (code) { // & case AND: { switch (cascade + level) { case 0: case 1: { if (parent.trim().length === 0) { break; } } default: { return selector.replace(andptn, '$1' + parent.trim()); } } break; } // : case COLON: { switch (selector.charCodeAt(1)) { // g in :global case 103: { if (escape > 0 && cascade > 0) { return selector.replace(escapeptn, '$1').replace(andptn, '$1' + nscope); } break; } default: { // :hover return parent.trim() + selector; } } } default: { // html & if (invert * cascade > 0 && selector.indexOf('\f') > 0) { return selector.replace(andptn, (parent.charCodeAt(0) === COLON ? '' : '$1') + parent.trim()); } } } return parent + selector; } /** * Property * * @param {string} input * @param {number} first * @param {number} second * @param {number} third * @return {string} */ function property(input, first, second, third) { var index = 0; var out = input + ';'; var hash = first * 2 + second * 3 + third * 4; var cache; // animation: a, n, i characters if (hash === 944) { out = animation(out); } else if (vendor > 0) { // vendor prefix switch (hash) { // text-decoration/text-size-adjust: t, e, x case 1015: { // text-size-adjust, - return out.charCodeAt(9) === DASH ? webkit + out + out : out; } // filter/fill f, i, l case 951: { // filter, t return out.charCodeAt(3) === 116 ? webkit + out + out : out; } // color/column, c, o, l case 963: { // column, n return out.charCodeAt(5) === 110 ? webkit + out + out : out; } // mask, m, a, s // clip-path, c, l, i case 969: case 942: { return webkit + out + out; } // appearance: a, p, p case 978: { return webkit + out + moz + out + out; } // hyphens: h, y, p // user-select: u, s, e case 1019: case 983: { return webkit + out + moz + out + ms + out + out; } // background/backface-visibility, b, a, c case 883: { // backface-visibility, - return out.charCodeAt(8) === DASH ? webkit + out + out : out; } // flex: f, l, e case 932: { return webkit + out + ms + out + out; } // order: o, r, d case 964: { return webkit + out + ms + 'flex' + '-' + out + out; } // justify-content, j, u, s case 1023: { cache = out.substring(out.indexOf(':', 15)).replace('flex-', '').replace('space-between', 'justify'); return webkit + 'box-pack' + cache + webkit + out + ms + 'flex-pack' + cache + out; } // cursor, c, u, r case 1005: { return cursorptn.test(out) ? out.replace(colonptn, ':' + webkit) + out.replace(colonptn, ':' + moz) + out : out; } // writing-mode, w, r, i case 1000: { cache = out.substring(13).trim(); index = cache.indexOf('-') + 1; switch (cache.charCodeAt(0) + cache.charCodeAt(index)) { // vertical-lr case 226: { cache = out.replace(writingptn, 'tb'); break; } // vertical-rl case 232: { cache = out.replace(writingptn, 'tb-rl'); break; } // horizontal-tb case 220: { cache = out.replace(writingptn, 'lr'); break; } default: { return out; } } return webkit + out + ms + cache + out; } // position: sticky case 1017: { if (out.indexOf('sticky', 9) === -1) { return out; } } // display(flex/inline-flex/inline-box): d, i, s case 975: { index = (out = input).length - 10; cache = (out.charCodeAt(index) === 33 ? out.substring(0, index) : out).substring(input.indexOf(':', 7) + 1).trim(); switch (hash = cache.charCodeAt(0) + (cache.charCodeAt(7) | 0)) { // inline- case 203: { // inline-box if (cache.charCodeAt(8) < 111) { break; } } // inline-box/sticky case 115: { out = out.replace(cache, webkit + cache) + ';' + out; break; } // inline-flex // flex case 207: case 102: { out = out.replace(cache, webkit + (hash > 102 ? 'inline-' : '') + 'box') + ';' + out.replace(cache, webkit + cache) + ';' + out.replace(cache, ms + cache + 'box') + ';' + out; } } return out + ';'; } // align-items, align-center, align-self: a, l, i, - case 938: { if (out.charCodeAt(5) === DASH) { switch (out.charCodeAt(6)) { // align-items, i case 105: { cache = out.replace('-items', ''); return webkit + out + webkit + 'box-' + cache + ms + 'flex-' + cache + out; } // align-self, s case 115: { return webkit + out + ms + 'flex-item-' + out.replace(selfptn, '') + out; } // align-content default: { return webkit + out + ms + 'flex-line-pack' + out.replace('align-content', '') + out; } } } break; } // width: min-content / width: max-content case 953: { if ((index = out.indexOf('-content', 9)) > 0) { // width: min-content / width: max-content if (out.charCodeAt(index - 3) === 109 && out.charCodeAt(index - 4) !== 45) { cache = out.substring(index - 3); return 'width:' + webkit + cache + 'width:' + moz + cache + 'width:' + cache; } } break; } // transform, transition: t, r, a case 962: { out = webkit + out + (out.charCodeAt(5) === 102 ? ms + out : '') + out; // transitions if (second + third === 211 && out.charCodeAt(13) === 105 && out.indexOf('transform', 10) > 0) { return out.substring(0, out.indexOf(';', 27) + 1).replace(transformptn, '$1' + webkit + '$2') + out; } break; } } } return out; } /** * @param {string} match * @param {string} group * @return {string} */ function supports(match, group) { var out = property(group, group.charCodeAt(0), group.charCodeAt(1), group.charCodeAt(2)); return out !== group + ';' ? out.replace(propertyptn, ' or ($1)').substring(4) : '(' + group + ')'; } /** * Animation * * @param {string} input * @return {string} */ function animation(input) { var length = input.length; var index = input.indexOf(':', 9) + 1; var declare = input.substring(0, index).trim(); var body = input.substring(index, length - 1).trim(); var out = ''; // shorthand if (input.charCodeAt(9) !== DASH) { // split in case of multiple animations var list = body.split(animationptn); for (var i = 0, index = 0, length = list.length; i < length; index = 0, ++i) { var value = list[i]; var items = value.split(propertiesptn); while (value = items[index]) { var peak = value.charCodeAt(0); if (keyed === 1 && ( // letters peak > AT && peak < 90 || peak > 96 && peak < 123 || peak === UNDERSCORE || // dash but not in sequence i.e -- peak === DASH && value.charCodeAt(1) !== DASH)) { // not a number/function switch (isNaN(parseFloat(value)) + (value.indexOf('(') !== -1)) { case 1: { switch (value) { // not a valid reserved keyword case 'infinite':case 'alternate':case 'backwards':case 'running': case 'normal':case 'forwards':case 'both':case 'none':case 'linear': case 'ease':case 'ease-in':case 'ease-out':case 'ease-in-out': case 'paused':case 'reverse':case 'alternate-reverse':case 'inherit': case 'initial':case 'unset':case 'step-start':case 'step-end': { break; } default: { value += key; } } } } } items[index++] = value; } out += (i === 0 ? '' : ',') + items.join(' '); } } else { // animation-name, n out += input.charCodeAt(10) === 110 ? body + (keyed === 1 ? key : '') : body; } out = declare + out + ';'; return vendor > 0 ? webkit + out + out : out; } /** * Isolate * * @param {Array<string>} current */ function isolate(current) { for (var i = 0, length = current.length, selector = Array(length), padding, element; i < length; ++i) { // split individual elements in a selector i.e h1 h2 === [h1, h2] var elements = current[i].split(elementptn); var out = ''; for (var j = 0, size = 0, tail = 0, code = 0, l = elements.length; j < l; ++j) { // empty element if ((size = (element = elements[j]).length) === 0 && l > 1) { continue; } tail = out.charCodeAt(out.length - 1); code = element.charCodeAt(0); padding = ''; if (j !== 0) { // determine if we need padding switch (tail) { case STAR: case TILDE: case GREATERTHAN: case PLUS: case SPACE: case OPENPARENTHESES: { break; } default: { padding = ' '; } } } switch (code) { case AND: { element = padding + nscopealt; } case TILDE: case GREATERTHAN: case PLUS: case SPACE: case CLOSEPARENTHESES: case OPENPARENTHESES: { break; } case OPENBRACKET: { element = padding + element + nscopealt; break; } case COLON: { switch (element.charCodeAt(1) * 2 + element.charCodeAt(2) * 3) { // :global case 530: { if (escape > 0) { element = padding + element.substring(8, size - 1); break; } } // :hover, :nth-child(), ... default: { if (j < 1 || elements[j - 1].length < 1) { element = padding + nscopealt + element; } } } break; } case COMMA: { padding = ''; } default: { if (size > 1 && element.indexOf(':') > 0) { element = padding + element.replace(pseudoptn, '$1' + nscopealt + '$2'); } else { element = padding + element + nscopealt; } } } out += element; } selector[i] = out.replace(formatptn, '').trim(); } return selector; } /** * Proxy * * @param {number} context * @param {string} content * @param {Array<string>} selectors * @param {Array<string>} parents * @param {number} line * @param {number} column * @param {number} length * @param {number} id * @param {number} depth * @return {(string|void|*)} */ function proxy(context, content, selectors, parents, line, column, length, id, depth) { for (var i = 0, out = content, next; i < plugged; ++i) { switch (next = plugins[i].call(stylis, context, out, selectors, parents, line, column, length, id, depth)) { case void 0: case false: case true: case null: { break; } default: { out = next; } } } switch (out) { case void 0: case false: case true: case null: case content: { break; } default: { return out; } } } /** * Minify * * @param {(string|*)} output * @return {string} */ function minify(output) { return output.replace(formatptn, '').replace(beforeptn, '').replace(afterptn, '$1').replace(tailptn, '$1').replace(whiteptn, ' '); } /** * Use * * @param {(Array<function(...?)>|function(...?)|number|void)?} plugin */ function use(plugin) { switch (plugin) { case void 0: case null: { plugged = plugins.length = 0; break; } default: { switch (plugin.constructor) { case Array: { for (var i = 0, length = plugin.length; i < length; ++i) { use(plugin[i]); } break; } case Function: { plugins[plugged++] = plugin; break; } case Boolean: { unkwn = !!plugin | 0; } } } } return use; } /** * Set * * @param {*} options */ function set$$1(options) { for (var name in options) { var value = options[name]; switch (name) { case 'keyframe': keyed = value | 0;break; case 'global': escape = value | 0;break; case 'cascade': cascade = value | 0;break; case 'compress': compress = value | 0;break; case 'prefix': vendor = value | 0;break; case 'semicolon': semicolon = value | 0;break; case 'preserve': preserve = value | 0;break; } } return set$$1; } /** * Stylis * * @param {string} selector * @param {string} input * @return {*} */ function stylis(selector, input) { if (this !== void 0 && this.constructor === stylis) { return factory(selector); } // setup var ns = selector; var code = ns.charCodeAt(0); // trim leading whitespace if (code < 33) { code = (ns = ns.trim()).charCodeAt(0); } // keyframe/animation namespace if (keyed > 0) { key = ns.replace(invalidptn, code === OPENBRACKET ? '' : '-'); } // reset, used to assert if a plugin is moneky-patching the return value code = 1; // cascade/isolate if (cascade === 1) { nscope = ns; } else { nscopealt = ns; } var selectors = [nscope]; var result; // execute plugins, pre-process context if (plugged > 0) { result = proxy(PREPS, input, selectors, selectors, line, column, 0, 0, 0); if (result !== void 0 && typeof result === 'string') { input = result; } } // build var output = compile(array, selectors, input, 0, 0); // execute plugins, post-process context if (plugged > 0) { result = proxy(POSTS, output, selectors, selectors, line, column, output.length, 0, 0); // bypass minification if (result !== void 0 && typeof (output = result) !== 'string') { code = 0; } } // reset key = ''; nscope = ''; nscopealt = ''; pattern = 0; line = 1; column = 1; return compress * code === 0 ? output : minify(output); } stylis['use'] = use; stylis['set'] = set$$1; if (options !== void 0) { set$$1(options); } return stylis; }); }); // var stylis = new stylis$1({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: true }); var stringifyRules = function stringifyRules(rules, selector, prefix) { var flatCSS = rules.join('').replace(/^\s*\/\/.*$/gm, ''); // replace JS comments var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS; return stylis(prefix || !selector ? '' : selector, cssStr); }; // var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); var charsLength = chars.length; /* Some high number, usually 9-digit base-10. Map it to base-😎 */ var generateAlphabeticName = function generateAlphabeticName(code) { var name = ''; var x = void 0; for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = chars[x % charsLength] + name; } return chars[x % charsLength] + name; }; // var interleave = (function (strings, interpolations) { return interpolations.reduce(function (array, interp, i) { return array.concat(interp, strings[i + 1]); }, [strings[0]]); }); // var css = (function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return flatten(interleave(strings, interpolations)); }); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s+(\S+)\s+\*\//mg; var extractCompsFromCSS = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // /* eslint-disable no-underscore-dangle */ /* * Browser Style Sheet with Rehydration * * <style data-styled-components="x y z" * data-styled-components-is-local="true"> * /· sc-component-id: a ·/ * .sc-a { ... } * .x { ... } * /· sc-component-id: b ·/ * .sc-b { ... } * .y { ... } * .z { ... } * </style> * * Note: replace · with * in the above snippet. * */ var COMPONENTS_PER_TAG = 40; var BrowserTag = function () { function BrowserTag(el, isLocal) { var existingSource = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; classCallCheck(this, BrowserTag); this.el = el; this.isLocal = isLocal; this.ready = false; var extractedComps = extractCompsFromCSS(existingSource); this.size = extractedComps.length; this.components = extractedComps.reduce(function (acc, obj) { acc[obj.componentId] = obj; // eslint-disable-line no-param-reassign return acc; }, {}); } BrowserTag.prototype.isFull = function isFull() { return this.size >= COMPONENTS_PER_TAG; }; BrowserTag.prototype.addComponent = function addComponent(componentId) { if (!this.ready) this.replaceElement(); if (this.components[componentId]) throw new Error('Trying to add Component \'' + componentId + '\' twice!'); var comp = { componentId: componentId, textNode: document.createTextNode('') }; this.el.appendChild(comp.textNode); this.size += 1; this.components[componentId] = comp; }; BrowserTag.prototype.inject = function inject(componentId, css, name) { if (!this.ready) this.replaceElement(); var comp = this.components[componentId]; if (!comp) throw new Error('Must add a new component before you can inject css into it'); if (comp.textNode.data === '') comp.textNode.appendData('\n/* sc-component-id: ' + componentId + ' */\n'); comp.textNode.appendData(css); if (name) { var existingNames = this.el.getAttribute(SC_ATTR); this.el.setAttribute(SC_ATTR, existingNames ? existingNames + ' ' + name : name); } var nonce = getNonce(); if (nonce) { this.el.setAttribute('nonce', nonce); } }; BrowserTag.prototype.toHTML = function toHTML() { return this.el.outerHTML; }; BrowserTag.prototype.toReactElement = function toReactElement() { throw new Error('BrowserTag doesn\'t implement toReactElement!'); }; BrowserTag.prototype.clone = function clone() { throw new Error('BrowserTag cannot be cloned!'); }; /* Because we care about source order, before we can inject anything we need to * create a text node for each component and replace the existing CSS. */ BrowserTag.prototype.replaceElement = function replaceElement() { var _this = this; this.ready = true; // We have nothing to inject. Use the current el. if (this.size === 0) return; // Build up our replacement style tag var newEl = this.el.cloneNode(); newEl.appendChild(document.createTextNode('\n')); Object.keys(this.components).forEach(function (key) { var comp = _this.components[key]; // eslint-disable-next-line no-param-reassign comp.textNode = document.createTextNode(comp.cssFromDOM); newEl.appendChild(comp.textNode); }); if (!this.el.parentNode) throw new Error("Trying to replace an element that wasn't mounted!"); // The ol' switcheroo this.el.parentNode.replaceChild(newEl, this.el); this.el = newEl; }; return BrowserTag; }(); /* Factory function to separate DOM operations from logical ones*/ var BrowserStyleSheet = { create: function create() { var tags = []; var names = {}; /* Construct existing state from DOM */ var nodes = document.querySelectorAll('[' + SC_ATTR + ']'); var nodesLength = nodes.length; for (var i = 0; i < nodesLength; i += 1) { var el = nodes[i]; tags.push(new BrowserTag(el, el.getAttribute(LOCAL_ATTR) === 'true', el.innerHTML)); var attr = el.getAttribute(SC_ATTR); if (attr) { attr.trim().split(/\s+/).forEach(function (name) { names[name] = true; }); } } /* Factory for making more tags */ var tagConstructor = function tagConstructor(isLocal) { var el = document.createElement('style'); el.type = 'text/css'; el.setAttribute(SC_ATTR, ''); el.setAttribute(LOCAL_ATTR, isLocal ? 'true' : 'false'); if (!document.head) throw new Error('Missing document <head>'); document.head.appendChild(el); return new BrowserTag(el, isLocal); }; return new StyleSheet(tagConstructor, tags, names); } }; // var SC_ATTR = 'data-styled-components'; var LOCAL_ATTR = 'data-styled-components-is-local'; var CONTEXT_KEY = '__styled-components-stylesheet__'; var instance = null; // eslint-disable-next-line no-use-before-define var clones = []; var StyleSheet = function () { function StyleSheet(tagConstructor) { var tags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, StyleSheet); this.hashes = {}; this.deferredInjections = {}; this.stylesCacheable = typeof document !== 'undefined'; this.tagConstructor = tagConstructor; this.tags = tags; this.names = names; this.constructComponentTagMap(); } // helper for `ComponentStyle` to know when it cache static styles. // staticly styled-component can not safely cache styles on the server // without all `ComponentStyle` instances saving a reference to the // the styleSheet instance they last rendered with, // or listening to creation / reset events. otherwise you might create // a component with one stylesheet and render it another api response // with another, losing styles on from your server-side render. StyleSheet.prototype.constructComponentTagMap = function constructComponentTagMap() { var _this = this; this.componentTags = {}; this.tags.forEach(function (tag) { Object.keys(tag.components).forEach(function (componentId) { _this.componentTags[componentId] = tag; }); }); }; /* Best level of caching—get the name from the hash straight away. */ StyleSheet.prototype.getName = function getName(hash) { return this.hashes[hash.toString()]; }; /* Second level of caching—if the name is already in the dom, don't * inject anything and record the hash for getName next time. */ StyleSheet.prototype.alreadyInjected = function alreadyInjected(hash, name) { if (!this.names[name]) return false; this.hashes[hash.toString()] = name; return true; }; /* Third type of caching—don't inject components' componentId twice. */ StyleSheet.prototype.hasInjectedComponent = function hasInjectedComponent(componentId) { return !!this.componentTags[componentId]; }; StyleSheet.prototype.deferredInject = function deferredInject(componentId, isLocal, css) { if (this === instance) { clones.forEach(function (clone) { clone.deferredInject(componentId, isLocal, css); }); } this.getOrCreateTag(componentId, isLocal); this.deferredInjections[componentId] = css; }; StyleSheet.prototype.inject = function inject(componentId, isLocal, css, hash, name) { if (this === instance) { clones.forEach(function (clone) { clone.inject(componentId, isLocal, css); }); } var tag = this.getOrCreateTag(componentId, isLocal); var deferredInjection = this.deferredInjections[componentId]; if (deferredInjection) { tag.inject(componentId, deferredInjection); delete this.deferredInjections[componentId]; } tag.inject(componentId, css, name); if (hash && name) { this.hashes[hash.toString()] = name; } }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { return this.tags.map(function (tag, i) { return tag.toReactElement('sc-' + i); }); }; StyleSheet.prototype.getOrCreateTag = function getOrCreateTag(componentId, isLocal) { var existingTag = this.componentTags[componentId]; if (existingTag) { return existingTag; } var lastTag = this.tags[this.tags.length - 1]; var componentTag = !lastTag || lastTag.isFull() || lastTag.isLocal !== isLocal ? this.createNewTag(isLocal) : lastTag; this.componentTags[componentId] = componentTag; componentTag.addComponent(componentId); return componentTag; }; StyleSheet.prototype.createNewTag = function createNewTag(isLocal) { var newTag = this.tagConstructor(isLocal); this.tags.push(newTag); return newTag; }; StyleSheet.reset = function reset(isServer) { instance = StyleSheet.create(isServer); }; /* We can make isServer totally implicit once Jest 20 drops and we * can change environment on a per-test basis. */ StyleSheet.create = function create() { var isServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : typeof document === 'undefined'; return (isServer ? ServerStyleSheet : BrowserStyleSheet).create(); }; StyleSheet.clone = function clone(oldSheet) { var newSheet = new StyleSheet(oldSheet.tagConstructor, oldSheet.tags.map(function (tag) { return tag.clone(); }), _extends({}, oldSheet.names)); newSheet.hashes = _extends({}, oldSheet.hashes); newSheet.deferredInjections = _extends({}, oldSheet.deferredInjections); clones.push(newSheet); return newSheet; }; createClass(StyleSheet, null, [{ key: 'instance', get: function get$$1() { return instance || (instance = StyleSheet.create()); } }]); return StyleSheet; }(); /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction$1 = function emptyFunction() {}; emptyFunction$1.thatReturns = makeEmptyFunction; emptyFunction$1.thatReturnsFalse = makeEmptyFunction(false); emptyFunction$1.thatReturnsTrue = makeEmptyFunction(true); emptyFunction$1.thatReturnsNull = makeEmptyFunction(null); emptyFunction$1.thatReturnsThis = function () { return this; }; emptyFunction$1.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction$1; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant$1(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant$1; var emptyFunction$2 = emptyFunction_1; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning$1 = emptyFunction$2; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning$1 = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } var warning_1 = warning$1; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; if (process.env.NODE_ENV !== 'production') { var invariant$2 = invariant_1; var warning$2 = warning_1; var ReactPropTypesSecret$2 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes$1(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant$2(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$2); } catch (ex) { error = ex; } warning$2(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error === 'undefined' ? 'undefined' : _typeof(error)); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning$2(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } var checkPropTypes_1 = checkPropTypes$1; var emptyFunction = emptyFunction_1; var invariant = invariant_1; var warning = warning_1; var ReactPropTypesSecret = ReactPropTypesSecret_1; var checkPropTypes = checkPropTypes_1; var factoryWithTypeCheckers = function factoryWithTypeCheckers(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant(false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3) { warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue)) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var emptyFunction$3 = emptyFunction_1; var invariant$3 = invariant_1; var factoryWithThrowingShims = function factoryWithThrowingShims() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant$3(false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); } shim.isRequired = shim; function getShim() { return shim; } var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction$3; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var index$3 = createCommonjsModule(function (module) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (process.env.NODE_ENV !== 'production') { var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element') || 0xeac7; var isValidElement = function isValidElement(object) { return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); var _StyleSheetManager$ch; // var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager() { classCallCheck(this, StyleSheetManager); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } StyleSheetManager.prototype.getChildContext = function getChildContext() { var _ref; return _ref = {}, _ref[CONTEXT_KEY] = this.props.sheet, _ref; }; StyleSheetManager.prototype.render = function render() { /* eslint-disable react/prop-types */ // Flow v0.43.1 will report an error accessing the `children` property, // but v0.47.0 will not. It is necessary to use a type cast instead of // a "fixme" comment to satisfy both Flow versions. return React__default.Children.only(this.props.children); }; return StyleSheetManager; }(React.Component); StyleSheetManager.childContextTypes = (_StyleSheetManager$ch = {}, _StyleSheetManager$ch[CONTEXT_KEY] = index$3.oneOfType([index$3.instanceOf(StyleSheet), index$3.instanceOf(ServerStyleSheet)]).isRequired, _StyleSheetManager$ch); StyleSheetManager.propTypes = { sheet: index$3.oneOfType([index$3.instanceOf(StyleSheet), index$3.instanceOf(ServerStyleSheet)]).isRequired }; // /* eslint-disable no-underscore-dangle */ var ServerTag = function () { function ServerTag(isLocal) { classCallCheck(this, ServerTag); this.isLocal = isLocal; this.components = {}; this.size = 0; this.names = []; } ServerTag.prototype.isFull = function isFull() { return false; }; ServerTag.prototype.addComponent = function addComponent(componentId) { if (this.components[componentId]) throw new Error('Trying to add Component \'' + componentId + '\' twice!'); this.components[componentId] = { componentId: componentId, css: '' }; this.size += 1; }; ServerTag.prototype.concatenateCSS = function concatenateCSS() { var _this = this; return Object.keys(this.components).reduce(function (styles, k) { return styles + _this.components[k].css; }, ''); }; ServerTag.prototype.inject = function inject(componentId, css, name) { var comp = this.components[componentId]; if (!comp) throw new Error('Must add a new component before you can inject css into it'); if (comp.css === '') comp.css = '/* sc-component-id: ' + componentId + ' */\n'; comp.css += css.replace(/\n*$/, '\n'); if (name) this.names.push(name); }; ServerTag.prototype.toHTML = function toHTML() { var attrs = ['type="text/css"', SC_ATTR + '="' + this.names.join(' ') + '"', LOCAL_ATTR + '="' + (this.isLocal ? 'true' : 'false') + '"']; var nonce = getNonce(); if (nonce) { attrs.push('nonce="' + nonce + '"'); } return '<style ' + attrs.join(' ') + '>' + this.concatenateCSS() + '</style>'; }; ServerTag.prototype.toReactElement = function toReactElement(key) { var _attrs; var attrs = (_attrs = {}, _attrs[SC_ATTR] = this.names.join(' '), _attrs[LOCAL_ATTR] = this.isLocal.toString(), _attrs); var nonce = getNonce(); if (nonce) { attrs.nonce = nonce; } return React__default.createElement('style', _extends({ key: key, type: 'text/css' }, attrs, { dangerouslySetInnerHTML: { __html: this.concatenateCSS() } })); }; ServerTag.prototype.clone = function clone() { var _this2 = this; var copy = new ServerTag(this.isLocal); copy.names = [].concat(this.names); copy.size = this.size; copy.components = Object.keys(this.components).reduce(function (acc, key) { acc[key] = _extends({}, _this2.components[key]); // eslint-disable-line no-param-reassign return acc; }, {}); return copy; }; return ServerTag; }(); var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); this.instance = StyleSheet.clone(StyleSheet.instance); } ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.closed) throw new Error("Can't collect styles once you've called getStyleTags!"); return React__default.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { if (!this.closed) { clones.splice(clones.indexOf(this.instance), 1); this.closed = true; } return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { if (!this.closed) { clones.splice(clones.indexOf(this.instance), 1); this.closed = true; } return this.instance.toReactElements(); }; ServerStyleSheet.create = function create() { return new StyleSheet(function (isLocal) { return new ServerTag(isLocal); }); }; return ServerStyleSheet; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // /* Trying to avoid the unknown-prop errors on styled components by filtering by React's attribute whitelist. */ /* Logic copied from ReactDOMUnknownPropertyHook */ var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true, className: true, /* List copied from https://facebook.github.io/react/docs/events.html */ onCopy: true, onCut: true, onPaste: true, onCompositionEnd: true, onCompositionStart: true, onCompositionUpdate: true, onKeyDown: true, onKeyPress: true, onKeyUp: true, onFocus: true, onBlur: true, onChange: true, onInput: true, onSubmit: true, onReset: true, onClick: true, onContextMenu: true, onDoubleClick: true, onDrag: true, onDragEnd: true, onDragEnter: true, onDragExit: true, onDragLeave: true, onDragOver: true, onDragStart: true, onDrop: true, onMouseDown: true, onMouseEnter: true, onMouseLeave: true, onMouseMove: true, onMouseOut: true, onMouseOver: true, onMouseUp: true, onSelect: true, onTouchCancel: true, onTouchEnd: true, onTouchMove: true, onTouchStart: true, onScroll: true, onWheel: true, onAbort: true, onCanPlay: true, onCanPlayThrough: true, onDurationChange: true, onEmptied: true, onEncrypted: true, onEnded: true, onError: true, onLoadedData: true, onLoadedMetadata: true, onLoadStart: true, onPause: true, onPlay: true, onPlaying: true, onProgress: true, onRateChange: true, onSeeked: true, onSeeking: true, onStalled: true, onSuspend: true, onTimeUpdate: true, onVolumeChange: true, onWaiting: true, onLoad: true, onAnimationStart: true, onAnimationEnd: true, onAnimationIteration: true, onTransitionEnd: true, onCopyCapture: true, onCutCapture: true, onPasteCapture: true, onCompositionEndCapture: true, onCompositionStartCapture: true, onCompositionUpdateCapture: true, onKeyDownCapture: true, onKeyPressCapture: true, onKeyUpCapture: true, onFocusCapture: true, onBlurCapture: true, onChangeCapture: true, onInputCapture: true, onSubmitCapture: true, onResetCapture: true, onClickCapture: true, onContextMenuCapture: true, onDoubleClickCapture: true, onDragCapture: true, onDragEndCapture: true, onDragEnterCapture: true, onDragExitCapture: true, onDragLeaveCapture: true, onDragOverCapture: true, onDragStartCapture: true, onDropCapture: true, onMouseDownCapture: true, onMouseEnterCapture: true, onMouseLeaveCapture: true, onMouseMoveCapture: true, onMouseOutCapture: true, onMouseOverCapture: true, onMouseUpCapture: true, onSelectCapture: true, onTouchCancelCapture: true, onTouchEndCapture: true, onTouchMoveCapture: true, onTouchStartCapture: true, onScrollCapture: true, onWheelCapture: true, onAbortCapture: true, onCanPlayCapture: true, onCanPlayThroughCapture: true, onDurationChangeCapture: true, onEmptiedCapture: true, onEncryptedCapture: true, onEndedCapture: true, onErrorCapture: true, onLoadedDataCapture: true, onLoadedMetadataCapture: true, onLoadStartCapture: true, onPauseCapture: true, onPlayCapture: true, onPlayingCapture: true, onProgressCapture: true, onRateChangeCapture: true, onSeekedCapture: true, onSeekingCapture: true, onStalledCapture: true, onSuspendCapture: true, onTimeUpdateCapture: true, onVolumeChangeCapture: true, onWaitingCapture: true, onLoadCapture: true, onAnimationStartCapture: true, onAnimationEndCapture: true, onAnimationIterationCapture: true, onTransitionEndCapture: true }; /* From HTMLDOMPropertyConfig */ var htmlProps = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: true, allowTransparency: true, alt: true, // specifies target context for links with `preload` type as: true, async: true, autoComplete: true, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: true, autoPlay: true, capture: true, cellPadding: true, cellSpacing: true, charSet: true, challenge: true, checked: true, cite: true, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: true, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, default: true, defer: true, dir: true, disabled: true, download: true, draggable: true, encType: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: true, formTarget: true, frameBorder: true, headers: true, height: true, hidden: true, high: true, href: true, hrefLang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, inputMode: true, integrity: true, is: true, keyParams: true, keyType: true, kind: true, label: true, lang: true, list: true, loop: true, low: true, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, minLength: true, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: true, muted: true, name: true, nonce: true, noValidate: true, open: true, optimum: true, pattern: true, placeholder: true, playsInline: true, poster: true, preload: true, profile: true, radioGroup: true, readOnly: true, referrerPolicy: true, rel: true, required: true, reversed: true, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scoped: true, scrolling: true, seamless: true, selected: true, shape: true, size: true, sizes: true, span: true, spellCheck: true, src: true, srcDoc: true, srcLang: true, srcSet: true, start: true, step: true, style: true, summary: true, tabIndex: true, target: true, title: true, // Setting .type throws on non-<input> tags type: true, useMap: true, value: true, width: true, wmode: true, wrap: true, /** * RDFa Properties */ about: true, datatype: true, inlist: true, prefix: true, // property is also supported for OpenGraph in meta tags. property: true, resource: true, typeof: true, vocab: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: true, autoCorrect: true, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: true, // color is for Safari mask-icon link color: true, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: true, itemScope: true, itemType: true, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: true, itemRef: true, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: true, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: true, // IE-only attribute that controls focus behavior unselectable: 0 }; var svgProps = { accentHeight: true, accumulate: true, additive: true, alignmentBaseline: true, allowReorder: true, alphabetic: true, amplitude: true, arabicForm: true, ascent: true, attributeName: true, attributeType: true, autoReverse: true, azimuth: true, baseFrequency: true, baseProfile: true, baselineShift: true, bbox: true, begin: true, bias: true, by: true, calcMode: true, capHeight: true, clip: true, clipPath: true, clipRule: true, clipPathUnits: true, colorInterpolation: true, colorInterpolationFilters: true, colorProfile: true, colorRendering: true, contentScriptType: true, contentStyleType: true, cursor: true, cx: true, cy: true, d: true, decelerate: true, descent: true, diffuseConstant: true, direction: true, display: true, divisor: true, dominantBaseline: true, dur: true, dx: true, dy: true, edgeMode: true, elevation: true, enableBackground: true, end: true, exponent: true, externalResourcesRequired: true, fill: true, fillOpacity: true, fillRule: true, filter: true, filterRes: true, filterUnits: true, floodColor: true, floodOpacity: true, focusable: true, fontFamily: true, fontSize: true, fontSizeAdjust: true, fontStretch: true, fontStyle: true, fontVariant: true, fontWeight: true, format: true, from: true, fx: true, fy: true, g1: true, g2: true, glyphName: true, glyphOrientationHorizontal: true, glyphOrientationVertical: true, glyphRef: true, gradientTransform: true, gradientUnits: true, hanging: true, horizAdvX: true, horizOriginX: true, ideographic: true, imageRendering: true, in: true, in2: true, intercept: true, k: true, k1: true, k2: true, k3: true, k4: true, kernelMatrix: true, kernelUnitLength: true, kerning: true, keyPoints: true, keySplines: true, keyTimes: true, lengthAdjust: true, letterSpacing: true, lightingColor: true, limitingConeAngle: true, local: true, markerEnd: true, markerMid: true, markerStart: true, markerHeight: true, markerUnits: true, markerWidth: true, mask: true, maskContentUnits: true, maskUnits: true, mathematical: true, mode: true, numOctaves: true, offset: true, opacity: true, operator: true, order: true, orient: true, orientation: true, origin: true, overflow: true, overlinePosition: true, overlineThickness: true, paintOrder: true, panose1: true, pathLength: true, patternContentUnits: true, patternTransform: true, patternUnits: true, pointerEvents: true, points: true, pointsAtX: true, pointsAtY: true, pointsAtZ: true, preserveAlpha: true, preserveAspectRatio: true, primitiveUnits: true, r: true, radius: true, refX: true, refY: true, renderingIntent: true, repeatCount: true, repeatDur: true, requiredExtensions: true, requiredFeatures: true, restart: true, result: true, rotate: true, rx: true, ry: true, scale: true, seed: true, shapeRendering: true, slope: true, spacing: true, specularConstant: true, specularExponent: true, speed: true, spreadMethod: true, startOffset: true, stdDeviation: true, stemh: true, stemv: true, stitchTiles: true, stopColor: true, stopOpacity: true, strikethroughPosition: true, strikethroughThickness: true, string: true, stroke: true, strokeDasharray: true, strokeDashoffset: true, strokeLinecap: true, strokeLinejoin: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, surfaceScale: true, systemLanguage: true, tableValues: true, targetX: true, targetY: true, textAnchor: true, textDecoration: true, textRendering: true, textLength: true, to: true, transform: true, u1: true, u2: true, underlinePosition: true, underlineThickness: true, unicode: true, unicodeBidi: true, unicodeRange: true, unitsPerEm: true, vAlphabetic: true, vHanging: true, vIdeographic: true, vMathematical: true, values: true, vectorEffect: true, version: true, vertAdvY: true, vertOriginX: true, vertOriginY: true, viewBox: true, viewTarget: true, visibility: true, widths: true, wordSpacing: true, writingMode: true, x: true, xHeight: true, x1: true, x2: true, xChannelSelector: true, xlinkActuate: true, xlinkArcrole: true, xlinkHref: true, xlinkRole: true, xlinkShow: true, xlinkTitle: true, xlinkType: true, xmlBase: true, xmlns: true, xmlnsXlink: true, xmlLang: true, xmlSpace: true, y: true, y1: true, y2: true, yChannelSelector: true, z: true, zoomAndPan: true }; /* From DOMProperty */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; var isCustomAttribute = RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$')); var hasOwnProperty = {}.hasOwnProperty; var validAttr = (function (name) { return hasOwnProperty.call(htmlProps, name) || hasOwnProperty.call(svgProps, name) || isCustomAttribute(name.toLowerCase()) || hasOwnProperty.call(reactProps, name); }); // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function isStyledComponent(target) /* : %checks */{ return typeof target === 'function' && typeof target.styledComponentId === 'string'; } // /* eslint-disable no-undef */ function getComponentName(target) { return target.displayName || target.name || 'Component'; } // var determineTheme = (function (props, fallbackTheme, defaultProps) { // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types */ var isDefaultTheme = defaultProps && props.theme === defaultProps.theme; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme; /* eslint-enable */ return theme; }); var index$4 = isFunction; var toString = Object.prototype.toString; function isFunction(fn) { var string = toString.call(fn); return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && ( // IE8 and below fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt); } // /** * Creates a broadcast that can be listened to, i.e. simple event emitter * * @see https://github.com/ReactTraining/react-broadcast */ var createBroadcast = function createBroadcast(initialState) { var listeners = {}; var id = 0; var state = initialState; function publish(nextState) { state = nextState; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in listeners) { var listener = listeners[key]; if (listener === undefined) { // eslint-disable-next-line no-continue continue; } listener(state); } } function subscribe(listener) { var currentId = id; listeners[currentId] = listener; id += 1; listener(state); return currentId; } function unsubscribe(unsubID) { listeners[unsubID] = undefined; } return { publish: publish, subscribe: subscribe, unsubscribe: unsubscribe }; }; // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); var _ThemeProvider$childC; var _ThemeProvider$contex; // /* globals React$Element */ // NOTE: DO NOT CHANGE, changing this is a semver major change! var CHANNEL = '__styled-components__'; var CHANNEL_NEXT = CHANNEL + 'next__'; var CONTEXT_CHANNEL_SHAPE = index$3.shape({ getTheme: index$3.func, subscribe: index$3.func, unsubscribe: index$3.func }); var warnChannelDeprecated = once(function () { // eslint-disable-next-line no-console console.error('Warning: Usage of `context.' + CHANNEL + '` as a function is deprecated. It will be replaced with the object on `.context.' + CHANNEL_NEXT + '` in a future version.'); }); /** * Provide a theme to an entire react component tree via context and event listeners (have to do * both context and event emitter as pure components block context updates) */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider() { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this)); _this.unsubscribeToOuterId = -1; _this.getTheme = _this.getTheme.bind(_this); return _this; } ThemeProvider.prototype.componentWillMount = function componentWillMount() { var _this2 = this; // If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme // with the outer theme var outerContext = this.context[CHANNEL_NEXT]; if (outerContext !== undefined) { this.unsubscribeToOuterId = outerContext.subscribe(function (theme) { _this2.outerTheme = theme; }); } this.broadcast = createBroadcast(this.getTheme()); }; ThemeProvider.prototype.getChildContext = function getChildContext() { var _this3 = this, _babelHelpers$extends; return _extends({}, this.context, (_babelHelpers$extends = {}, _babelHelpers$extends[CHANNEL_NEXT] = { getTheme: this.getTheme, subscribe: this.broadcast.subscribe, unsubscribe: this.broadcast.unsubscribe }, _babelHelpers$extends[CHANNEL] = function (subscriber) { warnChannelDeprecated(); // Patch the old `subscribe` provide via `CHANNEL` for older clients. var unsubscribeId = _this3.broadcast.subscribe(subscriber); return function () { return _this3.broadcast.unsubscribe(unsubscribeId); }; }, _babelHelpers$extends)); }; ThemeProvider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (this.props.theme !== nextProps.theme) this.broadcast.publish(this.getTheme(nextProps.theme)); }; ThemeProvider.prototype.componentWillUnmount = function componentWillUnmount() { if (this.unsubscribeToOuterId !== -1) { this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeToOuterId); } }; // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation ThemeProvider.prototype.getTheme = function getTheme(passedTheme) { var theme = passedTheme || this.props.theme; if (index$4(theme)) { var mergedTheme = theme(this.outerTheme); if (!index(mergedTheme)) { throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!'); } return mergedTheme; } if (!index(theme)) { throw new Error('[ThemeProvider] Please make your theme prop a plain object'); } return _extends({}, this.outerTheme, theme); }; ThemeProvider.prototype.render = function render() { if (!this.props.children) { return null; } return React__default.Children.only(this.props.children); }; return ThemeProvider; }(React.Component); ThemeProvider.childContextTypes = (_ThemeProvider$childC = {}, _ThemeProvider$childC[CHANNEL] = index$3.func, _ThemeProvider$childC[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$childC); ThemeProvider.contextTypes = (_ThemeProvider$contex = {}, _ThemeProvider$contex[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$contex); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`]/g; var multiDashRegex = /--+/g; // HACK for generating all static styles without needing to allocate // an empty execution context every single time... var STATIC_EXECUTION_CONTEXT = {}; var _StyledComponent = (function (ComponentStyle, constructWithOptions) { /* We depend on components having unique IDs */ var identifiers = {}; var generateId = function generateId(_displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : _displayName.replace(escapeRegex, '-') // Replace all possible CSS selectors .replace(multiDashRegex, '-'); // Replace multiple -- with single - var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var hash = ComponentStyle.generateName(displayName + nr); var componentId = displayName + '-' + hash; return parentComponentId !== undefined ? parentComponentId + '-' + componentId : componentId; }; var BaseStyledComponent = function (_Component) { inherits(BaseStyledComponent, _Component); function BaseStyledComponent() { var _temp, _this, _ret; classCallCheck(this, BaseStyledComponent); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.attrs = {}, _this.state = { theme: null, generatedClassName: '' }, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret); } BaseStyledComponent.prototype.unsubscribeFromContext = function unsubscribeFromContext() { if (this.unsubscribeId !== -1) { this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId); } }; BaseStyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props) { var attrs = this.constructor.attrs; var context = _extends({}, props, { theme: theme }); if (attrs === undefined) { return context; } this.attrs = Object.keys(attrs).reduce(function (acc, key) { var attr = attrs[key]; // eslint-disable-next-line no-param-reassign acc[key] = typeof attr === 'function' ? attr(context) : attr; return acc; }, {}); return _extends({}, context, this.attrs); }; BaseStyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var _constructor = this.constructor, attrs = _constructor.attrs, componentStyle = _constructor.componentStyle, warnTooManyClasses = _constructor.warnTooManyClasses; var styleSheet = this.context[CONTEXT_KEY] || StyleSheet.instance; // staticaly styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, styleSheet); } else { var executionContext = this.buildExecutionContext(theme, props); var className = componentStyle.generateAndInjectStyles(executionContext, styleSheet); if (warnTooManyClasses !== undefined) warnTooManyClasses(className); return className; } }; BaseStyledComponent.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var componentStyle = this.constructor.componentStyle; var styledContext = this.context[CHANNEL_NEXT]; // If this is a staticaly-styled component, we don't need to the theme // to generate or build styles. if (componentStyle.isStatic) { var generatedClassName = this.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, this.props); this.setState({ generatedClassName: generatedClassName }); // If there is a theme in the context, subscribe to the event emitter. This // is necessary due to pure components blocking context updates, this circumvents // that by updating when an event is emitted } else if (styledContext !== undefined) { var subscribe = styledContext.subscribe; this.unsubscribeId = subscribe(function (nextTheme) { // This will be called once immediately var theme = determineTheme(_this2.props, nextTheme, _this2.constructor.defaultProps); var generatedClassName = _this2.generateAndInjectStyles(theme, _this2.props); _this2.setState({ theme: theme, generatedClassName: generatedClassName }); }); } else { // eslint-disable-next-line react/prop-types var theme = this.props.theme || {}; var _generatedClassName = this.generateAndInjectStyles(theme, this.props); this.setState({ theme: theme, generatedClassName: _generatedClassName }); } }; BaseStyledComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var _this3 = this; // If this is a staticaly-styled component, we don't need to listen to // props changes to update styles var componentStyle = this.constructor.componentStyle; if (componentStyle.isStatic) { return; } this.setState(function (oldState) { var theme = determineTheme(nextProps, oldState.theme, _this3.constructor.defaultProps); var generatedClassName = _this3.generateAndInjectStyles(theme, nextProps); return { theme: theme, generatedClassName: generatedClassName }; }); }; BaseStyledComponent.prototype.componentWillUnmount = function componentWillUnmount() { this.unsubscribeFromContext(); }; BaseStyledComponent.prototype.render = function render() { var _this4 = this; // eslint-disable-next-line react/prop-types var innerRef = this.props.innerRef; var generatedClassName = this.state.generatedClassName; var _constructor2 = this.constructor, styledComponentId = _constructor2.styledComponentId, target = _constructor2.target; var isTargetTag = isTag(target); var className = [ // eslint-disable-next-line react/prop-types this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); var baseProps = _extends({}, this.attrs, { className: className }); if (isStyledComponent(target)) { baseProps.innerRef = innerRef; } else { baseProps.ref = innerRef; } var propsForElement = Object.keys(this.props).reduce(function (acc, propName) { // Don't pass through non HTML tags through to HTML elements // always omit innerRef if (propName !== 'innerRef' && propName !== 'className' && (!isTargetTag || validAttr(propName))) { // eslint-disable-next-line no-param-reassign acc[propName] = _this4.props[propName]; } return acc; }, baseProps); return React.createElement(target, propsForElement); }; return BaseStyledComponent; }(React.Component); var createStyledComponent = function createStyledComponent(target, options, rules) { var _StyledComponent$cont; var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')' : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? BaseStyledComponent : _options$ParentCompon, extendingRules = options.rules, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? options.displayName + '-' + options.componentId : componentId; var warnTooManyClasses = void 0; if (process.env.NODE_ENV !== 'production') { warnTooManyClasses = createWarnTooManyClasses(displayName); } var componentStyle = new ComponentStyle(extendingRules === undefined ? rules : extendingRules.concat(rules), attrs, styledComponentId); var StyledComponent = function (_ParentComponent) { inherits(StyledComponent, _ParentComponent); function StyledComponent() { classCallCheck(this, StyledComponent); return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments)); } StyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : getComponentName(tag)); var newOptions = _extends({}, optionsToCopy, { componentId: newComponentId, ParentComponent: StyledComponent }); return createStyledComponent(tag, newOptions, rules); }; createClass(StyledComponent, null, [{ key: 'extend', get: function get$$1() { var rulesFromOptions = options.rules, parentComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['rules', 'componentId']); var newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules); var newOptions = _extends({}, optionsToCopy, { rules: newRules, parentComponentId: parentComponentId, ParentComponent: StyledComponent }); return constructWithOptions(createStyledComponent, target, newOptions); } }]); return StyledComponent; }(ParentComponent); StyledComponent.contextTypes = (_StyledComponent$cont = {}, _StyledComponent$cont[CHANNEL] = index$3.func, _StyledComponent$cont[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _StyledComponent$cont[CONTEXT_KEY] = index$3.oneOfType([index$3.instanceOf(StyleSheet), index$3.instanceOf(ServerStyleSheet)]), _StyledComponent$cont); StyledComponent.displayName = displayName; StyledComponent.styledComponentId = styledComponentId; StyledComponent.attrs = attrs; StyledComponent.componentStyle = componentStyle; StyledComponent.warnTooManyClasses = warnTooManyClasses; StyledComponent.target = target; return StyledComponent; }; return createStyledComponent; }); // murmurhash2 via https://gist.github.com/raycmorgan/588423 function doHash(str, seed) { var m = 0x5bd1e995; var r = 24; var h = seed ^ str.length; var length = str.length; var currentIndex = 0; while (length >= 4) { var k = UInt32(str, currentIndex); k = Umul32(k, m); k ^= k >>> r; k = Umul32(k, m); h = Umul32(h, m); h ^= k; currentIndex += 4; length -= 4; } switch (length) { case 3: h ^= UInt16(str, currentIndex); h ^= str.charCodeAt(currentIndex + 2) << 16; h = Umul32(h, m); break; case 2: h ^= UInt16(str, currentIndex); h = Umul32(h, m); break; case 1: h ^= str.charCodeAt(currentIndex); h = Umul32(h, m); break; } h ^= h >>> 13; h = Umul32(h, m); h ^= h >>> 15; return h >>> 0; } function UInt32(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) + (str.charCodeAt(pos++) << 16) + (str.charCodeAt(pos) << 24); } function UInt16(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8); } function Umul32(n, m) { n = n | 0; m = m | 0; var nlo = n & 0xffff; var nhi = n >>> 16; var res = nlo * m + ((nhi * m & 0xffff) << 16) | 0; return res; } // var isStaticRules = function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (typeof rule === 'function' && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled copmonent return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (typeof value === 'function') { return false; } } } return true; }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var _ComponentStyle = (function (nameGenerator, flatten, stringifyRules) { var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.instance.hasInjectedComponent(this.componentId)) { var placeholder = process.env.NODE_ENV !== 'production' ? '.' + componentId + ' {}' : ''; StyleSheet.instance.deferredInject(componentId, true, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, lastClassName = this.lastClassName; if (isStatic && lastClassName !== undefined) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext); var hash = doHash(this.componentId + flatCSS.join('')); var existingName = styleSheet.getName(hash); if (existingName !== undefined) { if (styleSheet.stylesCacheable) { this.lastClassName = existingName; } return existingName; } var name = nameGenerator(hash); if (styleSheet.stylesCacheable) { this.lastClassName = existingName; } if (styleSheet.alreadyInjected(hash, name)) { return name; } var css = '\n' + stringifyRules(flatCSS, '.' + name); // NOTE: this can only be set when we inject the class-name. // For some reason, presumably due to how css is stringifyRules behaves in // differently between client and server, styles break. styleSheet.inject(this.componentId, true, css, hash, name); return name; }; ComponentStyle.generateName = function generateName(str) { return nameGenerator(doHash(str)); }; return ComponentStyle; }(); return ComponentStyle; }); // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var _styled = (function (styledComponent, constructWithOptions) { var styled = function styled(tag) { return constructWithOptions(styledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); return styled; }); // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; var _keyframes = (function (nameGenerator, stringifyRules, css) { return function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var hash = doHash(replaceWhitespace(JSON.stringify(rules))); var existingName = StyleSheet.instance.getName(hash); if (existingName) return existingName; var name = nameGenerator(hash); if (StyleSheet.instance.alreadyInjected(hash, name)) return name; var generatedCSS = stringifyRules(rules, name, '@keyframes'); StyleSheet.instance.inject('sc-keyframes-' + name, true, generatedCSS, hash, name); return name; }; }); // var _injectGlobal = (function (stringifyRules, css) { var injectGlobal = function injectGlobal(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var hash = doHash(JSON.stringify(rules)); var componentId = 'sc-global-' + hash; if (StyleSheet.instance.hasInjectedComponent(componentId)) return; StyleSheet.instance.inject(componentId, false, stringifyRules(rules)); }; return injectGlobal; }); // var _constructWithOptions = (function (css) { var constructWithOptions = function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof tag !== 'string' && typeof tag !== 'function') { // $FlowInvalidInputTest throw new Error('Cannot create styled-component for component: ' + tag); } /* This is callable directly as a template function */ var templateFunction = function templateFunction(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return componentConstructor(tag, options, css.apply(undefined, [strings].concat(interpolations))); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || {}, attrs) })); }; return templateFunction; }; return constructWithOptions; }); /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; var index$5 = function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) {} } } } return targetComponent; }; // /* globals ReactClass */ var wrapWithTheme = function wrapWithTheme(Component$$1) { var _WithTheme$contextTyp; var componentName = Component$$1.displayName || Component$$1.name || 'Component'; var isStyledComponent$$1 = isStyledComponent(Component$$1); var WithTheme = function (_React$Component) { inherits(WithTheme, _React$Component); function WithTheme() { var _temp, _this, _ret; classCallCheck(this, WithTheme); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {}, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret); } // NOTE: This is so that isStyledComponent passes for the innerRef unwrapping WithTheme.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var defaultProps = this.constructor.defaultProps; var styledContext = this.context[CHANNEL_NEXT]; var themeProp = determineTheme(this.props, undefined, defaultProps); if (styledContext === undefined && themeProp === undefined && process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps'); } else if (styledContext === undefined && themeProp !== undefined) { this.setState({ theme: themeProp }); } else { var subscribe = styledContext.subscribe; this.unsubscribeId = subscribe(function (nextTheme) { var theme = determineTheme(_this2.props, nextTheme, defaultProps); _this2.setState({ theme: theme }); }); } }; WithTheme.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var defaultProps = this.constructor.defaultProps; this.setState(function (oldState) { var theme = determineTheme(nextProps, oldState.theme, defaultProps); return { theme: theme }; }); }; WithTheme.prototype.componentWillUnmount = function componentWillUnmount() { if (this.unsubscribeId !== -1) { this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId); } }; WithTheme.prototype.render = function render() { // eslint-disable-next-line react/prop-types var innerRef = this.props.innerRef; var theme = this.state.theme; return React__default.createElement(Component$$1, _extends({ theme: theme }, this.props, { innerRef: isStyledComponent$$1 ? innerRef : undefined, ref: isStyledComponent$$1 ? undefined : innerRef })); }; return WithTheme; }(React__default.Component); WithTheme.displayName = 'WithTheme(' + componentName + ')'; WithTheme.styledComponentId = 'withTheme'; WithTheme.contextTypes = (_WithTheme$contextTyp = {}, _WithTheme$contextTyp[CHANNEL] = index$3.func, _WithTheme$contextTyp[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _WithTheme$contextTyp); return index$5(WithTheme, Component$$1); }; // /* Import singletons */ /* Import singleton constructors */ /* Import components */ /* Import Higher Order Components */ /* Instantiate singletons */ var ComponentStyle = _ComponentStyle(generateAlphabeticName, flatten, stringifyRules); var constructWithOptions = _constructWithOptions(css); var StyledComponent = _StyledComponent(ComponentStyle, constructWithOptions); /* Instantiate exported singletons */ var keyframes = _keyframes(generateAlphabeticName, stringifyRules, css); var injectGlobal = _injectGlobal(stringifyRules, css); var styled = _styled(StyledComponent, constructWithOptions); exports['default'] = styled; exports.css = css; exports.keyframes = keyframes; exports.injectGlobal = injectGlobal; exports.ThemeProvider = ThemeProvider; exports.withTheme = wrapWithTheme; exports.ServerStyleSheet = ServerStyleSheet; exports.StyleSheetManager = StyleSheetManager; Object.defineProperty(exports, '__esModule', { value: true }); })));
app/javascript/mastodon/components/poll.js
sylph-sin-tyaku/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import { vote, fetchPoll } from 'mastodon/actions/polls'; import Motion from 'mastodon/features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import escapeTextContentForBrowser from 'escape-html'; import emojify from 'mastodon/features/emoji/emoji'; import RelativeTimestamp from './relative_timestamp'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ closed: { id: 'poll.closed', defaultMessage: 'Closed' }, voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer', description: 'Tooltip of the "voted" checkmark in polls' }, }); const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => { obj[`:${emoji.get('shortcode')}:`] = emoji.toJS(); return obj; }, {}); export default @injectIntl class Poll extends ImmutablePureComponent { static propTypes = { poll: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, dispatch: PropTypes.func, disabled: PropTypes.bool, }; state = { selected: {}, expired: null, }; static getDerivedStateFromProps (props, state) { const { poll, intl } = props; const expired = poll.get('expired') || (new Date(poll.get('expires_at'))).getTime() < intl.now(); return (expired === state.expired) ? null : { expired }; } componentDidMount () { this._setupTimer(); } componentDidUpdate () { this._setupTimer(); } componentWillUnmount () { clearTimeout(this._timer); } _setupTimer () { const { poll, intl } = this.props; clearTimeout(this._timer); if (!this.state.expired) { const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now(); this._timer = setTimeout(() => { this.setState({ expired: true }); }, delay); } } handleOptionChange = e => { const { target: { value } } = e; if (this.props.poll.get('multiple')) { const tmp = { ...this.state.selected }; if (tmp[value]) { delete tmp[value]; } else { tmp[value] = true; } this.setState({ selected: tmp }); } else { const tmp = {}; tmp[value] = true; this.setState({ selected: tmp }); } }; handleVote = () => { if (this.props.disabled) { return; } this.props.dispatch(vote(this.props.poll.get('id'), Object.keys(this.state.selected))); }; handleRefresh = () => { if (this.props.disabled) { return; } this.props.dispatch(fetchPoll(this.props.poll.get('id'))); }; renderOption (option, optionIndex, showResults) { const { poll, disabled, intl } = this.props; const pollVotesCount = poll.get('voters_count') || poll.get('votes_count'); const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100; const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count')); const active = !!this.state.selected[`${optionIndex}`]; const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex)); let titleEmojified = option.get('title_emojified'); if (!titleEmojified) { const emojiMap = makeEmojiMap(poll); titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap); } return ( <li key={option.get('title')}> {showResults && ( <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}> {({ width }) => <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} /> } </Motion> )} <label className={classNames('poll__text', { selectable: !showResults })}> <input name='vote-options' type={poll.get('multiple') ? 'checkbox' : 'radio'} value={optionIndex} checked={active} onChange={this.handleOptionChange} disabled={disabled} /> {!showResults && <span className={classNames('poll__input', { checkbox: poll.get('multiple'), active })} />} {showResults && <span className='poll__number'> {!!voted && <Icon id='check' className='poll__vote__mark' title={intl.formatMessage(messages.voted)} />} {Math.round(percent)}% </span>} <span dangerouslySetInnerHTML={{ __html: titleEmojified }} /> </label> </li> ); } render () { const { poll, intl } = this.props; const { expired } = this.state; if (!poll) { return null; } const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />; const showResults = poll.get('voted') || expired; const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item); let votesCount = null; if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) { votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />; } else { votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />; } return ( <div className='poll'> <ul> {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))} </ul> <div className='poll__footer'> {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>} {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>} {votesCount} {poll.get('expires_at') && <span> · {timeRemaining}</span>} </div> </div> ); } }
tests/components/HelpTabs.spec.js
trussworks/DoDidDone
import React from 'react'; import { HelpTabs } from 'components/HelpTabs'; import { shallow } from 'enzyme'; describe('(Component) HelpTabs', () => { let _wrapper; beforeEach(() => _wrapper = shallow(<HelpTabs/>)); it('Renders a help tab container', () => { const tabsContainer = _wrapper.find('Tabs'); expect(tabsContainer).to.exist; }); });
example/react-native-gifted-chat/src/MessageAudio.js
Karkin/react-native-gifted-chat
import React from 'react'; import { Image, StyleSheet, View, Dimensions, TouchableOpacity, } from 'react-native'; import RNFS from 'react-native-fs'; import Sound from 'react-native-sound'; import IconIonicons from 'react-native-vector-icons/Ionicons'; var whoosh; export default class MessageAudio extends React.Component { constructor(props) { super(props); this.onActionsPress = this.onActionsPress.bind(this); } onActionsPress() { // console.log(this.props.currentMessage.audio); setTimeout(() => { var path = RNFS.CachesDirectoryPath+'/audioMsg_'+new Date().getTime()+'.aac'; RNFS.writeFile(path, this.props.currentMessage.audio, 'base64') .then((success) => { if(whoosh){ whoosh.stop(); } whoosh = new Sound(path, "", (error) => { if (error) { console.log('failed to load the sound', error); return; } // loaded successfully console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels()); setTimeout(() => { // Play the sound with an onEnd callback whoosh.play((success) => { if (success) { console.log('successfully finished playing'); } else { console.log('playback failed due to audio decoding errors'); } }); }, 100); }); }) .catch((err) => { console.log(err.message); }); }, 100); } render() { const { width, height } = Dimensions.get('window'); return ( <View style={[styles.container, this.props.containerStyle]}> <TouchableOpacity style={[styles.audio, this.props.audioStyle]} onPress={this.onActionsPress} > <IconIonicons name="ios-play" size={30} color="#000000" /> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { }, audio: { width: 100, height: 30, alignItems:'center', }, }); MessageAudio.defaultProps = { currentMessage: { image: null, }, containerStyle: {}, audioStyle: {}, audioProps: {}, }; MessageAudio.propTypes = { currentMessage: React.PropTypes.object, containerStyle: View.propTypes.style, audioStyle: Image.propTypes.style, audioProps: React.PropTypes.object, };
src/parser/warlock/demonology/modules/features/LegionStrike.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER_PET } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatThousands } from 'common/format'; import StatisticBox from 'interface/others/StatisticBox'; import { isPermanentPet } from '../pets/helpers'; class LegionStrike extends Analyzer { casts = 0; damage = 0; constructor(...args) { super(...args); this.addEventListener(Events.cast.by(SELECTED_PLAYER_PET).spell(SPELLS.FELGUARD_LEGION_STRIKE), this.legionStrikeCast); this.addEventListener(Events.damage.by(SELECTED_PLAYER_PET).spell(SPELLS.FELGUARD_LEGION_STRIKE), this.legionStrikeDamage); } legionStrikeCast(event) { // Grimoire: Felguard casts Legion Strike with the same spell ID, only count LS casts from the permanent pet if (this._isPermanentPet(event.sourceID)) { this.casts += 1; } } legionStrikeDamage(event) { if (this._isPermanentPet(event.sourceID)) { this.damage += event.amount + (event.absorbed || 0); } } _getPetGuid(id) { return this.owner.playerPets.find(pet => pet.id === id).guid; } _isPermanentPet(id) { const guid = this._getPetGuid(id); return isPermanentPet(guid); } get suggestionThresholds() { return { actual: this.casts, isLessThan: { minor: 1, average: 0, major: 0, }, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your Felguard didn't cast <SpellLink id={SPELLS.FELGUARD_LEGION_STRIKE.id} /> at all. Remember to turn on the auto-cast for this ability as it's a great portion of your total damage.</>) .icon(SPELLS.FELGUARD_LEGION_STRIKE.icon) .actual(`${actual} Legion Strike casts`) .recommended(`> ${recommended} casts are recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.FELGUARD_LEGION_STRIKE.id} />} value={this.owner.formatItemDamageDone(this.damage)} label="Legion Strike damage" tooltip={`${formatThousands(this.damage)} damage`} /> ); } } export default LegionStrike;
test/FormGroupSpec.js
victorzhang17/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import FormGroup from '../src/FormGroup'; import {shouldWarn} from './helpers'; describe('FormGroup', () => { it('renders children', () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup> <span className='child1' /> <span className='child2' /> </FormGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child1')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child2')); }); it('renders with form-group class', () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup> <span /> </FormGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group')); }); it('renders form-group with sm or lg class when bsSize is small or large', () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup bsSize="small"> <span /> </FormGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-sm')); instance = ReactTestUtils.renderIntoDocument( <FormGroup bsSize="large"> <span /> </FormGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-lg')); }); // This test case must come first, since the error only gets logged once. it('throws no warning without bsSize when standalone', () => { ReactTestUtils.renderIntoDocument( <FormGroup standalone /> ); // Warning thrown above would lead to failure from index. }); it('throws warning about bsSize when standalone', () => { ReactTestUtils.renderIntoDocument( <FormGroup standalone bsSize="large" /> ); shouldWarn('Failed propType: bsSize'); }); it('renders no form-group class when standalone', () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup standalone> <span /> </FormGroup> ); assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0); }); it('renders no form-group-* class when standalone', () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup standalone bsSize="large" /> ); assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0); assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group-lg').length, 0); }); [{ className: 'has-feedback', props: { hasFeedback: true } }, { className: 'has-success', props: { bsStyle: 'success' } }, { className: 'has-warning', props: { bsStyle: 'warning' } }, { className: 'has-error', props: { bsStyle: 'error' } }, { className: 'custom-group', props: { groupClassName: 'custom-group' } } ].forEach( testCase => { it(`does not render ${testCase.className} class`, () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup> <span /> </FormGroup> ); assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, testCase.className).length, 0); }); it(`renders with ${testCase.className} class`, () => { let instance = ReactTestUtils.renderIntoDocument( <FormGroup {...testCase.props}> <span /> </FormGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, testCase.className)); }); }); });
index.js
davidsamacoits/react-native-swipeable-parallax-carousel
import React, { Component } from 'react'; import { View, ImageBackground, Image, Text, TouchableOpacity, Animated, Dimensions, PanResponder, } from 'react-native'; import styles from './styles'; const SWIPE_THRESHOLD = 0.25; class SwipeableParallaxCarousel extends Component { // Default props // static defaultProps = { height: 200, navigationColor: '#ffffff', onPress: () => {}, } // Class constructor // constructor(props) { super(props); const position = new Animated.ValueXY(); const panResponder = PanResponder.create({ onStartShouldSetPanResponder: () => true, onMoveShouldSetPanResponder: (event, gesture) => { return Math.abs(gesture.dx) > 5; }, onPanResponderGrant: () => { // Deactivate parent scrollview if (this.props.parentScrollViewRef) this.props.parentScrollViewRef.setNativeProps({ scrollEnabled: false }); }, onPanResponderMove: (event, gesture) => { position.setValue({ x: gesture.dx, y: gesture.dy }); }, onPanResponderRelease: (event, gesture) => { if (gesture.dx > SWIPE_THRESHOLD * this.state.screenWidth) { // Can't swipe if it's the beginning if (this.state.currentItem === 0) { this._resetPosition(); } else this._forceSwipe('right'); } else if (gesture.dx < -SWIPE_THRESHOLD * this.state.screenWidth) { // Can't swipe if it's the end if (this.state.currentItem === this.props.data.length - 1) { this._resetPosition(); } else this._forceSwipe('left'); } else { this._resetPosition(); } // Reactivate parent scrollview if (this.props.parentScrollViewRef) this.props.parentScrollViewRef.setNativeProps({ scrollEnabled: true }); } }); this.panResponder = panResponder; this.position = position; this.state = { currentItem: 0, nextItem: 0, screenWidth: Dimensions.get('window').width, }; } // Force swipe // _forceSwipe(direction) { const distance = (direction === 'right') ? this.state.screenWidth : -this.state.screenWidth; // Calculate nextItem const currentitem = this.state.currentItem; const newitem = (direction === 'right') ? currentitem - 1 : currentitem + 1; this.setState({ nextItem: newitem }); Animated.spring(this.position, { toValue: { x: distance, y: 0 }, }).start(() => this._onSwipeComplete(direction, newitem)); } // on SwipeComplete // _onSwipeComplete(direction, newitem) { this.position.setValue({ x: 0, y: 0 }); this.setState({ currentItem: newitem }); } // Reset position // _resetPosition() { Animated.spring(this.position, { toValue: { x: 0, y: 0 } }).start(); } // Get overlay // _getOverlay(overlayPath, height) { if (overlayPath) return <Image source={overlayPath} style={[styles.overlay, { height, width: this.state.screenWidth }]} />; return null; } // Get title // _getTitle(item, titleColor) { if (item.title) { return ( <View style={[styles.itemTitleContainer, this._getTitleAlign(), this._getTitlePadding()]}> <Text style={[styles.itemTitle, { color: titleColor }]}>{item.title}</Text> {item.subtitle && <Text style={[styles.itemSubtitle, { color: titleColor }]}>{item.subtitle}</Text> } </View> ); } return null; } // Get title alignement // _getTitleAlign() { if (this.props.align === 'center') return { alignItems: 'center' }; if (this.props.align === 'right') return { alignItems: 'flex-end' }; return { alignItems: 'flex-start' }; } // Get title padding (if navigation active) // _getTitlePadding() { if (this.props.navigation) return { paddingBottom: 40 }; return null; } // Get style for each individual item // _getItemStyle(index) { const { position } = this; // Current item zIndex (for parallax effect) const zIndex = (index === this.state.currentItem) ? 0 : 1; // Default margin based on the item position const defaultmargin = ((index - this.state.currentItem) * this.state.screenWidth); let deltaleft = this.state.screenWidth; if (this.props.parallax && index === this.state.currentItem) deltaleft = this.state.screenWidth / 4; if (!this.props.parallax && this.state.currentItem === this.props.data.length - 1) deltaleft = this.state.screenWidth / 4; let deltaright = this.state.screenWidth; if (this.props.parallax && index === this.state.currentItem) deltaright = this.state.screenWidth / 4; if (!this.props.parallax && this.state.currentItem === 0) deltaright = this.state.screenWidth / 4; const margin = position.x.interpolate({ inputRange: [-this.state.screenWidth, 0, this.state.screenWidth], outputRange: [defaultmargin - deltaleft, defaultmargin, defaultmargin + deltaright], }); return { left: margin, zIndex, elevation: zIndex }; } // Render items method // _renderItems() { const { data, height, overlayPath, titleColor, onPress } = this.props; return data.map((item, index) => { return ( <Animated.View key={item.id} {...this.panResponder.panHandlers} style={[styles.itemContainer, { height, width: this.state.screenWidth }, this._getItemStyle(index)]} > <TouchableOpacity onPress={() => onPress(item.id)} style={styles.touchableContainer} activeOpacity={0.98} > <ImageBackground source={{ uri: item.imagePath }} style={styles.itemImage} > {this._getOverlay(overlayPath, height)} {this._getTitle(item, titleColor)} </ImageBackground> </TouchableOpacity> </Animated.View> ); }); } // Render navigation // _renderNavigation() { const { navigation, } = this.props; if (navigation) { return ( <View style={styles.navigationContainer}> {this._renderNavigationItems()} </View> ); } return null; } // Render navigation item // _renderNavigationItems() { const { data, navigationColor, navigationType } = this.props; // Type of item (dots == default, bars, squares) let typeItem = null; if (navigationType === 'bars') typeItem = styles.navigationItemBars; if (navigationType === 'squares') typeItem = styles.navigationItemSquares; return data.map((item, index) => { // Current item selection let currentItem = null; if (index === this.state.nextItem) currentItem = { backgroundColor: navigationColor, transform: [{ scale: 1.25 }] }; return ( <Animated.View key={index} style={[styles.navigationItem, typeItem, currentItem]} /> ); }); } // onLayout method to resize when orientation change // _onLayout() { this.setState({ screenWidth: Dimensions.get('window').width }); } // Render method // render() { return ( <View onLayout={this._onLayout.bind(this)}> <View style={{ height: this.props.height, width: this.state.screenWidth }}> {this._renderItems()} {this._renderNavigation()} </View> </View> ); } } export default SwipeableParallaxCarousel;
ajax/libs/yui/3.8.1/scrollview-base/scrollview-base-coverage.js
marxo/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/scrollview-base/scrollview-base.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/scrollview-base/scrollview-base.js", code: [] }; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].code=["YUI.add('scrollview-base', function (Y, NAME) {","","/**"," * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators"," *"," * @module scrollview"," * @submodule scrollview-base"," */","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,",""," /**"," * 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;"," "," if (svAxis && svAxis.x) {"," bb.addClass(CLASS_NAMES.horizontal);"," }",""," if (svAxis && svAxis.y) {"," bb.addClass(CLASS_NAMES.vertical);"," }",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis"," *"," * @property _minScrollX"," * @type number"," * @protected"," */"," sv._minScrollX = (rtl) ? Math.min(0, -(scrollWidth - width)) : 0;",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis"," *"," * @property _maxScrollX"," * @type number"," * @protected"," */"," sv._maxScrollX = (rtl) ? 0 : Math.max(0, scrollWidth - width);",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _minScrollY"," * @type number"," * @protected"," */"," sv._minScrollY = 0;",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _maxScrollY"," * @type number"," * @protected"," */"," sv._maxScrollY = Math.max(0, scrollHeight - height);"," },",""," /**"," * 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;",""," /**"," * 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) {"," // Cancel and delete sv._flickAnim"," sv._flickAnim.cancel();"," delete sv._flickAnim;"," sv._onTransEnd();"," }",""," // TODO: Review if neccesary (#2530129)"," e.stopPropagation();",""," // 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;",""," 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) {",""," // If we're out-out-bounds, then snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }",""," // Inbounds"," else {"," // Don't fire scrollEnd on 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.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,",""," // 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 ? sv._minScrollX : sv._minScrollY,"," max = flickAxis === DIM_X ? sv._maxScrollX : sv._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._flickAnim.cancel();"," delete sv._flickAnim;"," }",""," // 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);"," }"," },",""," /**"," * 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),"," bb = sv._bb,"," scrollOffset = 10, // 10px"," isForward = (e.wheelDelta > 0),"," scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);",""," scrollToY = _constrain(scrollToY, sv._minScrollY, sv._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),"," minX = sv._minScrollX,"," minY = sv._minScrollY,"," maxX = sv._maxScrollX,"," maxY = sv._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),"," minX = sv._minScrollX,"," minY = sv._minScrollY,"," maxX = sv._maxScrollX,"," maxY = sv._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 {"," // It shouldn't ever get here, but in case it does, fire scrollEnd"," 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;",""," // @TODO: Move to sv._cancelFlick()"," 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;"," }",""," // If for some reason we're OOB, snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }",""," // 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});"]; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].lines = {"1":0,"9":0,"49":0,"61":0,"62":0,"65":0,"132":0,"135":0,"136":0,"139":0,"140":0,"141":0,"142":0,"143":0,"153":0,"156":0,"157":0,"158":0,"161":0,"164":0,"165":0,"169":0,"170":0,"173":0,"174":0,"177":0,"178":0,"181":0,"182":0,"185":0,"186":0,"201":0,"206":0,"229":0,"233":0,"235":0,"236":0,"249":0,"253":0,"255":0,"256":0,"259":0,"272":0,"277":0,"280":0,"282":0,"294":0,"302":0,"305":0,"310":0,"314":0,"317":0,"320":0,"323":0,"324":0,"338":0,"351":0,"352":0,"353":0,"356":0,"357":0,"359":0,"360":0,"366":0,"368":0,"370":0,"381":0,"391":0,"392":0,"395":0,"396":0,"406":0,"415":0,"424":0,"433":0,"449":0,"450":0,"453":0,"463":0,"464":0,"465":0,"467":0,"468":0,"469":0,"472":0,"473":0,"474":0,"477":0,"479":0,"481":0,"485":0,"486":0,"487":0,"492":0,"493":0,"495":0,"496":0,"503":0,"504":0,"506":0,"507":0,"510":0,"511":0,"514":0,"529":0,"531":0,"532":0,"535":0,"548":0,"549":0,"551":0,"552":0,"565":0,"573":0,"585":0,"586":0,"589":0,"596":0,"597":0,"601":0,"603":0,"604":0,"605":0,"609":0,"612":0,"615":0,"655":0,"667":0,"668":0,"671":0,"672":0,"676":0,"677":0,"681":0,"682":0,"684":0,"685":0,"697":0,"703":0,"704":0,"708":0,"709":0,"712":0,"713":0,"716":0,"722":0,"725":0,"726":0,"733":0,"734":0,"749":0,"750":0,"753":0,"762":0,"763":0,"767":0,"768":0,"783":0,"810":0,"811":0,"815":0,"818":0,"820":0,"821":0,"822":0,"826":0,"827":0,"832":0,"839":0,"840":0,"852":0,"859":0,"865":0,"868":0,"871":0,"875":0,"877":0,"878":0,"884":0,"887":0,"901":0,"912":0,"923":0,"935":0,"936":0,"938":0,"939":0,"943":0,"956":0,"957":0,"960":0,"967":0,"970":0,"971":0,"972":0,"975":0,"976":0,"979":0,"980":0,"982":0,"993":0,"1005":0,"1016":0,"1027":0,"1038":0,"1049":0,"1052":0,"1054":0,"1057":0,"1061":0,"1062":0,"1083":0,"1084":0,"1104":0,"1105":0,"1108":0,"1120":0,"1132":0}; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].functions = {"_constrain:48":0,"ScrollView:61":0,"initializer:131":0,"bindUI:152":0,"_bindAttrs:200":0,"_bindDrag:228":0,"_bindFlick:248":0,"_bindMousewheel:271":0,"syncUI:293":0,"_getScrollDims:337":0,"_uiDimensionsChange:380":0,"scrollTo:447":0,"_transform:527":0,"_moveTo:547":0,"_onTransEnd:564":0,"_onGestureMoveStart:583":0,"_onGestureMove:654":0,"_onGestureMoveEnd:696":0,"_flick:748":0,"_flickFrame:781":0,"_mousewheel:851":0,"_isOutOfBounds:900":0,"_snapBack:922":0,"_afterScrollChange:954":0,"_afterFlickChange:992":0,"_afterDisabledChange:1003":0,"_afterAxisChange:1015":0,"_afterDragChange:1026":0,"_afterDimChange:1037":0,"_afterScrollEnd:1048":0,"_axisSetter:1080":0,"_setScroll:1101":0,"_setScrollX:1119":0,"_setScrollY:1131":0,"(anonymous 1):1":0}; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].coveredLines = 218; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].coveredFunctions = 35; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1); YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "(anonymous 1)", 1); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 9); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_constrain", 48); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 49); 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 */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 61); function ScrollView() { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "ScrollView", 61); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 62); ScrollView.superclass.constructor.apply(this, arguments); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 65); 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, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "initializer", 131); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 132); var sv = this; // Cache these values, since they aren't going to change. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 135); sv._bb = sv.get(BOUNDING_BOX); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 136); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes _yuitest_coverline("build/scrollview-base/scrollview-base.js", 139); sv._cAxis = sv.get(AXIS); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 140); sv._cBounce = sv.get(BOUNCE); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 141); sv._cBounceRange = sv.get(BOUNCE_RANGE); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 142); sv._cDeceleration = sv.get(DECELERATION); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 143); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "bindUI", 152); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 153); var sv = this; // Bind interaction listers _yuitest_coverline("build/scrollview-base/scrollview-base.js", 156); sv._bindFlick(sv.get(FLICK)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 157); sv._bindDrag(sv.get(DRAG)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 158); sv._bindMousewheel(true); // Bind change events _yuitest_coverline("build/scrollview-base/scrollview-base.js", 161); sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 164); if (IE) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 165); sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties _yuitest_coverline("build/scrollview-base/scrollview-base.js", 169); if (ScrollView.SNAP_DURATION) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 170); sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 173); if (ScrollView.SNAP_EASING) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 174); sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 177); if (ScrollView.EASING) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 178); sv.set(EASING, ScrollView.EASING); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 181); if (ScrollView.FRAME_STEP) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 182); sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 185); if (ScrollView.BOUNCE_RANGE) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 186); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindAttrs", 200); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 201); var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 206); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindDrag", 228); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 229); var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 233); bb.detach(DRAG + '|*'); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 235); if (drag) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 236); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindFlick", 248); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 249); var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 253); bb.detach(FLICK + '|*'); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 255); if (flick) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 256); bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick _yuitest_coverline("build/scrollview-base/scrollview-base.js", 259); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindMousewheel", 271); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 272); var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 277); bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews _yuitest_coverline("build/scrollview-base/scrollview-base.js", 280); if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 282); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "syncUI", 293); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 294); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 302); if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes _yuitest_coverline("build/scrollview-base/scrollview-base.js", 305); sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 310); sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node _yuitest_coverline("build/scrollview-base/scrollview-base.js", 314); sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value _yuitest_coverline("build/scrollview-base/scrollview-base.js", 317); sv._cDisabled = sv.get(DISABLED); // Run this to set initial values _yuitest_coverline("build/scrollview-base/scrollview-base.js", 320); sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 323); if (sv._isOutOfBounds()) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 324); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_getScrollDims", 337); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 338); 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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 351); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 352); cb.setStyle(TRANS.DURATION, ZERO); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 353); cb.setStyle(TRANS.PROPERTY, EMPTY); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 356); origHWTransform = sv._forceHWTransforms; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 357); sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 359); sv._moveTo(cb, 0, 0); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 360); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 366); sv._moveTo(cb, -(origX), -(origY)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 368); sv._forceHWTransforms = origHWTransform; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 370); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_uiDimensionsChange", 380); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 381); 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; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 391); if (svAxis && svAxis.x) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 392); bb.addClass(CLASS_NAMES.horizontal); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 395); if (svAxis && svAxis.y) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 396); bb.addClass(CLASS_NAMES.vertical); } /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 406); sv._minScrollX = (rtl) ? Math.min(0, -(scrollWidth - width)) : 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 415); sv._maxScrollX = (rtl) ? 0 : Math.max(0, scrollWidth - width); /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 424); sv._minScrollY = 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 433); sv._maxScrollY = Math.max(0, scrollHeight - height); }, /** * 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "scrollTo", 447); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 449); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 450); return; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 453); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 463); duration = duration || 0; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 464); easing = easing || sv.get(EASING); // @TODO: Cache this _yuitest_coverline("build/scrollview-base/scrollview-base.js", 465); node = node || cb; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 467); if (x !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 468); sv.set(SCROLL_X, x, {src:UI}); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 469); newX = -(x); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 472); if (y !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 473); sv.set(SCROLL_Y, y, {src:UI}); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 474); newY = -(y); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 477); transform = sv._transform(newX, newY); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 479); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 481); node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move _yuitest_coverline("build/scrollview-base/scrollview-base.js", 485); if (duration === 0) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 486); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 487); 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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 492); if (x !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 493); node.setStyle(LEFT, newX + PX); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 495); if (y !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 496); node.setStyle(TOP, newY + PX); } } } // Animate else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 503); transition.easing = easing; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 504); transition.duration = duration / 1000; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 506); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 507); transition.transform = transform; } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 510); transition.left = newX + PX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 511); transition.top = newY + PX; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 514); 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? _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_transform", 527); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 529); var prop = 'translate(' + x + 'px, ' + y + 'px)'; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 531); if (this._forceHWTransforms) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 532); prop += ' translateZ(0)'; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 535); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_moveTo", 547); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 548); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 549); node.setStyle('transform', this._transform(x, y)); } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 551); node.setStyle(LEFT, x + PX); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 552); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onTransEnd", 564); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 565); var sv = this; /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 573); sv.fire(EV_SCROLL_END); }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMoveStart", 583); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 585); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 586); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 589); var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 596); if (sv._prevent.start) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 597); e.preventDefault(); } // if a flick animation is in progress, cancel it _yuitest_coverline("build/scrollview-base/scrollview-base.js", 601); if (sv._flickAnim) { // Cancel and delete sv._flickAnim _yuitest_coverline("build/scrollview-base/scrollview-base.js", 603); sv._flickAnim.cancel(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 604); delete sv._flickAnim; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 605); sv._onTransEnd(); } // TODO: Review if neccesary (#2530129) _yuitest_coverline("build/scrollview-base/scrollview-base.js", 609); e.stopPropagation(); // Reset lastScrolledAmt _yuitest_coverline("build/scrollview-base/scrollview-base.js", 612); sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later _yuitest_coverline("build/scrollview-base/scrollview-base.js", 615); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMove", 654); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 655); 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; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 667); if (sv._prevent.move) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 668); e.preventDefault(); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 671); gesture.deltaX = startClientX - clientX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 672); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 676); if (gesture.axis === null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 677); gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 681); if (gesture.axis === DIM_X && svAxisX) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 682); sv.set(SCROLL_X, startX + gesture.deltaX); } else {_yuitest_coverline("build/scrollview-base/scrollview-base.js", 684); if (gesture.axis === DIM_Y && svAxisY) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 685); sv.set(SCROLL_Y, startY + gesture.deltaY); }} }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMoveEnd", 696); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 697); var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 703); if (sv._prevent.end) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 704); e.preventDefault(); } // Store the end X/Y coordinates _yuitest_coverline("build/scrollview-base/scrollview-base.js", 708); gesture.endClientX = clientX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 709); gesture.endClientY = clientY; // Cleanup the event handlers _yuitest_coverline("build/scrollview-base/scrollview-base.js", 712); gesture.onGestureMove.detach(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 713); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle _yuitest_coverline("build/scrollview-base/scrollview-base.js", 716); 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) _yuitest_coverline("build/scrollview-base/scrollview-base.js", 722); if (gesture.deltaX !== null && gesture.deltaY !== null) { // If we're out-out-bounds, then snapback _yuitest_coverline("build/scrollview-base/scrollview-base.js", 725); if (sv._isOutOfBounds()) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 726); sv._snapBack(); } // Inbounds else { // Don't fire scrollEnd on 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 733); if (sv.pages && !sv.pages.get(AXIS)[gesture.axis]) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 734); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_flick", 748); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 749); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 750); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 753); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 762); if (sv._gesture) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 763); sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis _yuitest_coverline("build/scrollview-base/scrollview-base.js", 767); if (svAxis[flickAxis]) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 768); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_flickFrame", 781); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 783); var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, // 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 ? sv._minScrollX : sv._minScrollY, max = flickAxis === DIM_X ? sv._maxScrollX : sv._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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 810); if (withinMinRange || withinMaxRange) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 811); newVelocity *= bounce; } // Is the velocity too slow to bother? _yuitest_coverline("build/scrollview-base/scrollview-base.js", 815); tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range _yuitest_coverline("build/scrollview-base/scrollview-base.js", 818); if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim _yuitest_coverline("build/scrollview-base/scrollview-base.js", 820); if (sv._flickAnim) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 821); sv._flickAnim.cancel(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 822); delete sv._flickAnim; } // If we're inside the scroll area, just end _yuitest_coverline("build/scrollview-base/scrollview-base.js", 826); if (aboveMin && belowMax) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 827); sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 832); sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead _yuitest_coverline("build/scrollview-base/scrollview-base.js", 839); sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 840); sv.set(axisAttr, newPosition); } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_mousewheel", 851); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 852); var sv = this, scrollY = sv.get(SCROLL_Y), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 859); scrollToY = _constrain(scrollToY, sv._minScrollY, sv._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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 865); if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt _yuitest_coverline("build/scrollview-base/scrollview-base.js", 868); sv.lastScrolledAmt = 0; // Jump to the new offset _yuitest_coverline("build/scrollview-base/scrollview-base.js", 871); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 875); if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves _yuitest_coverline("build/scrollview-base/scrollview-base.js", 877); sv.scrollbars._update(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 878); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event _yuitest_coverline("build/scrollview-base/scrollview-base.js", 884); sv._onTransEnd(); // prevent browser default behavior on mouse scroll _yuitest_coverline("build/scrollview-base/scrollview-base.js", 887); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_isOutOfBounds", 900); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 901); var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 912); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_snapBack", 922); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 923); var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 935); if (newX !== currentX) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 936); sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else {_yuitest_coverline("build/scrollview-base/scrollview-base.js", 938); if (newY !== currentY) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 939); sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { // It shouldn't ever get here, but in case it does, fire scrollEnd _yuitest_coverline("build/scrollview-base/scrollview-base.js", 943); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterScrollChange", 954); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 956); if (e.src === ScrollView.UI_SRC) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 957); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 960); var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value _yuitest_coverline("build/scrollview-base/scrollview-base.js", 967); sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() _yuitest_coverline("build/scrollview-base/scrollview-base.js", 970); if (e.attrName === SCROLL_X) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 971); scrollToArgs.push(val); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 972); scrollToArgs.push(sv.get(SCROLL_Y)); } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 975); scrollToArgs.push(sv.get(SCROLL_X)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 976); scrollToArgs.push(val); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 979); scrollToArgs.push(duration); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 980); scrollToArgs.push(easing); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 982); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterFlickChange", 992); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 993); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDisabledChange", 1003); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1005); this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterAxisChange", 1015); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1016); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDragChange", 1026); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1027); this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDimChange", 1037); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1038); this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterScrollEnd", 1048); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1049); var sv = this; // @TODO: Move to sv._cancelFlick() _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1052); if (sv._flickAnim) { // Cancel the flick (if it exists) _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1054); sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1057); delete sv._flickAnim; } // If for some reason we're OOB, snapback _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1061); if (sv._isOutOfBounds()) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1062); sv._snapBack(); } // 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_axisSetter", 1080); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1083); if (Y.Lang.isString(val)) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1084); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScroll", 1101); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1104); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1105); val = Y.Attribute.INVALID_VALUE; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1108); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScrollX", 1119); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1120); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScrollY", 1131); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1132); 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});
blueocean-material-icons/src/js/components/svg-icons/image/collections-bookmark.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageCollectionsBookmark = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 10l-2.5-1.5L15 12V4h5v8z"/> </SvgIcon> ); ImageCollectionsBookmark.displayName = 'ImageCollectionsBookmark'; ImageCollectionsBookmark.muiName = 'SvgIcon'; export default ImageCollectionsBookmark;
app/containers/Launch/index.js
abakusbackup/abacash-client
// @flow import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { fetchSeller } from '../../actions/system'; import Style from './Launch.css'; import RFID from '../../components/RFID'; import Button, { Buttons } from '../../components/Button'; import { addNotification } from '../../actions/notification'; type Props = { system: Object, seller: Object, rfidDevice: string, push: () => void, fetchSystem: () => Promise<*>, fetchSeller: () => Promise<*>, addNotification: () => Promise<*> }; class LaunchContainer extends React.Component { setSeller = (card) => { this.props.fetchSeller(card); } onScan = (card) => { this.props.fetchSeller(card) .catch(() => { this.props.addNotification({ title: 'Not found!', level: 'warning', message: 'Could not find the specified user', uid: 'user_not_found' }); }); } handleStart = () => { if (this.props.system.get('needSeller') && !this.props.seller) { this.props.addNotification({ title: 'Du må registrer en selger!', level: 'info', message: 'Du må være en registrert selger. Koble til RFID-leser og skann kortet ditt.', autoDismiss: 0, uid: 'not_seller' }); } else { this.props.push('/sales'); } } props: Props; render() { return ( <div className={Style.launchContainer}> <h1 className={Style.header}>AbaCash</h1> {this.props.system && <h6 className={Style.subHeader}>{this.props.system.get('name')}</h6>} {this.props.system && this.props.seller && this.props.system.get('needSeller') && <h6 className={Style.subHeader}> Seller: {this.props.seller.get('displayName') || '- Scan card -'} </h6> } <Buttons> <Button cancel onClick={() => { this.props.push('/?presist=true'); }} label='Tilbake' /> {this.props.system && <Button confirm onClick={this.handleStart} label='Start' />} </Buttons> <RFID device={this.props.rfidDevice} action={this.onScan} /> </div> ); } } const mapStateToProps = (store) => ({ seller: store.system.get('seller'), rfidDevice: store.rfid.get('device') }); const mapDispatchToProps = { fetchSeller, push, addNotification }; export default connect(mapStateToProps, mapDispatchToProps)(LaunchContainer);
src/Parser/Hunter/BeastMastery/Modules/Features/AlwaysBeCasting.js
enragednuke/WoWAnalyzer
import React from 'react'; import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'Main/StatisticBox'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; class AlwaysBeCasting extends CoreAlwaysBeCasting { static dependencies = { ...CoreAlwaysBeCasting.dependencies, combatants: Combatants, }; get suggestionThresholds() { return { actual: this.downtimePercentage, isGreaterThan: { minor: 0.15, average: 0.175, major: 0.2, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your downtime can be improved. Try to reduce the delay between casting spells. If everything is on cooldown, try and use <SpellLink id={SPELLS.COBRA_SHOT.id} /> to stay off the focus cap and do some damage.</Wrapper>) .icon('spell_mage_altertime') .actual(`${formatPercentage(actual)}% downtime`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } statisticOrder = STATISTIC_ORDER.CORE(1); } export default AlwaysBeCasting;
node_modules/grunt/node_modules/js-yaml/node_modules/argparse/node_modules/underscore.string/test/test_underscore/vendor/jquery.js
jesusjavierdediego/DataGridSamples
/*! * jQuery JavaScript Library v1.7.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: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * 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( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( 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, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { 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 ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, 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; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { div.innerHTML = ""; marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // 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] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = 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; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( 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 ) { for ( var 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; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); 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 ); 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise( object ); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, 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 self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: selector && quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // 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 && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; 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 ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var 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 ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.globalPOS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { 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, "" ) : null; } if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType, script, j, ret = []; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"), safeChildNodes = safeFragment.childNodes, remove; // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }; 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; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}, ret, name; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( rnumnonpx.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : value; } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && 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, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( (display === "" && jQuery.css(elem, "display") === "none") || !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; 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 ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // 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( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; 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(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow( doc ), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {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 ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ 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 width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, null ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
src/svg-icons/places/child-care.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesChildCare = (props) => ( <SvgIcon {...props}> <circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/> </SvgIcon> ); PlacesChildCare = pure(PlacesChildCare); PlacesChildCare.displayName = 'PlacesChildCare'; PlacesChildCare.muiName = 'SvgIcon'; export default PlacesChildCare;
app/jsx/grading/AccountTabContainer.js
venturehive/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import GradingStandardCollection from 'jsx/grading/gradingStandardCollection' import GradingPeriodSetCollection from 'jsx/grading/GradingPeriodSetCollection' import $ from 'jquery' import I18n from 'i18n!grading_periods' const { bool, string, shape } = PropTypes; class AccountTabContainer extends React.Component { static propTypes = { readOnly: bool.isRequired, urls: shape({ gradingPeriodSetsURL: string.isRequired, gradingPeriodsUpdateURL: string.isRequired, enrollmentTermsURL: string.isRequired, deleteGradingPeriodURL: string.isRequired }).isRequired, } componentDidMount () { $(this.tabContainer).children('.ui-tabs-minimal').tabs(); } render () { return ( <div ref={(el) => { this.tabContainer = el; }}> <h1>{I18n.t('Grading')}</h1> <div className="ui-tabs-minimal"> <ul> <li><a href="#grading-periods-tab" className="grading_periods_tab"> {I18n.t('Grading Periods')}</a></li> <li><a href="#grading-standards-tab" className="grading_standards_tab"> {I18n.t('Grading Schemes')}</a></li> </ul> <div ref={(el) => { this.gradingPeriods = el; }} id="grading-periods-tab" > <GradingPeriodSetCollection urls={this.props.urls} readOnly={this.props.readOnly} /> </div> <div ref={(el) => { this.gradingStandards = el; }} id="grading-standards-tab" > <GradingStandardCollection /> </div> </div> </div> ); } } export default AccountTabContainer
ajax/libs/yui/3.5.0/event-custom-base/event-custom-base-debug.js
hcxiong/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
todomvc/test/components/Header.spec.js
samlatif-uk/redux-tdd-hw
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Header from '../../components/Header' import TodoTextInput from '../../components/TodoTextInput' function setup() { const props = { addTodo: expect.createSpy() } const renderer = TestUtils.createRenderer() renderer.render(<Header {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output, renderer: renderer } } describe('components', () => { describe('Header', () => { it('should render correctly', () => { const { output } = setup() expect(output.type).toBe('header') expect(output.props.className).toBe('header') const [ h1, input ] = output.props.children expect(h1.type).toBe('h1') expect(h1.props.children).toBe('todos') expect(input.type).toBe(TodoTextInput) expect(input.props.newTodo).toBe(true) expect(input.props.placeholder).toBe('What needs to be done?') }) it('should call addTodo if length of text is greater than 0', () => { const { output, props } = setup() const input = output.props.children[1] input.props.onSave('') expect(props.addTodo.calls.length).toBe(0) input.props.onSave('Use Redux') expect(props.addTodo.calls.length).toBe(1) }) }) })
app/app.js
rjzheng/REWBoilerplate
/* Node Modules */ import React from 'react'; import ReactDOM from 'react-dom'; import { Route, Router, IndexRoute, hashHistory } from 'react-router'; import { Provider } from 'react-redux'; /* Routes */ import routes from './routes'; /* Store */ import * as conf from 'configureStore'; // Init custom store configuration var store = conf.configure(); // Subscribe to state changes store.subscribe(() => { console.log('Store changed', store.getState()); }); // Render provider and routes to DOM ReactDOM.render( <Provider store={store}> <Router history={hashHistory} routes={routes} /> </Provider>, document.getElementById('app') );
src/__tests__/components/Auth/ChangePassword.js
isuruAb/chat.susi.ai
import React from 'react'; import ChangePassword from '../../../components/Auth/ChangePassword/ChangePassword.react'; import { shallow } from 'enzyme'; it('render ChangePassword without crashing',()=>{ shallow(<ChangePassword />); });
src/components/NotFoundPage/NotFoundPage.js
elurye/ReactJestBoiler
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; //require('./NotFoundPage.less'); import React, { Component } from 'react'; class NotFoundPage extends Component { render() { return ( <div> <h1>Page Not Found</h1> <p>Sorry, but the page you were trying to view does not exist.</p> </div> ); } } export default NotFoundPage;
docs/app/Examples/views/Statistic/Content/StatisticExampleProps.js
koenvg/Semantic-UI-React
import React from 'react' import { Statistic } from 'semantic-ui-react' const items = [ { key: '22', label: 'Saves', value: '22' }, { key: 'Three Thousand', label: 'Signups', text: true, value: 'Three Thousand' }, { key: '5', label: 'Flights', value: '5' }, { key: '42', label: 'Team Members', value: '42' }, ] const StatisticExampleProps = () => ( <div> <Statistic.Group> <Statistic label='Saves' value='22' /> <Statistic label='Signups' value='Three Thousand' text /> <Statistic label='Flights' value='5' /> <Statistic label='Team Members' value='42' /> </Statistic.Group> <Statistic.Group items={items} /> </div> ) export default StatisticExampleProps
assets/blog/js/Article.js
mywei1989/blog_react
import React from 'react'; import { Link } from 'react-router'; import $ from 'jquery'; import Settings from '../../../settings'; class Article extends React.Component{ constructor(props){ super(props); this.state={ title:'', timeStr:'', tags:[], post:'' } } componentDidMount(){ this.getArticle(this.props); } componentWillReceiveProps(nextProps){ this.getArticle(nextProps); } getArticle(props){ let self = this; let url = Settings.getServiceUrl(); //判断是否是从router进入 从router进入这是是undefined if(props.params){ let queryType = props.route.to.queryType; if(queryType!='info'){ url = url + '/' + props.params.year + '/' + props.params.month + '/' + props.params.name; }else{ url = url + '/' + props.params.info; } $.ajax({ url:url, type:'GET', }).done(function(result){ self.setState({ title:result.article.title, timeStr:result.article.timeStr, tags:result.article.tags, post:result.article.post }); }.bind(self)); } } render(){ if(this.props.route){ return ( <article> <header> <h2> <a href="#">{this.state.title}</a> </h2> </header> <div className="article-meta clearfix"> <time className="left">{this.state.timeStr}</time> <ul className="tags left"></ul> <ul className="tags right"> { this.state.tags.map(function(item,index){ return (<li><Link to={"/tag"+"/"+item.tag+"/"}>{item.tagName}</Link></li>) }) } </ul> </div> <div className="markdown-body" dangerouslySetInnerHTML={{__html: this.state.post}}> </div> </article> ) }else{ return( <article> <header> <h2> <Link to={"/"+this.props.articleModel.time.year+"/"+this.props.articleModel.time.month+"/"+this.props.articleModel.name}>{this.props.articleModel.title}</Link> </h2> </header> <div className="article-meta clearfix"> <time className="left" >{this.props.articleModel.timeStr}</time> <ul className="tags right"> { this.props.articleModel.tags.map(function(item,index){ return (<li key={index}><Link to={"/tag"+"/"+item.tag+"/"}>{item.tagName}</Link></li>) }) } </ul> </div> <div className="markdown-body" dangerouslySetInnerHTML={{__html: this.props.articleModel.post}}> </div> </article> ) } } } export default Article
apps/mk-app-devtools/apps/mk-app-devtools-test/action.js
ziaochina/mk-demo
import React from 'react' import { action as MetaAction, AppLoader } from 'mk-meta-engine' import config from './config' class action { constructor(option) { this.metaAction = option.metaAction this.config = config.current } onInit = ({ component, injections }) => { this.component = component this.injections = injections console.log('test') injections.reduce('init') } btnClick = async() => { const ret = await this.metaAction.modal('show', { title: 'devtools', width: 900, bodyStyle: {height: 600, overflow: 'auto'}, children: this.metaAction.loadApp('mk-app-devtools', { store: this.component.props.store, }) }) console.log(ret) } } export default function creator(option) { const metaAction = new MetaAction(option), o = new action({ ...option, metaAction }), ret = { ...metaAction, ...o } metaAction.config({ metaHandlers: ret }) return ret }
src/svg-icons/action/flight-takeoff.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFlightTakeoff = (props) => ( <SvgIcon {...props}> <path d="M2.5 19h19v2h-19zm19.57-9.36c-.21-.8-1.04-1.28-1.84-1.06L14.92 10l-6.9-6.43-1.93.51 4.14 7.17-4.97 1.33-1.97-1.54-1.45.39 1.82 3.16.77 1.33 1.6-.43 5.31-1.42 4.35-1.16L21 11.49c.81-.23 1.28-1.05 1.07-1.85z"/> </SvgIcon> ); ActionFlightTakeoff = pure(ActionFlightTakeoff); ActionFlightTakeoff.displayName = 'ActionFlightTakeoff'; ActionFlightTakeoff.muiName = 'SvgIcon'; export default ActionFlightTakeoff;
src/components/Root.js
coryhouse/react-slingshot
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ConnectedRouter } from 'connected-react-router'; import { Provider } from 'react-redux'; import App from './App'; export default class Root extends Component { render() { const { store, history } = this.props; return ( <Provider store={store}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </Provider> ); } } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired };
fields/types/embedly/EmbedlyField.js
joerter/keystone
import React from 'react'; import Field from '../Field'; import { FormField, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'EmbedlyField', // always defers to renderValue; there is no form UI for this field renderField () { return this.renderValue(); }, renderValue (path, label, multiline) { return ( <FormField key={path} label={label} className="form-field--secondary"> <FormInput noedit multiline={multiline}>{this.props.value[path]}</FormInput> </FormField> ); }, renderAuthor () { if (!this.props.value.authorName) return; return ( <FormField key="author" label="Author" className="form-field--secondary"> <FormInput noedit href={this.props.value.authorUrl && this.props.value.authorUrl} target="_blank">{this.props.value.authorName}</FormInput> </FormField> ); }, renderDimensions () { if (!this.props.value.width || !this.props.value.height) return; return ( <FormField key="dimensions" label="Dimensions" className="form-field--secondary"> <FormInput noedit>{this.props.value.width} &times; {this.props.value.height}px</FormInput> </FormField> ); }, renderPreview () { if (!this.props.value.thumbnailUrl) return; var image = <img width={this.props.value.thumbnailWidth} height={this.props.value.thumbnailHeight} src={this.props.value.thumbnailUrl} />; var preview = this.props.value.url ? ( <a href={this.props.value.url} target="_blank" className="img-thumbnail">{image}</a> ) : ( <div className="img-thumbnail">{image}</div> ); return ( <FormField label="Preview" className="form-field--secondary"> {preview} </FormField> ); }, renderUI () { if (!this.props.value.exists) { return ( <FormField label={this.props.label}> <FormInput noedit>(not set)</FormInput> </FormField> ); } return ( <div className="field-type-embedly"> <FormField key="provider" label={this.props.label}> <FormInput noedit>{this.props.value.providerName} {this.props.value.type}</FormInput> </FormField> {this.renderValue('title', 'Title')} {this.renderAuthor()} {this.renderValue('description', 'Description', true)} {this.renderPreview()} {this.renderDimensions()} </div> ); }, });
src/ModalTitle.js
westonplatter/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalTitle extends React.Component { render() { return ( <h4 {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> { this.props.children } </h4> ); } } ModalTitle.propTypes = { /** * A css class applied to the Component */ modalClassName: React.PropTypes.string }; ModalTitle.defaultProps = { modalClassName: 'modal-title' }; export default ModalTitle;
Libraries/Image/Image.ios.js
charlesvinette/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 on 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. */ 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.string, /** * 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 sucessfully 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;
src/components/App.js
betoesquivel/hackmtyaug16_LSystemsUI
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Text } from 'essence-core'; import AppBar from 'essence-appbar'; import Icon from 'essence-icon'; import { Block } from 'essence-core'; import {orange, grey, blue, lightblue, lightergrey} from '../colors.js'; import Evolve from './Evolve.js'; import MyDivider from './Divider.js'; import RankedIndividuals from './RankedIndividuals.js'; import * as Actions from '../actions/Actions'; @connect(state => ( {state: state.GeneticReducer } )) export default class App extends Component { render() { const {state, dispatch} = this.props; return ( <div> <AppBar classes={'e-text-white'} style={ {backgroundColor: orange} }> <Icon name={"notification-sync"} /> <Text classes={'e-text-right e-text-lowercase e-display-1'}> {'genetic turtle-drawn lsystems'} </Text> </AppBar> <Evolve {...bindActionCreators(Actions, dispatch)} state={state} /> <MyDivider {...bindActionCreators(Actions, dispatch)} state={state} /> <RankedIndividuals {...bindActionCreators(Actions, dispatch)} hasMore={state.get('hasMore')} lastEvaluatedIndividual={state.get('lastEvaluatedIndividual')} ranked-individuals={state.get('rankedIndividuals')} /> </div> ); } }
ajax/libs/onsen/2.0.0-alpha.14/js/onsenui.min.js
hanbyul-here/cdnjs
/*! onsenui v2.0.0-alpha.14 - 2015-11-10 */ function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}!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)})}}(),document.registerElement=void 0,"undefined"==typeof WeakMap&&!function(){var defineProperty=Object.defineProperty,counter=Date.now()%1e9,WeakMap=function(){this.name="__st"+(1e9*Math.random()>>>0)+(counter++ +"__")};WeakMap.prototype={set:function(key,value){var entry=key[this.name];return entry&&entry[0]===key?entry[1]=value:defineProperty(key,this.name,{value:[key,value],writable:!0}),this},get:function(key){var entry;return(entry=key[this.name])&&entry[0]===key?entry[1]:void 0},"delete":function(key){var entry=key[this.name];return entry&&entry[0]===key?(entry[0]=entry[1]=void 0, !0):!1},has:function(key){var entry=key[this.name];return entry?entry[0]===key:!1}},window.WeakMap=WeakMap}(),function(global){function scheduleCallback(observer){scheduledObservers.push(observer),isScheduled||(isScheduled=!0,setImmediate(dispatchCallbacks))}function wrapIfNeeded(node){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(node)||node}function dispatchCallbacks(){isScheduled=!1;var observers=scheduledObservers;scheduledObservers=[],observers.sort(function(o1,o2){return o1.uid_-o2.uid_});var anyNonEmpty=!1;observers.forEach(function(observer){var queue=observer.takeRecords();removeTransientObserversFor(observer),queue.length&&(observer.callback_(queue,observer),anyNonEmpty=!0)}),anyNonEmpty&&dispatchCallbacks()}function removeTransientObserversFor(observer){observer.nodes_.forEach(function(node){var registrations=registrationsTable.get(node);registrations&&registrations.forEach(function(registration){registration.observer===observer&&registration.removeTransientObservers()})})}function forEachAncestorAndObserverEnqueueRecord(target,callback){for(var node=target;node;node=node.parentNode){var registrations=registrationsTable.get(node);if(registrations)for(var j=0;j<registrations.length;j++){var registration=registrations[j],options=registration.options;if(node===target||options.subtree){var record=callback(options);record&&registration.enqueue(record)}}}}function JsMutationObserver(callback){this.callback_=callback,this.nodes_=[],this.records_=[],this.uid_=++uidCounter}function MutationRecord(type,target){this.type=type,this.target=target,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function copyMutationRecord(original){var record=new MutationRecord(original.type,original.target);return record.addedNodes=original.addedNodes.slice(),record.removedNodes=original.removedNodes.slice(),record.previousSibling=original.previousSibling,record.nextSibling=original.nextSibling,record.attributeName=original.attributeName,record.attributeNamespace=original.attributeNamespace,record.oldValue=original.oldValue,record}function getRecord(type,target){return currentRecord=new MutationRecord(type,target)}function getRecordWithOldValue(oldValue){return recordWithOldValue?recordWithOldValue:(recordWithOldValue=copyMutationRecord(currentRecord),recordWithOldValue.oldValue=oldValue,recordWithOldValue)}function clearRecords(){currentRecord=recordWithOldValue=void 0}function recordRepresentsCurrentMutation(record){return record===recordWithOldValue||record===currentRecord}function selectRecord(lastRecord,newRecord){return lastRecord===newRecord?lastRecord:recordWithOldValue&&recordRepresentsCurrentMutation(lastRecord)?recordWithOldValue:null}function Registration(observer,target,options){this.observer=observer,this.target=target,this.options=options,this.transientObservedNodes=[]}var setImmediate,registrationsTable=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))setImmediate=setTimeout;else if(window.setImmediate)setImmediate=window.setImmediate;else{var setImmediateQueue=[],sentinel=String(Math.random());window.addEventListener("message",function(e){if(e.data===sentinel){var queue=setImmediateQueue;setImmediateQueue=[],queue.forEach(function(func){func()})}}),setImmediate=function(func){setImmediateQueue.push(func),window.postMessage(sentinel,"*")}}var isScheduled=!1,scheduledObservers=[],uidCounter=0;JsMutationObserver.prototype={observe:function(target,options){if(target=wrapIfNeeded(target),!options.childList&&!options.attributes&&!options.characterData||options.attributeOldValue&&!options.attributes||options.attributeFilter&&options.attributeFilter.length&&!options.attributes||options.characterDataOldValue&&!options.characterData)throw new SyntaxError;var registrations=registrationsTable.get(target);registrations||registrationsTable.set(target,registrations=[]);for(var registration,i=0;i<registrations.length;i++)if(registrations[i].observer===this){registration=registrations[i],registration.removeListeners(),registration.options=options;break}registration||(registration=new Registration(this,target,options),registrations.push(registration),this.nodes_.push(target)),registration.addListeners()},disconnect:function(){this.nodes_.forEach(function(node){for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++){var registration=registrations[i];if(registration.observer===this){registration.removeListeners(),registrations.splice(i,1);break}}},this),this.records_=[]},takeRecords:function(){var copyOfRecords=this.records_;return this.records_=[],copyOfRecords}};var currentRecord,recordWithOldValue;Registration.prototype={enqueue:function(record){var records=this.observer.records_,length=records.length;if(records.length>0){var lastRecord=records[length-1],recordToReplaceLast=selectRecord(lastRecord,record);if(recordToReplaceLast)return void(records[length-1]=recordToReplaceLast)}else scheduleCallback(this.observer);records[length]=record},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(node){var options=this.options;options.attributes&&node.addEventListener("DOMAttrModified",this,!0),options.characterData&&node.addEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.addEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(node){var options=this.options;options.attributes&&node.removeEventListener("DOMAttrModified",this,!0),options.characterData&&node.removeEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.removeEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(node){if(node!==this.target){this.addListeners_(node),this.transientObservedNodes.push(node);var registrations=registrationsTable.get(node);registrations||registrationsTable.set(node,registrations=[]),registrations.push(this)}},removeTransientObservers:function(){var transientObservedNodes=this.transientObservedNodes;this.transientObservedNodes=[],transientObservedNodes.forEach(function(node){this.removeListeners_(node);for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++)if(registrations[i]===this){registrations.splice(i,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var name=e.attrName,namespace=e.relatedNode.namespaceURI,target=e.target,record=new getRecord("attributes",target);record.attributeName=name,record.attributeNamespace=namespace;var oldValue=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return!options.attributes||options.attributeFilter&&options.attributeFilter.length&&-1===options.attributeFilter.indexOf(name)&&-1===options.attributeFilter.indexOf(namespace)?void 0:options.attributeOldValue?getRecordWithOldValue(oldValue):record});break;case"DOMCharacterDataModified":var target=e.target,record=getRecord("characterData",target),oldValue=e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return options.characterData?options.characterDataOldValue?getRecordWithOldValue(oldValue):record:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var addedNodes,removedNodes,changedNode=e.target;"DOMNodeInserted"===e.type?(addedNodes=[changedNode],removedNodes=[]):(addedNodes=[],removedNodes=[changedNode]);var previousSibling=changedNode.previousSibling,nextSibling=changedNode.nextSibling,record=getRecord("childList",e.target.parentNode);record.addedNodes=addedNodes,record.removedNodes=removedNodes,record.previousSibling=previousSibling,record.nextSibling=nextSibling,forEachAncestorAndObserverEnqueueRecord(e.relatedNode,function(options){return options.childList?record:void 0})}clearRecords()}},global.JsMutationObserver=JsMutationObserver,global.MutationObserver||(global.MutationObserver=JsMutationObserver)}(this),window.CustomElements=window.CustomElements||{flags:{}},function(scope){var flags=scope.flags,modules=[],addModule=function(module){modules.push(module)},initializeModules=function(){modules.forEach(function(module){module(scope)})};scope.addModule=addModule,scope.initializeModules=initializeModules,scope.hasNative=Boolean(document.registerElement),scope.useNative=!flags.register&&scope.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(scope){function forSubtree(node,cb){findAllElements(node,function(e){return cb(e)?!0:void forRoots(e,cb)}),forRoots(node,cb)}function findAllElements(node,find,data){var e=node.firstElementChild;if(!e)for(e=node.firstChild;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;for(;e;)find(e,data)!==!0&&findAllElements(e,find,data),e=e.nextElementSibling;return null}function forRoots(node,cb){for(var root=node.shadowRoot;root;)forSubtree(root,cb),root=root.olderShadowRoot}function forDocumentTree(doc,cb){_forDocumentTree(doc,cb,[])}function _forDocumentTree(doc,cb,processingDocuments){if(doc=wrap(doc),!(processingDocuments.indexOf(doc)>=0)){processingDocuments.push(doc);for(var n,imports=doc.querySelectorAll("link[rel="+IMPORT_LINK_TYPE+"]"),i=0,l=imports.length;l>i&&(n=imports[i]);i++)n["import"]&&_forDocumentTree(n["import"],cb,processingDocuments);cb(doc)}}var IMPORT_LINK_TYPE=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";scope.forDocumentTree=forDocumentTree,scope.forSubtree=forSubtree}),window.CustomElements.addModule(function(scope){function addedNode(node){return added(node)||addedSubtree(node)}function added(node){return scope.upgrade(node)?!0:void attached(node)}function addedSubtree(node){forSubtree(node,function(e){return added(e)?!0:void 0})}function attachedNode(node){attached(node),inDocument(node)&&forSubtree(node,function(e){attached(e)})}function deferMutation(fn){pendingMutations.push(fn),isPendingMutations||(isPendingMutations=!0,setTimeout(takeMutations))}function takeMutations(){isPendingMutations=!1;for(var p,$p=pendingMutations,i=0,l=$p.length;l>i&&(p=$p[i]);i++)p();pendingMutations=[]}function attached(element){hasPolyfillMutations?deferMutation(function(){_attached(element)}):_attached(element)}function _attached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&!element.__attached&&inDocument(element)&&(element.__attached=!0,element.attachedCallback&&element.attachedCallback())}function detachedNode(node){detached(node),forSubtree(node,function(e){detached(e)})}function detached(element){hasPolyfillMutations?deferMutation(function(){_detached(element)}):_detached(element)}function _detached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&element.__attached&&!inDocument(element)&&(element.__attached=!1,element.detachedCallback&&element.detachedCallback())}function inDocument(element){for(var p=element,doc=wrap(document);p;){if(p==doc)return!0;p=p.parentNode||p.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&p.host}}function watchShadow(node){if(node.shadowRoot&&!node.shadowRoot.__watched){flags.dom&&console.log("watching shadow-root for: ",node.localName);for(var root=node.shadowRoot;root;)observe(root),root=root.olderShadowRoot}}function handler(mutations){if(flags.dom){var mx=mutations[0];if(mx&&"childList"===mx.type&&mx.addedNodes&&mx.addedNodes){for(var d=mx.addedNodes[0];d&&d!==document&&!d.host;)d=d.parentNode;var u=d&&(d.URL||d._URL||d.host&&d.host.localName)||"";u=u.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",mutations.length,u||"")}mutations.forEach(function(mx){"childList"===mx.type&&(forEach(mx.addedNodes,function(n){n.localName&&addedNode(n)}),forEach(mx.removedNodes,function(n){n.localName&&detachedNode(n)}))}),flags.dom&&console.groupEnd()}function takeRecords(node){for(node=wrap(node),node||(node=wrap(document));node.parentNode;)node=node.parentNode;var observer=node.__observer;observer&&(handler(observer.takeRecords()),takeMutations())}function observe(inRoot){if(!inRoot.__observer){var observer=new MutationObserver(handler);observer.observe(inRoot,{childList:!0,subtree:!0}),inRoot.__observer=observer}}function upgradeDocument(doc){doc=wrap(doc),flags.dom&&console.group("upgradeDocument: ",doc.baseURI.split("/").pop()),addedNode(doc),observe(doc),flags.dom&&console.groupEnd()}function upgradeDocumentTree(doc){forDocumentTree(doc,upgradeDocument)}var flags=scope.flags,forSubtree=scope.forSubtree,forDocumentTree=scope.forDocumentTree,hasPolyfillMutations=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;scope.hasPolyfillMutations=hasPolyfillMutations;var isPendingMutations=!1,pendingMutations=[],forEach=Array.prototype.forEach.call.bind(Array.prototype.forEach),originalCreateShadowRoot=Element.prototype.createShadowRoot;originalCreateShadowRoot&&(Element.prototype.createShadowRoot=function(){var root=originalCreateShadowRoot.call(this);return CustomElements.watchShadow(this),root}),scope.watchShadow=watchShadow,scope.upgradeDocumentTree=upgradeDocumentTree,scope.upgradeSubtree=addedSubtree,scope.upgradeAll=addedNode,scope.attachedNode=attachedNode,scope.takeRecords=takeRecords}),window.CustomElements.addModule(function(scope){function upgrade(node){if(!node.__upgraded__&&node.nodeType===Node.ELEMENT_NODE){var is=node.getAttribute("is"),definition=scope.getRegisteredDefinition(is||node.localName);if(definition){if(is&&definition.tag==node.localName)return upgradeWithDefinition(node,definition);if(!is&&!definition["extends"])return upgradeWithDefinition(node,definition)}}}function upgradeWithDefinition(element,definition){return flags.upgrade&&console.group("upgrade:",element.localName),definition.is&&element.setAttribute("is",definition.is),implementPrototype(element,definition),element.__upgraded__=!0,created(element),scope.attachedNode(element),scope.upgradeSubtree(element),flags.upgrade&&console.groupEnd(),element}function implementPrototype(element,definition){Object.__proto__?element.__proto__=definition.prototype:(customMixin(element,definition.prototype,definition["native"]),element.__proto__=definition.prototype)}function customMixin(inTarget,inSrc,inNative){for(var used={},p=inSrc;p!==inNative&&p!==HTMLElement.prototype;){for(var k,keys=Object.getOwnPropertyNames(p),i=0;k=keys[i];i++)used[k]||(Object.defineProperty(inTarget,k,Object.getOwnPropertyDescriptor(p,k)),used[k]=1);p=Object.getPrototypeOf(p)}}function created(element){element.createdCallback&&element.createdCallback()}var flags=scope.flags;scope.upgrade=upgrade,scope.upgradeWithDefinition=upgradeWithDefinition,scope.implementPrototype=implementPrototype}),window.CustomElements.addModule(function(scope){function register(name,options){var definition=options||{};if(!name)throw new Error("document.registerElement: first argument `name` must not be empty");if(name.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(name)+"'.");if(isReservedTag(name))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(name)+"'. The type name is invalid.");if(getRegisteredDefinition(name))throw new Error("DuplicateDefinitionError: a type with name '"+String(name)+"' is already registered");return definition.prototype||(definition.prototype=Object.create(HTMLElement.prototype)),definition.__name=name.toLowerCase(),definition.lifecycle=definition.lifecycle||{},definition.ancestry=ancestry(definition["extends"]),resolveTagName(definition),resolvePrototypeChain(definition),overrideAttributeApi(definition.prototype),registerDefinition(definition.__name,definition),definition.ctor=generateConstructor(definition),definition.ctor.prototype=definition.prototype,definition.prototype.constructor=definition.ctor,scope.ready&&upgradeDocumentTree(document),definition.ctor}function overrideAttributeApi(prototype){if(!prototype.setAttribute._polyfilled){var setAttribute=prototype.setAttribute;prototype.setAttribute=function(name,value){changeAttribute.call(this,name,value,setAttribute)};var removeAttribute=prototype.removeAttribute;prototype.removeAttribute=function(name){changeAttribute.call(this,name,null,removeAttribute)},prototype.setAttribute._polyfilled=!0}}function changeAttribute(name,value,operation){name=name.toLowerCase();var oldValue=this.getAttribute(name);operation.apply(this,arguments);var newValue=this.getAttribute(name);this.attributeChangedCallback&&newValue!==oldValue&&this.attributeChangedCallback(name,oldValue,newValue)}function isReservedTag(name){for(var i=0;i<reservedTagList.length;i++)if(name===reservedTagList[i])return!0}function ancestry(extnds){var extendee=getRegisteredDefinition(extnds);return extendee?ancestry(extendee["extends"]).concat([extendee]):[]}function resolveTagName(definition){for(var a,baseTag=definition["extends"],i=0;a=definition.ancestry[i];i++)baseTag=a.is&&a.tag;definition.tag=baseTag||definition.__name,baseTag&&(definition.is=definition.__name)}function resolvePrototypeChain(definition){if(!Object.__proto__){var nativePrototype=HTMLElement.prototype;if(definition.is){var inst=document.createElement(definition.tag),expectedPrototype=Object.getPrototypeOf(inst);expectedPrototype===definition.prototype&&(nativePrototype=expectedPrototype)}for(var ancestor,proto=definition.prototype;proto&&proto!==nativePrototype;)ancestor=Object.getPrototypeOf(proto),proto.__proto__=ancestor,proto=ancestor;definition["native"]=nativePrototype}}function instantiate(definition){return upgradeWithDefinition(domCreateElement(definition.tag),definition)}function getRegisteredDefinition(name){return name?registry[name.toLowerCase()]:void 0}function registerDefinition(name,definition){registry[name]=definition}function generateConstructor(definition){return function(){return instantiate(definition)}}function createElementNS(namespace,tag,typeExtension){return namespace===HTML_NAMESPACE?createElement(tag,typeExtension):domCreateElementNS(namespace,tag)}function createElement(tag,typeExtension){tag&&(tag=tag.toLowerCase()),typeExtension&&(typeExtension=typeExtension.toLowerCase());var definition=getRegisteredDefinition(typeExtension||tag);if(definition){if(tag==definition.tag&&typeExtension==definition.is)return new definition.ctor;if(!typeExtension&&!definition.is)return new definition.ctor}var element;return typeExtension?(element=createElement(tag),element.setAttribute("is",typeExtension),element):(element=domCreateElement(tag),tag.indexOf("-")>=0&&implementPrototype(element,HTMLElement),element)}function wrapDomMethodToForceUpgrade(obj,methodName){var orig=obj[methodName];obj[methodName]=function(){var n=orig.apply(this,arguments);return upgradeAll(n),n}}var isInstance,isIE11OrOlder=scope.isIE11OrOlder,upgradeDocumentTree=scope.upgradeDocumentTree,upgradeAll=scope.upgradeAll,upgradeWithDefinition=scope.upgradeWithDefinition,implementPrototype=scope.implementPrototype,useNative=scope.useNative,reservedTagList=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],registry={},HTML_NAMESPACE="http://www.w3.org/1999/xhtml",domCreateElement=document.createElement.bind(document),domCreateElementNS=document.createElementNS.bind(document);isInstance=Object.__proto__||useNative?function(obj,base){return obj instanceof base}:function(obj,ctor){for(var p=obj;p;){if(p===ctor.prototype)return!0;p=p.__proto__}return!1},wrapDomMethodToForceUpgrade(Node.prototype,"cloneNode"),wrapDomMethodToForceUpgrade(document,"importNode"),isIE11OrOlder&&!function(){var importNode=document.importNode;document.importNode=function(){var n=importNode.apply(document,arguments);if(n.nodeType==n.DOCUMENT_FRAGMENT_NODE){var f=document.createDocumentFragment();return f.appendChild(n),f}return n}}(),document.registerElement=register,document.createElement=createElement,document.createElementNS=createElementNS,scope.registry=registry,scope["instanceof"]=isInstance,scope.reservedTagList=reservedTagList,scope.getRegisteredDefinition=getRegisteredDefinition,document.register=document.registerElement}),function(scope){function bootstrap(){upgradeDocumentTree(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(elt){upgradeDocumentTree(wrap(elt["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var useNative=scope.useNative,initializeModules=scope.initializeModules,isIE11OrOlder=/Trident/.test(navigator.userAgent);if(useNative){var nop=function(){};scope.watchShadow=nop,scope.upgrade=nop,scope.upgradeAll=nop,scope.upgradeDocumentTree=nop,scope.upgradeSubtree=nop,scope.takeRecords=nop,scope["instanceof"]=function(obj,base){return obj instanceof base}}else initializeModules();var upgradeDocumentTree=scope.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(node){return node}),isIE11OrOlder&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(inType,params){params=params||{};var e=document.createEvent("CustomEvent");return e.initCustomEvent(inType,Boolean(params.bubbles),Boolean(params.cancelable),params.detail),e},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||scope.flags.eager)bootstrap();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var loadEvent=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(loadEvent,bootstrap)}else bootstrap();scope.isIE11OrOlder=isIE11OrOlder}(window.CustomElements),window.CustomEvent||!function(){var CustomEvent;CustomEvent=function(event,params){var evt;return params=params||{bubbles:!1,cancelable:!1,detail:void 0},evt=document.createEvent("CustomEvent"),evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail),evt},CustomEvent.prototype=window.Event.prototype,window.CustomEvent=CustomEvent}(),function(){"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),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}}(),"document"in self&&("classList"in document.createElement("_")&&(!document.createElementNS||"classList"in document.createElementNS("http://www.w3.org/2000/svg","g"))?!function(){"use strict";var testElement=document.createElement("_");if(testElement.classList.add("c1","c2"),!testElement.classList.contains("c2")){var createMethod=function(method){var original=DOMTokenList.prototype[method];DOMTokenList.prototype[method]=function(token){var i,len=arguments.length;for(i=0;len>i;i++)token=arguments[i],original.call(this,token)}};createMethod("add"),createMethod("remove")}if(testElement.classList.toggle("c3",!1),testElement.classList.contains("c3")){var _toggle=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(token,force){return 1 in arguments&&!this.contains(token)==!force?force:_toggle.call(this,token)}}testElement=null}():!function(view){"use strict";if("Element"in view){var classListProp="classList",protoProp="prototype",elemCtrProto=view.Element[protoProp],objCtr=Object,strTrim=String[protoProp].trim||function(){return this.replace(/^\s+|\s+$/g,"")},arrIndexOf=Array[protoProp].indexOf||function(item){for(var i=0,len=this.length;len>i;i++)if(i in this&&this[i]===item)return i;return-1},DOMEx=function(type,message){this.name=type,this.code=DOMException[type],this.message=message},checkTokenAndGetIndex=function(classList,token){if(""===token)throw new DOMEx("SYNTAX_ERR","An invalid or illegal string was specified");if(/\s/.test(token))throw new DOMEx("INVALID_CHARACTER_ERR","String contains an invalid character");return arrIndexOf.call(classList,token)},ClassList=function(elem){for(var trimmedClasses=strTrim.call(elem.getAttribute("class")||""),classes=trimmedClasses?trimmedClasses.split(/\s+/):[],i=0,len=classes.length;len>i;i++)this.push(classes[i]);this._updateClassName=function(){elem.setAttribute("class",this.toString())}},classListProto=ClassList[protoProp]=[],classListGetter=function(){return new ClassList(this)};if(DOMEx[protoProp]=Error[protoProp],classListProto.item=function(i){return this[i]||null},classListProto.contains=function(token){return token+="",-1!==checkTokenAndGetIndex(this,token)},classListProto.add=function(){var token,tokens=arguments,i=0,l=tokens.length,updated=!1;do token=tokens[i]+"",-1===checkTokenAndGetIndex(this,token)&&(this.push(token),updated=!0);while(++i<l);updated&&this._updateClassName()},classListProto.remove=function(){var token,index,tokens=arguments,i=0,l=tokens.length,updated=!1;do for(token=tokens[i]+"",index=checkTokenAndGetIndex(this,token);-1!==index;)this.splice(index,1),updated=!0,index=checkTokenAndGetIndex(this,token);while(++i<l);updated&&this._updateClassName()},classListProto.toggle=function(token,force){token+="";var result=this.contains(token),method=result?force!==!0&&"remove":force!==!1&&"add";return method&&this[method](token),force===!0||force===!1?force:!result},classListProto.toString=function(){return this.join(" ")},objCtr.defineProperty){var classListPropDesc={get:classListGetter,enumerable:!0,configurable:!0};try{objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc)}catch(ex){-2146823252===ex.number&&(classListPropDesc.enumerable=!1,objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc))}}else objCtr[protoProp].__defineGetter__&&elemCtrProto.__defineGetter__(classListProp,classListGetter)}}(self)),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.timeStamp-this.lastClickTime>-1&&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&&event.timeStamp-this.lastClickTime>-1)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)},window.FastClick=FastClick}();var 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),!function(e,t,n){function r(e,t){return typeof e===t}function o(){var e,t,n,o,i,s,a;for(var l in S)if(S.hasOwnProperty(l)){if(e=[],t=S[l],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;n<t.options.aliases.length;n++)e.push(t.options.aliases[n].toLowerCase());for(o=r(t.fn,"function")?t.fn():t.fn,i=0;i<e.length;i++)s=e[i],a=s.split("."),1===a.length?Modernizr[a[0]]=o:(!Modernizr[a[0]]||Modernizr[a[0]]instanceof Boolean||(Modernizr[a[0]]=new Boolean(Modernizr[a[0]])),Modernizr[a[0]][a[1]]=o),C.push((o?"":"no-")+a.join("-"))}}function i(e){var t=w.className,n=Modernizr._config.classPrefix||"";if(_&&(t=t.baseVal),Modernizr._config.enableJSClass){var r=new RegExp("(^|\\s)"+n+"no-js(\\s|$)");t=t.replace(r,"$1"+n+"js$2")}Modernizr._config.enableClasses&&(t+=" "+n+e.join(" "+n),_?w.className.baseVal=t:w.className=t)}function s(e,t){if("object"==typeof e)for(var n in e)N(e,n)&&s(n,e[n]);else{e=e.toLowerCase();var r=e.split("."),o=Modernizr[r[0]];if(2==r.length&&(o=o[r[1]]),"undefined"!=typeof o)return Modernizr;t="function"==typeof t?t():t,1==r.length?Modernizr[r[0]]=t:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=t),i([(t&&0!=t?"":"no-")+r.join("-")]),Modernizr._trigger(e,t)}return Modernizr}function a(){return"function"!=typeof t.createElement?t.createElement(arguments[0]):_?t.createElementNS.call(t,"http://www.w3.org/2000/svg",arguments[0]):t.createElement.apply(t,arguments)}function l(e,t){return!!~(""+e).indexOf(t)}function u(){var e=t.body;return e||(e=a(_?"svg":"body"),e.fake=!0),e}function f(e,n,r,o){var i,s,l,f,c="modernizr",d=a("div"),p=u();if(parseInt(r,10))for(;r--;)l=a("div"),l.id=o?o[r]:c+(r+1),d.appendChild(l);return i=a("style"),i.type="text/css",i.id="s"+c,(p.fake?p:d).appendChild(i),p.appendChild(d),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(t.createTextNode(e)),d.id=c,p.fake&&(p.style.background="",p.style.overflow="hidden",f=w.style.overflow,w.style.overflow="hidden",w.appendChild(p)),s=n(d,e),p.fake?(p.parentNode.removeChild(p),w.style.overflow=f,w.offsetHeight):d.parentNode.removeChild(d),!!s}function c(e){return e.replace(/([a-z])-([a-z])/g,function(e,t,n){return t+n.toUpperCase()}).replace(/^-/,"")}function d(e,t){return function(){return e.apply(t,arguments)}}function p(e,t,n){var o;for(var i in e)if(e[i]in t)return n===!1?e[i]:(o=t[e[i]],r(o,"function")?d(o,n||t):o);return!1}function m(e){return e.replace(/([A-Z])/g,function(e,t){return"-"+t.toLowerCase()}).replace(/^ms-/,"-ms-")}function h(t,r){var o=t.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;)if(e.CSS.supports(m(t[o]),r))return!0;return!1}if("CSSSupportsRule"in e){for(var i=[];o--;)i.push("("+m(t[o])+":"+r+")");return i=i.join(" or "),f("@supports ("+i+") { #modernizr { position: absolute; } }",function(e){return"absolute"==getComputedStyle(e,null).position})}return n}function g(e,t,o,i){function s(){f&&(delete L.style,delete L.modElem)}if(i=r(i,"undefined")?!1:i,!r(o,"undefined")){var u=h(e,o);if(!r(u,"undefined"))return u}for(var f,d,p,m,g,v=["modernizr","tspan"];!L.style;)f=!0,L.modElem=a(v.shift()),L.style=L.modElem.style;for(p=e.length,d=0;p>d;d++)if(m=e[d],g=L.style[m],l(m,"-")&&(m=c(m)),L.style[m]!==n){if(i||r(o,"undefined"))return s(),"pfx"==t?m:!0;try{L.style[m]=o}catch(y){}if(L.style[m]!=g)return s(),"pfx"==t?m:!0}return s(),!1}function v(e,t,n,o,i){var s=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+k.join(s+" ")+s).split(" ");return r(t,"string")||r(t,"undefined")?g(a,t,o,i):(a=(e+" "+T.join(s+" ")+s).split(" "),p(a,t,n))}function y(e,t,r){return v(e,n,n,t,r)}var C=[],S=[],x={_version:"3.1.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function(e,t,n){S.push({name:e,fn:t,options:n})},addAsyncTest:function(e){S.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=x,Modernizr=new Modernizr,Modernizr.addTest("svg",!!t.createElementNS&&!!t.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect);var b=x._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):[];x._prefixes=b;var w=t.documentElement,_="svg"===w.nodeName.toLowerCase();_||!function(e,t){function n(e,t){var n=e.createElement("p"),r=e.getElementsByTagName("head")[0]||e.documentElement;return n.innerHTML="x<style>"+t+"</style>",r.insertBefore(n.lastChild,r.firstChild)}function r(){var e=C.elements;return"string"==typeof e?e.split(" "):e}function o(e,t){var n=C.elements;"string"!=typeof n&&(n=n.join(" ")),"string"!=typeof e&&(e=e.join(" ")),C.elements=n+" "+e,u(t)}function i(e){var t=y[e[g]];return t||(t={},v++,e[g]=v,y[v]=t),t}function s(e,n,r){if(n||(n=t),c)return n.createElement(e);r||(r=i(n));var o;return o=r.cache[e]?r.cache[e].cloneNode():h.test(e)?(r.cache[e]=r.createElem(e)).cloneNode():r.createElem(e),!o.canHaveChildren||m.test(e)||o.tagUrn?o:r.frag.appendChild(o)}function a(e,n){if(e||(e=t),c)return e.createDocumentFragment();n=n||i(e);for(var o=n.frag.cloneNode(),s=0,a=r(),l=a.length;l>s;s++)o.createElement(a[s]);return o}function l(e,t){t.cache||(t.cache={},t.createElem=e.createElement,t.createFrag=e.createDocumentFragment,t.frag=t.createFrag()),e.createElement=function(n){return C.shivMethods?s(n,e,t):t.createElem(n)},e.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+r().join().replace(/[\w\-:]+/g,function(e){return t.createElem(e),t.frag.createElement(e),'c("'+e+'")'})+");return n}")(C,t.frag)}function u(e){e||(e=t);var r=i(e);return!C.shivCSS||f||r.hasCSS||(r.hasCSS=!!n(e,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),c||l(e,r),e}var f,c,d="3.7.3",p=e.html5||{},m=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,h=/^(?: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,g="_html5shiv",v=0,y={};!function(){try{var e=t.createElement("a");e.innerHTML="<xyz></xyz>",f="hidden"in e,c=1==e.childNodes.length||function(){t.createElement("a");var e=t.createDocumentFragment();return"undefined"==typeof e.cloneNode||"undefined"==typeof e.createDocumentFragment||"undefined"==typeof e.createElement}()}catch(n){f=!0,c=!0}}();var C={elements:p.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:d,shivCSS:p.shivCSS!==!1,supportsUnknownElements:c,shivMethods:p.shivMethods!==!1,type:"default",shivDocument:u,createElement:s,createDocumentFragment:a,addElements:o};e.html5=C,u(t),"object"==typeof module&&module.exports&&(module.exports=C)}("undefined"!=typeof e?e:this,t);var E="Moz O ms Webkit",T=x._config.usePrefixes?E.toLowerCase().split(" "):[];x._domPrefixes=T;var N;!function(){var e={}.hasOwnProperty;N=r(e,"undefined")||r(e.call,"undefined")?function(e,t){return t in e&&r(e.constructor.prototype[t],"undefined")}:function(t,n){return e.call(t,n)}}(),x._l={},x.on=function(e,t){this._l[e]||(this._l[e]=[]),this._l[e].push(t),Modernizr.hasOwnProperty(e)&&setTimeout(function(){Modernizr._trigger(e,Modernizr[e])},0)},x._trigger=function(e,t){if(this._l[e]){var n=this._l[e];setTimeout(function(){var e,r;for(e=0;e<n.length;e++)(r=n[e])(t)},0),delete this._l[e]}},Modernizr._q.push(function(){x.addTest=s}),Modernizr.addTest("canvas",function(){var e=a("canvas");return!(!e.getContext||!e.getContext("2d"))});var P="CSS"in e&&"supports"in e.CSS,j="supportsCSS"in e;Modernizr.addTest("supports",P||j);var k=x._config.usePrefixes?E.split(" "):[];x._cssomPrefixes=k;var z=x.testStyles=f,F={elem:a("modernizr")};Modernizr._q.push(function(){delete F.elem});var L={style:F.elem.style};Modernizr._q.unshift(function(){delete L.style}),x.testProp=function(e,t,r){return g([e],n,t,r)},x.testAllProps=v,x.testAllProps=y,Modernizr.addTest("borderradius",y("borderRadius","0px",!0)),Modernizr.addTest("boxshadow",y("boxShadow","1px 1px",!0)),Modernizr.addTest("cssanimations",y("animationName","a",!0)),Modernizr.addTest("csstransforms",function(){return-1===navigator.userAgent.indexOf("Android 2.")&&y("transform","scale(1)",!0)}),Modernizr.addTest("csstransforms3d",function(){var e=!!y("perspective","1px",!0),t=Modernizr._config.usePrefixes;if(e&&(!t||"webkitPerspective"in w.style)){var n;Modernizr.supports?n="@supports (perspective: 1px)":(n="@media (transform-3d)",t&&(n+=",(-webkit-transform-3d)")),n+="{#modernizr{left:9px;position:absolute;height:5px;margin:0;padding:0;border:0}}",z(n,function(t){e=9===t.offsetLeft&&5===t.offsetHeight})}return e}),Modernizr.addTest("csstransitions",y("transition","all",!0)),o(),i(C),delete x.addTest,delete x.addAsyncTest;for(var A=0;A<Modernizr._q.length;A++)Modernizr._q[A]();e.Modernizr=Modernizr}(window,document),!function n(t,e,r){function o(u,f){if(!e[u]){if(!t[u]){var c="function"==typeof require&&require;if(!f&&c)return c(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var l=e[u]={exports:{}};t[u][0].call(l.exports,function(n){var e=t[u][1][n];return o(e?e:n)},l,l.exports,n,t,e,r)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(n,t,e){"use strict";function r(){}function o(n){try{return n.then}catch(t){return d=t,w}}function i(n,t){try{return n(t)}catch(e){return d=e,w}}function u(n,t,e){try{n(t,e)}catch(r){return d=r,w}}function f(n){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof n)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],n!==r&&v(n,this)}function c(n,t,e){return new n.constructor(function(o,i){var u=new f(r);u.then(o,i),s(n,new p(t,e,u))})}function s(n,t){for(;3===n._37;)n=n._12;return 0===n._37?void n._59.push(t):void y(function(){var e=1===n._37?t.onFulfilled:t.onRejected;if(null===e)return void(1===n._37?l(t.promise,n._12):a(t.promise,n._12));var r=i(e,n._12);r===w?a(t.promise,d):l(t.promise,r)})}function l(n,t){if(t===n)return a(n,new TypeError("A promise cannot be resolved with itself."));if(t&&("object"==typeof t||"function"==typeof t)){var e=o(t);if(e===w)return a(n,d);if(e===n.then&&t instanceof f)return n._37=3,n._12=t,void h(n);if("function"==typeof e)return void v(e.bind(t),n)}n._37=1,n._12=t,h(n)}function a(n,t){n._37=2,n._12=t,h(n)}function h(n){for(var t=0;t<n._59.length;t++)s(n,n._59[t]);n._59=null}function p(n,t,e){this.onFulfilled="function"==typeof n?n:null,this.onRejected="function"==typeof t?t:null,this.promise=e}function v(n,t){var e=!1,r=u(n,function(n){e||(e=!0,l(t,n))},function(n){e||(e=!0,a(t,n))});e||r!==w||(e=!0,a(t,d))}var y=n("asap/raw"),d=null,w={};t.exports=f,f._99=r,f.prototype.then=function(n,t){if(this.constructor!==f)return c(this,n,t);var e=new f(r);return s(this,new p(n,t,e)),e}},{"asap/raw":4}],2:[function(n,t,e){"use strict";function r(n){var t=new o(o._99);return t._37=1,t._12=n,t}var o=n("./core.js");t.exports=o;var i=r(!0),u=r(!1),f=r(null),c=r(void 0),s=r(0),l=r("");o.resolve=function(n){if(n instanceof o)return n;if(null===n)return f;if(void 0===n)return c;if(n===!0)return i;if(n===!1)return u;if(0===n)return s;if(""===n)return l;if("object"==typeof n||"function"==typeof n)try{var t=n.then;if("function"==typeof t)return new o(t.bind(n))}catch(e){return new o(function(n,t){t(e)})}return r(n)},o.all=function(n){var t=Array.prototype.slice.call(n);return new o(function(n,e){function r(u,f){if(f&&("object"==typeof f||"function"==typeof f)){if(f instanceof o&&f.then===o.prototype.then){for(;3===f._37;)f=f._12;return 1===f._37?r(u,f._12):(2===f._37&&e(f._12),void f.then(function(n){r(u,n)},e))}var c=f.then;if("function"==typeof c){var s=new o(c.bind(f));return void s.then(function(n){r(u,n)},e)}}t[u]=f,0===--i&&n(t)}if(0===t.length)return n([]);for(var i=t.length,u=0;u<t.length;u++)r(u,t[u])})},o.reject=function(n){return new o(function(t,e){e(n)})},o.race=function(n){return new o(function(t,e){n.forEach(function(n){o.resolve(n).then(t,e)})})},o.prototype["catch"]=function(n){return this.then(null,n)}},{"./core.js":1}],3:[function(n,t,e){"use strict";function r(){if(c.length)throw c.shift()}function o(n){var t;t=f.length?f.pop():new i,t.task=n,u(t)}function i(){this.task=null}var u=n("./raw"),f=[],c=[],s=u.makeRequestCallFromTimer(r);t.exports=o,i.prototype.call=function(){try{this.task.call()}catch(n){o.onerror?o.onerror(n):(c.push(n),s())}finally{this.task=null,f[f.length]=this}}},{"./raw":4}],4:[function(n,t,e){(function(n){"use strict";function e(n){f.length||(u(),c=!0),f[f.length]=n}function r(){for(;s<f.length;){var n=s;if(s+=1,f[n].call(),s>l){for(var t=0,e=f.length-s;e>t;t++)f[t]=f[t+s];f.length-=s,s=0}}f.length=0,s=0,c=!1}function o(n){var t=1,e=new a(n),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function i(n){return function(){function t(){clearTimeout(e),clearInterval(r),n()}var e=setTimeout(t,0),r=setInterval(t,50)}}t.exports=e;var u,f=[],c=!1,s=0,l=1024,a=n.MutationObserver||n.WebKitMutationObserver;u="function"==typeof a?o(r):i(r),e.requestFlush=u,e.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(n,t,e){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(n,t){var e=arguments.length?this.then.apply(this,arguments):this;e.then(null,function(n){setTimeout(function(){throw n},0)})})},{}],6:[function(n,t,e){n("asap"),"undefined"==typeof Promise&&(Promise=n("./lib/core.js"),n("./lib/es6-extensions.js")),n("./polyfill-done.js")},{"./lib/core.js":1,"./lib/es6-extensions.js":2,"./polyfill-done.js":5,asap:3}]},{},[6]),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}}(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}(),window.animit=function(){"use strict";var TIMEOUT_RATIO=1.4,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=[]};Animit.prototype={transitionQueue:void 0,elements: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=transition.css?new Animit.Transition(transition):new Animit.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 seconds>0&&this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},saveStyle:function(){return this.transitionQueue.push(function(done){this.elements.forEach(function(element,index){for(var css=this.lastStyleAttributeDict[index]={},i=0;i<element.style.length;i++)css[element.style[i]]=element.style[element.style[i]]}.bind(this)),done()}.bind(this)),this},restoreStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[transitionName]="none";var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var i=0,name="";i<element.style.length;i++)name=element.style[i],"undefined"==typeof css[element.style[i]]&&(css[element.style[i]]="");Object.keys(css).forEach(function(key){element.style[key]=css[key]})})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');var transitionName=util.transitionPropertyName;if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear");this.transitionQueue.push(function(done){var elements=this.elements,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),clearTransition(),done()}),timeoutId=setTimeout(function(){removeListeners(),clearTransition(),done()},1e3*options.duration*TIMEOUT_RATIO);elements.forEach(function(element,index){var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var name,i=0,len=element.style.length;len>i;i++)name=element.style[i],void 0===css[name]&&(css[name]="");element.style[transitionName]=transitionValue,Object.keys(css).forEach(function(key){key!==transitionName&&(element.style[key]=css[key])}),element.style[transitionName]=transitionValue});var clearTransition=function(){elements.forEach(function(element){element.style[transitionName]=""})}})}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.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];if(util.hasCssProperty(name))return void(result[name]=value);var prefixed=util.vendorPrefix+util.capitalize(name);util.hasCssProperty(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*TIMEOUT_RATIO,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element){element.style[util.transitionPropertyName]=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){element.style[util.transitionPropertyName]="",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length>0?util.forceLayoutAtOnce(elements,function(){util.batchAnimationFrame(callback)}):util.batchAnimationFrame(callback)}:void 0}};var util={};return util.capitalize=function(str){return str.charAt(0).toUpperCase()+str.slice(1)},util.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(", ")},util.onceOnTransitionEnd=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,!1)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},util._transitionEndEvents=function(){return"ontransitionend"in window?["transitionend"]:"onwebkittransitionend"in window?["webkitTransitionEnd"]:"webkit"===util.vendorPrefix||"o"===util.vendorPrefix||"moz"===util.vendorPrefix||"ms"===util.vendorPrefix?[util.vendorPrefix+"TransitionEnd","transitionend"]:[]}(),util._cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0);return dict}(),util.hasCssProperty=function(name){return name in util._cssPropertyDict},util.vendorPrefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1]; return pre}(),util.forceLayoutAtOnce=function(elements,callback){this.batchImmediate(function(){elements.forEach(function(element){element.offsetHeight}),callback()})},util.batchImmediate=function(){var callbacks=[];return function(callback){0===callbacks.length&&setImmediate(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.batchAnimationFrame=function(){var callbacks=[],raf=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,1e3/60)};return function(callback){0===callbacks.length&&raf(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.transitionPropertyName=function(){if(util.hasCssProperty("transition"))return"transition";if(util.hasCssProperty(util.vendorPrefix+"Transition"))return util.vendorPrefix+"Transition";throw new Error("Invalid state")}(),Animit}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();window.DoorLock=function(){"use strict";var generateId=function(){var i=0;return function(){return i++}}(),DoorLock=function(){function DoorLock(options){_classCallCheck(this,DoorLock),options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}}return _createClass(DoorLock,[{key:"lock",value:function(){var _this=this,unlock=function unlock(){_this._unlock(unlock)};return unlock.id=generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock}},{key:"_unlock",value: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()}},{key:"_tryToFreeWaitList",value:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()}},{key:"waitUnlock",value:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()}},{key:"isLocked",value:function(){return this._lockList.length>0}}]),DoorLock}();return DoorLock}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util={_ready:!1,_domContentLoaded:!1,_onDOMContentLoaded:function(){util._domContentLoaded=!0,ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0},addBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};window.addEventListener("DOMContentLoaded",function(){return util._onDOMContentLoaded()},!1);var HandlerRepository={_store:{},_genId:function(){var i=0;return function(){return i++}}(),set:function(element,handler){element.dataset.deviceBackButtonHandlerId&&this.remove(element);var id=element.dataset.deviceBackButtonHandlerId=HandlerRepository._genId();this._store[id]=handler},remove:function(element){element.dataset.deviceBackButtonHandlerId&&(delete this._store[element.dataset.deviceBackButtonHandlerId],delete element.dataset.deviceBackButtonHandlerId)},get:function(element){if(!element.dataset.deviceBackButtonHandlerId)return void 0;var id=element.dataset.deviceBackButtonHandlerId;if(!this._store[id])throw new Error;return this._store[id]},has:function(element){var id=element.dataset.deviceBackButtonHandlerId;return!!this._store[id]}},DeviceBackButtonDispatcher=function(){function DeviceBackButtonDispatcher(){_classCallCheck(this,DeviceBackButtonDispatcher),this._isEnabled=!1,this._boundCallback=this._callback.bind(this)}return _createClass(DeviceBackButtonDispatcher,[{key:"enable",value:function(){this._isEnabled||(util.addBackButtonListener(this._boundCallback),this._isEnabled=!0)}},{key:"disable",value:function(){this._isEnabled&&(util.removeBackButtonListener(this._boundCallback),this._isEnabled=!1)}},{key:"fireDeviceBackButtonEvent",value:function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)}},{key:"_callback",value:function(){this._dispatchDeviceBackButtonEvent()}},{key:"createHandler",value:function(element,callback){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){HandlerRepository.remove(element)},setListener:function(callback){this._callback=callback},enable:function(){HandlerRepository.set(element,this)},isEnabled:function(){return HandlerRepository.get(element)===this},destroy:function(){HandlerRepository.remove(element),this._callback=this._element=null}};return handler.enable(),handler}},{key:"_dispatchDeviceBackButtonEvent",value:function(){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parentNode;parent;){if(handler=HandlerRepository.get(parent))return handler._callback(createEvent(parent));parent=parent.parentNode}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=HandlerRepository.get(element);handler._callback(createEvent(element))}},{key:"_captureTree",value:function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],arrayOf(element.children).map(function(childElement){if("none"===childElement.style.display)return[];if(0===childElement.children.length&&!HandlerRepository.has(childElement))return[];var result=createTree(childElement);return 0!==result.children.length||HandlerRepository.has(result.element)?[result]:[]}))}}function arrayOf(target){for(var result=[],i=0;i<target.length;i++)result.push(target[i]);return result}return createTree(document.body)}},{key:"_findHandlerLeafElement",value:function(tree){function find(_x){for(var _again=!0;_again;){var node=_x;if(_again=!1,0===node.children.length)return node.element;if(1!==node.children.length)return node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(!left)return right;var leftZ=parseInt(window.getComputedStyle(left,"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right,"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null);_x=node.children[0],_again=!0}}return find(tree)}}]),DeviceBackButtonDispatcher}();ons._deviceBackButtonDispatcher=new DeviceBackButtonDispatcher,window.addEventListener("DOMContentLoaded",function(){ons._deviceBackButtonDispatcher.enable()})}(window.ons=window.ons||{}),function(ons){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}ons._readyLock=new DoorLock,ons._config={autoStatusBarFill:!0,animationsDisabled:!1},waitDeviceReady(),ons.isReady=function(){return!ons._readyLock.isLocked()},ons.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)},ons.ready=function(callback){ons.isReady()?callback():ons._readyLock.waitUnlock(callback)},ons.setDefaultDeviceBackButtonListener=function(listener){ons._defaultDeviceBackButtonHandler.setListener(listener)},ons.disableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.disable()},ons.enableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.enable()},ons.enableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!0},ons.disableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!1},ons.disableAnimations=function(){ons._config.animationsDisabled=!0},ons.enableAnimations=function(){ons._config.animationsDisabled=!1},ons._createPopoverOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-popover/gi)?"<div>"+html+"</div>":"<ons-popover>"+html+"</ons-popover>";var div=ons._util.createElement("<div>"+html+"</div>"),popover=div.querySelector("ons-popover");return CustomElements.upgrade(popover),document.body.appendChild(popover),options.link instanceof Function&&options.link(popover),popover})},ons.createPopover=ons._createPopoverOriginal,ons._createDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-dialog/gi)?"<div>"+html+"</div>":"<ons-dialog>"+html+"</ons-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),dialog=div.querySelector("ons-dialog");return CustomElements.upgrade(dialog),document.body.appendChild(dialog),options.link instanceof Function&&options.link(dialog),dialog})},ons.createDialog=ons._createDialogOriginal,ons._createAlertDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-alert-dialog/gi)?"<div>"+html+"</div>":"<ons-alert-dialog>"+html+"</ons-alert-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),alertDialog=div.querySelector("ons-alert-dialog");return CustomElements.upgrade(alertDialog),document.body.appendChild(alertDialog),options.link instanceof Function&&options.link(alertDialog),alertDialog})},ons.createAlertDialog=ons._createAlertDialogOriginal,ons._resolveLoadingPlaceholderOriginal=function(page,link){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));if(!(elements.length>0))throw new Error("No ons-loading-placeholder exists.");elements.filter(function(element){return!element.getAttribute("page")}).forEach(function(element){element.setAttribute("ons-loading-placeholder",page),ons._resolveLoadingPlaceholder(element,page,link)})},ons.resolveLoadingPlaceholder=ons._resolveLoadingPlaceholderOriginal,ons._setupLoadingPlaceHolders=function(){ons.ready(function(){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));elements.forEach(function(element){var page=element.getAttribute("ons-loading-placeholder");"string"==typeof page&&ons._resolveLoadingPlaceholder(element,page)})})},ons._resolveLoadingPlaceholder=function(element,page,link){link=link||function(element,done){done()},ons._internal.getPageHTMLAsync(page).then(function(html){for(;element.firstChild;)element.removeChild(element.firstChild);var contentElement=ons._util.createElement("<div>"+html+"</div>");contentElement.style.display="none",element.appendChild(contentElement),link(contentElement,function(){contentElement.style.display=""})})["catch"](function(error){throw new Error("Unabled to resolve placeholder: "+error)})}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util=ons._util||{};util.findChild=function(element,query){for(var match=query instanceof Function?query:"."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},i=0;i<element.children.length;i++){var node=element.children[i];if(match(node))return node}return null},util.findParent=function(element,query){for(var match="."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},parent=element.parentNode;;){if(!parent)return null;if(match(parent))return parent;parent=parent.parentNode}},util.isAttached=function(element){for(;document.documentElement!==element;){if(!element)return!1;element=element.parentNode}return!0},util.hasAnyComponentAsParent=function(element){for(;element&&document.documentElement!==element;)if(element=element.parentNode,element&&element.nodeName.toLowerCase().match(/(ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/))return!0;return!1},util.propagateAction=function(element,action){for(var i=0;i<element.childNodes.length;i++){var child=element.childNodes[i];child[action]?child[action]():ons._util.propagateAction(child,action)}},util.createElement=function(html){var wrapper=document.createElement("div");if(wrapper.innerHTML=html,wrapper.children.length>1)throw new Error('"html" must be one wrapper element.');return wrapper.children[0]},util.createFragment=function(html){var wrapper=document.createElement("div");wrapper.innerHTML=html;var fragment=document.createDocumentFragment();return wrapper.firstChild&&fragment.appendChild(wrapper.firstChild),fragment},util.extend=function(dst){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_len>_key;_key++)args[_key-1]=arguments[_key];for(var i=0;i<args.length;i++)if(args[i])for(var keys=Object.keys(args[i]),j=0;j<keys.length;j++){var key=keys[j];dst[key]=args[i][key]}return dst},util.arrayFrom=function(arrayLike){for(var result=[],i=0;i<arrayLike.length;i++)result.push(arrayLike[i]);return result},util.parseJSONObjectSafely=function(jsonString){var failSafe=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];try{var result=JSON.parse(""+jsonString);if("object"==typeof result&&null!==result)return result}catch(e){return failSafe}return failSafe},util.triggerElementEvent=function(target,eventName){var detail=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],event=new CustomEvent(eventName,{bubbles:!0,cancelable:!0,detail:detail});return Object.keys(detail).forEach(function(key){event[key]=detail[key]}),target.dispatchEvent(event),event},util.hasModifier=function(target,modifierName){if(!target.hasAttribute("modifier"))return!1;for(var modifiers=target.getAttribute("modifier").trim().split(/\s+/),i=0;i<modifiers.length;i++)if(modifiers[i]===modifierName)return!0;return!1}}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModalAnimator=function(){function ModalAnimator(options){_classCallCheck(this,ModalAnimator),this.delay=0,this.duration=.2,options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration,this.delay=void 0!==options.delay?options.delay:this.delay}return _createClass(ModalAnimator,[{key:"show",value:function(modal,callback){callback()}},{key:"hide",value:function(modal,callback){callback()}}]),ModalAnimator}();ons._internal=ons._internal||{},ons._internal.ModalAnimator=ModalAnimator}(window.ons=window.ons||{});var _get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var SplitterAnimator=(ons._util,function(){function SplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,SplitterAnimator),options=ons._util.extend({timing:"linear",duration:"0.3",delay:"0"},options||{}),this._timing=options.timing,this._duration=options.duration,this._delay=options.delay}return _createClass(SplitterAnimator,[{key:"layoutOnOpen",value:function(){}},{key:"layoutOnClose",value:function(){}},{key:"translate",value:function(distance){}},{key:"open",value:function(done){done()}},{key:"close",value:function(done){done()}},{key:"activate",value:function(contentElement,sideElement,maskElement){}},{key:"inactivate",value:function(){}},{key:"isActivated",value:function(){throw new Error}}]),SplitterAnimator}()),OverlaySplitterAnimator=function(_SplitterAnimator){function OverlaySplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,OverlaySplitterAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .1, 1)",duration:"0.3",delay:"0"},options||{}),_get(Object.getPrototypeOf(OverlaySplitterAnimator.prototype),"constructor",this).call(this,options)}return _inherits(OverlaySplitterAnimator,_SplitterAnimator),_createClass(OverlaySplitterAnimator,[{key:"isActivated",value:function(){return this._isActivated}},{key:"layoutOnClose",value:function(){animit(this._side).queue({transform:"translateX(0%)",width:this._side._getWidth()}).play(),this._mask.style.display="none"}},{key:"layoutOnOpen",value:function(){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+"100%, 0px, 0px)",width:this._side._getWidth()}).play(),this._mask.style.display="block"}},{key:"activate",value:function(contentElement,sideElement,maskElement){this._isActivated=!0,this._content=contentElement,this._side=sideElement,this._mask=maskElement,this._setupLayout()}},{key:"inactivate",value:function(){this._isActivated=!1,this._clearLayout(),this._content=this._side=this._mask=null}},{key:"translate",value:function(distance){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+distance+"px, 0px, 0px)"}).play()}},{key:"_clearLayout",value:function(){var side=this._side,mask=this._mask;side.style.zIndex="",side.style.right="",side.style.left="",side.style.transform=side.style.webkitTransform="",side.style.transition=side.style.webkitTransition="",side.style.width="",side.style.display="",mask.style.display="none"}},{key:"_setupLayout",value:function(){var side=this._side;side.style.zIndex=3,side.style.display="block",side._isLeftSide()?(side.style.left="auto",side.style.right="100%"):(side.style.left="100%",side.style.right="auto")}},{key:"open",value:function(done){var transform=this._side._isLeftSide()?"translate3d(100%, 0px, 0px)":"translate3d(-100%, 0px, 0px)";animit.runAll(animit(this._side).wait(this._delay).queue({transform:transform},{duration:this._duration,timing:this._timing}).queue(function(callback){callback(),done()}),animit(this._mask).wait(this._delay).queue({display:"block"}).queue({opacity:"1"},{duration:this._duration,timing:"linear"}))}},{key:"close",value:function(done){var _this=this;animit.runAll(animit(this._side).wait(this._delay).queue({transform:"translate3d(0px, 0px, 0px)"},{duration:this._duration,timing:this._timing}).queue(function(callback){_this._side.style.webkitTransition="",done(),callback()}),animit(this._mask).wait(this._delay).queue({opacity:"0"},{duration:this._duration,timing:"linear"}).queue({display:"none"}))}}]),OverlaySplitterAnimator}(SplitterAnimator);ons._internal=ons._internal||{},ons._internal.SplitterAnimator=SplitterAnimator,ons._internal.OverlaySplitterAnimator=OverlaySplitterAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var NavigatorTransitionAnimator=function(){function NavigatorTransitionAnimator(options){_classCallCheck(this,NavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(NavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NavigatorTransitionAnimator}(),NoneNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function NoneNavigatorTransitionAnimator(options){_classCallCheck(this,NoneNavigatorTransitionAnimator),_get(Object.getPrototypeOf(NoneNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(NoneNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(NoneNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NoneNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.NavigatorTransitionAnimator=NavigatorTransitionAnimator,ons._internal.NoneNavigatorTransitionAnimator=NoneNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var PopoverAnimator=function(){function PopoverAnimator(options){_classCallCheck(this,PopoverAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,delay:0},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(PopoverAnimator,[{key:"show",value:function(popover,callback){callback()}},{key:"hide",value:function(popover,callback){callback()}}]),PopoverAnimator}();ons._internal=ons._internal||{},ons._internal.PopoverAnimator=PopoverAnimator}(window.ons=window.ons||{}),function(ons){"use strict";ons.platform={_renderPlatform:null,select:function(platform){ons.platform._renderPlatform=platform.trim().toLowerCase()},isWebView:function(){return ons.isWebView()},isIOS:function(){return ons.platform._renderPlatform?"ios"===ons.platform._renderPlatform:"object"==typeof device?/iOS/i.test(device.platform):/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return ons.platform._renderPlatform?"android"===ons.platform._renderPlatform:"object"==typeof device?/Android/i.test(device.platform):/Android/i.test(navigator.userAgent)},isAndroidPhone:function(){return/Android/i.test(navigator.userAgent)&&/Mobile/i.test(navigator.userAgent)},isAndroidTablet:function(){return/Android/i.test(navigator.userAgent)&&!/Mobile/i.test(navigator.userAgent)},isWP:function(){return ons.platform._renderPlatform?"wp"===ons.platform._renderPlatform:"object"==typeof device?/Win32NT|WinCE/i.test(device.platform):/Windows Phone|IEMobile|WPDesktop/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isIPod:function(){return/iPod/i.test(navigator.userAgent)},isBlackBerry:function(){return ons.platform._renderPlatform?"blackberry"===ons.platform._renderPlatform:"object"==typeof device?/BlackBerry/i.test(device.platform):/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return ons.platform._renderPlatform?"opera"===ons.platform._renderPlatform:!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return ons.platform._renderPlatform?"firefox"===ons.platform._renderPlatform:"undefined"!=typeof InstallTrigger},isSafari:function(){return ons.platform._renderPlatform?"safari"===ons.platform._renderPlatform:Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return ons.platform._renderPlatform?"chrome"===ons.platform._renderPlatform:!(!window.chrome||window.opera||navigator.userAgent.indexOf(" OPR/")>=0||navigator.userAgent.indexOf(" Edge/")>=0)},isIE:function(){return ons.platform._renderPlatform?"ie"===ons.platform._renderPlatform:!!document.documentMode},isEdge:function(){return ons.platform._renderPlatform?"edge"===ons.platform._renderPlatform:navigator.userAgent.indexOf(" Edge/")>=0},isIOS7above:function(){if("object"==typeof device)return/iOS/i.test(device.platform)&&parseInt(device.version.split(".")[0])>=7;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},getMobileOS:function(){return this.isAndroid()?"android":this.isIOS()?"ios":this.isWP()?"wp":"other"},getIOSDevice:function(){return this.isIPhone()?"iphone":this.isIPad()?"ipad":this.isIPod()?"ipod":"na"}}}(window.ons=window.ons||{});var _get=function(_x4,_x5,_x6){for(var _again=!0;_again;){var object=_x4,property=_x5,receiver=_x6;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x4=parent,_x5=property,_x6=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AlertDialogAnimator=function(){function AlertDialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,AlertDialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(AlertDialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),AlertDialogAnimator}(),AndroidAlertDialogAnimator=function(_AlertDialogAnimator){function AndroidAlertDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"cubic-bezier(.1, .7, .4, 1)":_ref2$timing,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.2:_ref2$duration,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay;_classCallCheck(this,AndroidAlertDialogAnimator),_get(Object.getPrototypeOf(AndroidAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(AndroidAlertDialogAnimator,_AlertDialogAnimator),_createClass(AndroidAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidAlertDialogAnimator}(AlertDialogAnimator),IOSAlertDialogAnimator=function(_AlertDialogAnimator2){function IOSAlertDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"cubic-bezier(.1, .7, .4, 1)":_ref3$timing,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.2:_ref3$duration,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay;_classCallCheck(this,IOSAlertDialogAnimator),_get(Object.getPrototypeOf(IOSAlertDialogAnimator.prototype),"constructor",this).call(this,{ duration:duration,timing:timing,delay:delay})}return _inherits(IOSAlertDialogAnimator,_AlertDialogAnimator2),_createClass(IOSAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSAlertDialogAnimator}(AlertDialogAnimator);ons._internal=ons._internal||{},ons._internal.AlertDialogAnimator=AlertDialogAnimator,ons._internal.AndroidAlertDialogAnimator=AndroidAlertDialogAnimator,ons._internal.IOSAlertDialogAnimator=IOSAlertDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AnimatorFactory=function(){function AnimatorFactory(opts){if(_classCallCheck(this,AnimatorFactory),this._animators=opts.animators,this._baseClass=opts.baseClass,this._baseClassName=opts.baseClassName||opts.baseClass.name,this._animation=opts.defaultAnimation||"default",this._animationOptions=opts.defaultAnimationOptions||{},!this._animators[this._animation])throw new Error("No such animation: "+this._animation)}return _createClass(AnimatorFactory,[{key:"setAnimationOptions",value:function(options){this._animationOptions=options}},{key:"newAnimator",value:function(options,defaultAnimator){options=options||{};var animator=null;if(options.animation instanceof this._baseClass)return options.animation;var Animator=null;if("string"==typeof options.animation&&(Animator=this._animators[options.animation]),!Animator&&defaultAnimator)animator=defaultAnimator;else{Animator=Animator||this._animators[this._animation];var animationOpts=ons._util.extend({},this._animationOptions,options.animationOptions||{},ons._config.animationsDisabled?{duration:0,delay:0}:{});animator=new Animator(animationOpts)}if(!(animator instanceof this._baseClass))throw new Error('"animator" is not an instance of '+this._baseClassName+".");return animator}}],[{key:"parseAnimationOptionsString",value:function(jsonString){try{if("string"==typeof jsonString){var result=JSON.parse(jsonString);if("object"==typeof result&&null!==result)return result;console.error('"animation-options" attribute must be a JSON object string: '+jsonString)}return{}}catch(e){return console.error('"animation-options" attribute must be a JSON object string: '+jsonString),{}}}}]),AnimatorFactory}();ons._internal=ons._internal||{},ons._internal.AnimatorFactory=AnimatorFactory}(window.ons=window.ons||{});var _get=function(_x5,_x6,_x7){for(var _again=!0;_again;){var object=_x5,property=_x6,receiver=_x7;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x5=parent,_x6=property,_x7=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var DialogAnimator=function(){function DialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,DialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(DialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),DialogAnimator}(),AndroidDialogAnimator=function(_DialogAnimator){function AndroidDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"ease-in-out":_ref2$timing,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.3:_ref2$duration;_classCallCheck(this,AndroidDialogAnimator),_get(Object.getPrototypeOf(AndroidDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(AndroidDialogAnimator,_DialogAnimator),_createClass(AndroidDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidDialogAnimator}(DialogAnimator),IOSDialogAnimator=function(_DialogAnimator2){function IOSDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"ease-in-out":_ref3$timing,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.3:_ref3$duration;_classCallCheck(this,IOSDialogAnimator),_get(Object.getPrototypeOf(IOSDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(IOSDialogAnimator,_DialogAnimator2),_createClass(IOSDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSDialogAnimator}(DialogAnimator),SlideDialogAnimator=function(_DialogAnimator3){function SlideDialogAnimator(){var _ref4=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref4$timing=_ref4.timing,timing=void 0===_ref4$timing?"cubic-bezier(.1, .7, .4, 1)":_ref4$timing,_ref4$delay=_ref4.delay,delay=void 0===_ref4$delay?0:_ref4$delay,_ref4$duration=_ref4.duration,duration=void 0===_ref4$duration?.2:_ref4$duration;_classCallCheck(this,SlideDialogAnimator),_get(Object.getPrototypeOf(SlideDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(SlideDialogAnimator,_DialogAnimator3),_createClass(SlideDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),SlideDialogAnimator}(DialogAnimator);ons._internal=ons._internal||{},ons._internal.DialogAnimator=DialogAnimator,ons._internal.AndroidDialogAnimator=AndroidDialogAnimator,ons._internal.IOSDialogAnimator=IOSDialogAnimator,ons._internal.SlideDialogAnimator=SlideDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=function(_ModalAnimator){function FadeModalAnimator(options){_classCallCheck(this,FadeModalAnimator),options.timing=options.timing||"linear",options.duration=options.duration||"0.3",options.delay=options.delay||0,_get(Object.getPrototypeOf(FadeModalAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeModalAnimator,_ModalAnimator),_createClass(FadeModalAnimator,[{key:"show",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}},{key:"hide",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}}]),FadeModalAnimator}(ModalAnimator);ons._internal=ons._internal||{},ons._internal.FadeModalAnimator=FadeModalAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function FadeNavigatorTransitionAnimator(options){_classCallCheck(this,FadeNavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),_get(Object.getPrototypeOf(FadeNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(FadeNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.element._getContentElement(),enterPage.element._getBackgroundElement()]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}),animit(enterPage.element._getToolbarElement()).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle())}},{key:"pop",value:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.element._getContentElement(),leavePage.element._getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}),animit(leavePage.element._getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))}}]),FadeNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.FadeNavigatorTransitionAnimator=FadeNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=function(_PopoverAnimator){function FadePopoverAnimator(options){_classCallCheck(this,FadePopoverAnimator),_get(Object.getPrototypeOf(FadePopoverAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadePopoverAnimator,_PopoverAnimator),_createClass(FadePopoverAnimator,[{key:"show",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).wait(this.delay).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),FadePopoverAnimator}(PopoverAnimator);ons._internal=ons._internal||{},ons._internal.FadePopoverAnimator=FadePopoverAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function IOSSlideNavigatorTransitionAnimator(options){_classCallCheck(this,IOSSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(IOSSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black; opacity: 0;"></div>\n ')}return _inherits(IOSSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(IOSSlideNavigatorTransitionAnimator,[{key:"_decompose",value:function(page){CustomElements.upgrade(page.element);var toolbar=page.element._getToolbarElement();CustomElements.upgrade(toolbar);var left=toolbar._getToolbarLeftItemsElement(),right=toolbar._getToolbarRightItemsElement(),excludeBackButtonLabel=function(elements){for(var result=[],i=0;i<elements.length;i++)if("ons-back-button"===elements[i].nodeName.toLowerCase()){var iconElement=elements[i].querySelector(".ons-back-button__icon");iconElement&&result.push(iconElement)}else result.push(elements[i]);return result},other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[toolbar._getToolbarCenterItemsElement(),toolbar._getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.element._getContentElement(),background:page.element._getBackgroundElement(),toolbar:toolbar,bottomToolbar:page.element._getBottomToolbarElement()}}},{key:"_shouldAnimateToolbar",value:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.element._canAnimateToolbar()&&leavePage.element._canAnimateToolbar(),noAndroidLikeToolbar=!enterPage.element._getToolbarElement().classList.contains("navigation-bar--android")&&!leavePage.element._getToolbarElement().classList.contains("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar}},{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:.1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(this.delay+.3).restoreStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()}),animit(leavePageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePageDecomposition.other).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle())):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()})))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(0).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}),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}).wait(this.delay).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()})))}}]),IOSSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.IOSSlideNavigatorTransitionAnimator=IOSSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,LazyRepeatDelegate=function(){function LazyRepeatDelegate(){_classCallCheck(this,LazyRepeatDelegate)}return _createClass(LazyRepeatDelegate,[{key:"prepareItem",value:function(index,done){throw new Error("This is an abstract method.")}},{key:"countItems",value:function(){throw new Error("This is an abstract method.")}},{key:"updateItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"calculateItemHeight",value:function(index){throw new Error("This is an abstract method.")}},{key:"destroyItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"destroy",value:function(){throw new Error("This is an abstract method.")}}]),LazyRepeatDelegate}(),LazyRepeatProvider=function(){function LazyRepeatProvider(wrapperElement,templateElement,delegate){if(_classCallCheck(this,LazyRepeatProvider),!(delegate instanceof LazyRepeatDelegate))throw new Error('"delegate" parameter must be an instance of ons._internal.LazyRepeatDelegate.');if(!(templateElement instanceof Element))throw new Error('"templateElement" parameter must be an instance of Element.');if(!(wrapperElement instanceof Element))throw new Error('"wrapperElement" parameter must be an instance of Element.');if(this._templateElement=templateElement,this._wrapperElement=wrapperElement,this._delegate=delegate,this._pageContent=util.findParent(wrapperElement,".page__content"),this._pageContent||(this._pageContent=util.findParent(wrapperElement,".ons-scroller__content")),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> or an <ons-scroller> element.");this._itemHeightSum=[],this._maxIndex=0,this._renderedItems={},this._addEventListeners(),this._onChange()}return _createClass(LazyRepeatProvider,[{key:"_countItems",value:function(){return this._delegate.countItems()}},{key:"_getItemHeight",value:function(i){return this._delegate.calculateItemHeight(i)}},{key:"_getTopOffset",value:function(){return"undefined"!=typeof this._wrapperElement&&null!==this._wrapperElement?this._wrapperElement.getBoundingClientRect().top:0}},{key:"_onChange",value:function(){this._render()}},{key:"_render",value:function(){for(var items=this._getItemsInView(),keep={},i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key);this._wrapperElement.style.height=this._calculateListHeight()+"px"}},{key:"_calculateListHeight",value:function(){var indices=Object.keys(this._renderedItems).map(function(n){return parseInt(n)});return this._itemHeightSum[indices.pop()]||0}},{key:"_isRendered",value:function(index){return this._renderedItems.hasOwnProperty(index)}},{key:"_renderElement", value:function(_ref){var _this=this,index=_ref.index,top=_ref.top;if(this._isRendered(index)){var currentItem=this._renderedItems[index];this._delegate.updateItem(index,currentItem);var element=this._renderedItems[index].element;return void(element.style.top=this._wrapperElement.offsetTop+top+"px")}this._delegate.prepareItem(index,function(item){var element=item.element;element.style.position="absolute",element.style.top=top+"px",element.style.left="0px",element.style.right="0px",_this._wrapperElement.appendChild(element),_this._renderedItems[index]=item})}},{key:"_removeElement",value:function(index){if(this._isRendered(index)){var item=this._renderedItems[index];this._delegate.destroyItem(index,item),item.element.parentElement&&item.element.parentElement.removeChild(item.element),item=null,delete this._renderedItems[index]}}},{key:"_removeAllElements",value:function(){for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&this._removeElement(key)}},{key:"_calculateStartIndex",value: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}}},{key:"_recalculateItemHeightSum",value:function(){for(var sums=this._itemHeightSum,i=0,sum=0;i<Math.min(sums.length,this._countItems());i++)sum+=this._getItemHeight(i),sums[i]=sum}},{key:"_getItemsInView",value:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems();cnt!==this._itemCount&&(this._recalculateItemHeightSum(),this._maxIndex=cnt-1),this._itemCount=cnt;var startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-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))),i>0?this._itemHeightSum[i]=this._itemHeightSum[i-1]+h:this._itemHeightSum[i]=h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items}},{key:"_debounce",value:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}}},{key:"_doubleFireOnTouchend",value:function(){this._render(),this._debounce(this._render.bind(this),100)}},{key:"_addEventListeners",value:function(){ons.platform.isIOS()?this._boundOnChange=this._debounce(this._onChange.bind(this),30):this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.addEventListener("touchmove",this._boundOnChange,!0),this._pageContent.addEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.addEventListener("resize",this._boundOnChange,!0)}},{key:"_removeEventListeners",value:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.removeEventListener("touchmove",this._boundOnChange,!0),this._pageContent.removeEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.removeEventListener("resize",this._boundOnChange,!0)}},{key:"destroy",value:function(){this._delegate.destroy(),this._parentElement=this._templateElement=this._delegate=this._renderedItems=null,this._removeEventListeners()}}]),LazyRepeatProvider}();ons._internal=ons._internal||{},ons._internal.LazyRepeatProvider=LazyRepeatProvider,ons._internal.LazyRepeatDelegate=LazyRepeatDelegate}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function LiftNavigatorTransitionAnimator(options){_classCallCheck(this,LiftNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(LiftNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black;"></div>\n ')}return _inherits(LiftNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(LiftNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element);var maskClear=animit(this.backgroundMask).wait(.6).queue(function(done){_this.backgroundMask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).wait(.2).restoreStyle().queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:this.duration,timing:this.timing}))}},{key:"pop",value:function(enterPage,leavePage,callback){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element),animit.runAll(animit(this.backgroundMask).wait(.4).queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:this.duration,timing:this.timing}))}}]),LiftNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.LiftNavigatorTransitionAnimator=LiftNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModifierUtil=function(){function ModifierUtil(){_classCallCheck(this,ModifierUtil)}return _createClass(ModifierUtil,null,[{key:"diff",value:function(last,current){function makeDict(modifier){var dict={};return ModifierUtil.split(modifier).forEach(function(token){return dict[token]=token}),dict}last=makeDict((""+last).trim()),current=makeDict((""+current).trim());var removed=Object.keys(last).reduce(function(result,token){return current[token]||result.push(token),result},[]),added=Object.keys(current).reduce(function(result,token){return last[token]||result.push(token),result},[]);return{added:added,removed:removed}}},{key:"applyDiffToClassList",value:function(diff,classList,template){diff.added.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.add(klass)}),diff.removed.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.remove(klass)})}},{key:"applyDiffToElement",value:function(diff,element,scheme){for(var selector in scheme)if(scheme.hasOwnProperty(selector))for(var targetElements=""===selector?[element]:element.querySelectorAll(selector),i=0;i<targetElements.length;i++)ModifierUtil.applyDiffToClassList(diff,targetElements[i].classList,scheme[selector])}},{key:"onModifierChanged",value:function(last,current,element,scheme){return ModifierUtil.applyDiffToElement(ModifierUtil.diff(last,current),element,scheme)}},{key:"initModifier",value:function(element,scheme){var modifier=element.getAttribute("modifier");"string"==typeof modifier&&ModifierUtil.applyDiffToElement({removed:[],added:ModifierUtil.split(modifier)},element,scheme)}},{key:"split",value:function(modifier){return"string"!=typeof modifier?[]:modifier.trim().split(/ +/).filter(function(token){return""!==token})}}]),ModifierUtil}();ons._internal=ons._internal||{},ons._internal.ModifierUtil=ModifierUtil}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,NavigatorPage=function(){function NavigatorPage(params){var _this=this;_classCallCheck(this,NavigatorPage),this.page=params.page,this.name=params.page,this.element=params.element,this.options=params.options,this.navigator=params.navigator,this.initialContent=params.initialContent,this._blockEvents=function(event){(_this.navigator._isPopping||_this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())},this._pointerEvents.forEach(function(event){return _this.element.addEventListener(event,_this._blockEvents)},!1)}return _createClass(NavigatorPage,[{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"getPageView",value:function(){if(!this._page&&(this._page=util.findParent("ons-page"),!this._page))throw new Error("Fail to fetch ons-page element.");return this._page}},{key:"destroy",value:function(){var _this2=this;this._pointerEvents.forEach(function(event){return _this2.element.removeEventListener(event,_this2._blockEvents)},!1),this.element._destroy();var index=this.navigator._pages.indexOf(this);-1!==index&&this.navigator._pages.splice(index,1),this.element=this._page=this.options=this.navigator=null}},{key:"_pointerEvents",get:function(){return["touchmove"]}}]),NavigatorPage}();window.ons._internal.NavigatorPage=NavigatorPage}(window.ons=window.ons||{}),function(ons){"use strict";ons._internal=ons._internal||{},ons._internal.nullElement=document.createElement("div"),ons._internal.isEnabledAutoStatusBarFill=function(){return!!ons._config.autoStatusBarFill},ons._internal.normalizePageHTML=function(html){return html=(""+html).trim(),html.match(/^<ons-page/)||(html="<ons-page _muted>"+html+"</ons-page>"),html},ons._internal.waitDOMContentLoaded=function(callback){"loading"===document.readyState||"uninitialized"==document.readyState?window.document.addEventListener("DOMContentLoaded",callback):setImmediate(callback)},ons._internal.shouldFillStatusBar=function(element){if(ons._internal.isEnabledAutoStatusBarFill()&&ons.platform.isWebView()&&ons.platform.isIOS7above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,!element||!element.hasAttribute)return!0}}return!1},ons._internal.templateStore={_storage:{},get:function(key){return ons._internal.templateStore._storage[key]||null},set:function(key,template){ons._internal.templateStore._storage[key]=template}},document.addEventListener("_templateloaded",function(e){"ons-template"===e.target.nodeName.toLowerCase()&&ons._internal.templateStore.set(e.templateId,e.template)},!1),document.addEventListener("DOMContentLoaded",function(){function register(query){for(var templates=document.querySelectorAll(query),i=0;i<templates.length;i++)ons._internal.templateStore.set(templates[i].getAttribute("id"),templates[i].textContent)}register('script[type="text/ons-template"]'),register('script[type="text/template"]'),register('script[type="text/ng-template"]')},!1),ons._internal.getTemplateHTMLAsync=function(page){return new Promise(function(resolve,reject){setImmediate(function(){var cache=ons._internal.templateStore.get(page);if(cache){var html="string"==typeof cache?cache:cache[1];resolve(html)}else!function(){var xhr=new XMLHttpRequest;xhr.open("GET",page,!0),xhr.onload=function(response){var html=xhr.responseText;xhr.status>=400&&xhr.status<600?reject(html):resolve(html)},xhr.onerror=function(){throw new Error("The page is not found: "+page)},xhr.send(null)}()})})},ons._internal.getPageHTMLAsync=function(page){var pages=ons.pageAttributeExpression.evaluate(page),getPage=function getPage(page){return"string"!=typeof page?Promise.reject("Must specify a page."):ons._internal.getTemplateHTMLAsync(page).then(function(html){return ons._internal.normalizePageHTML(html)},function(error){return 0===pages.length?Promise.reject(error):getPage(pages.shift())}).then(function(html){return ons._internal.normalizePageHTML(html)})};return getPage(pages.shift())}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util;ons.notification={},ons.notification._createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,_callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder,defaultValue,submitOnEnter,compile){compile=compile||function(object){return object};var titleElementHTML="string"==typeof title?'<div class="alert-dialog-title"></div>':"",dialogElement=util.createElement("\n <ons-alert-dialog>\n "+titleElementHTML+'\n <div class="alert-dialog-content"></div>\n <div class="alert-dialog-footer"></div>\n </ons-alert-dialog>'),titleElement=dialogElement.querySelector(".alert-dialog-title"),messageElement=dialogElement.querySelector(".alert-dialog-content"),footerElement=dialogElement.querySelector(".alert-dialog-footer"),inputElement=void 0;"string"==typeof title&&(titleElement.textContent=title),titleElement=null,dialogElement.setAttribute("animation",animation),messageIsHTML?messageElement.innerHTML=message:messageElement.textContent=message,promptDialog&&(inputElement=util.createElement('<input class="text-input" type="text"></input>'),modifier&&inputElement.classList.add("text-input--"+modifier),inputElement.setAttribute("placeholder",placeholder),inputElement.value=defaultValue,inputElement.style.width="100%",inputElement.style.marginTop="10px",messageElement.appendChild(inputElement),submitOnEnter&&inputElement.addEventListener("keypress",function(event){13===event.keyCode&&dialogElement.hide({callback:function(){_callback(inputElement.value),dialogElement.destroy(),dialogElement=null}})},!1)),document.body.appendChild(dialogElement),compile(dialogElement),buttonLabels.length<=2&&footerElement.classList.add("alert-dialog-footer--one");for(var createButton=function(i){var buttonElement=util.createElement('<button class="alert-dialog-button"></button>');buttonElement.textContent=buttonLabels[i],i==primaryButtonIndex&&buttonElement.classList.add("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonElement.classList.add("alert-dialog-button--one");var onClick=function onClick(){buttonElement.removeEventListener("click",onClick,!1),dialogElement.hide({callback:function(){_callback(promptDialog?inputElement.value:i),dialogElement.destroy(),dialogElement=inputElement=buttonElement=null}})};buttonElement.addEventListener("click",onClick,!1),footerElement.appendChild(buttonElement)},i=0;i<buttonLabels.length;i++)createButton(i);return cancelable&&(dialogElement.setCancelable(cancelable),dialogElement.addEventListener("cancel",function(){_callback(promptDialog?null:-1),setTimeout(function(){dialogElement.destroy(),dialogElement=null,inputElement=null})},!1)),dialogElement.show({callback:function(){inputElement&&promptDialog&&autofocus&&inputElement.focus()}}),messageElement=footerElement=null,modifier&&dialogElement.setAttribute("modifier",modifier),Promise.resolve(dialogElement)},ons.notification._alertOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1,"","",!1,options.compile)},ons.notification.alert=ons.notification._alertOriginal,ons.notification._confirmOriginal=function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");return ons.notification._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,"","",!1,options.compile)},ons.notification.confirm=ons.notification._confirmOriginal,ons.notification._promptOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",defaultValue:"",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0,submitOnEnter:!0};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");return ons.notification._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,options.defaultValue,options.submitOnEnter,options.compile)},ons.notification.prompt=ons.notification._promptOriginal}(window.ons=window.ons||{}),function(ons){var create=function(){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;"orientation"in window?window.orientation%180===0?this._isPortrait=function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var _this=this,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))},20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj};ons.orientation=create()._init()}(window.ons=window.ons||{}),function(ons){ons.pageAttributeExpression={_variables:{},defineVariable:function(name,value){var overwrite=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];if("string"!=typeof name)throw new Error("Variable name must be a string.");if("string"!=typeof value&&"function"!=typeof value)throw new Error("Variable value must be a string or a function.");if(this._variables.hasOwnProperty(name)&&!overwrite)throw new Error('"'+name+'" is already defined.');this._variables[name]=value},getVariable:function(name){return this._variables.hasOwnProperty(name)?this._variables[name]:null},removeVariable:function(name){delete this._variables[name]},getAllVariables:function(){return this._variables},_parsePart:function(part){var c=void 0,inInterpolation=!1,currentIndex=0,tokens=[];if(0===part.length)throw new Error("Unable to parse empty string.");for(var i=0;i<part.length;i++)if(c=part.charAt(i),"$"===c&&"{"===part.charAt(i+1)){if(inInterpolation)throw new Error("Nested interpolation not supported.");var token=part.substring(currentIndex,i);token.length>0&&tokens.push(part.substring(currentIndex,i)),currentIndex=i,inInterpolation=!0}else if("}"===c){if(!inInterpolation)throw new Error("} must be preceeded by ${");var token=part.substring(currentIndex,i+1);token.length>0&&tokens.push(part.substring(currentIndex,i+1)),currentIndex=i+1,inInterpolation=!1}if(inInterpolation)throw new Error("Unterminated interpolation.");return tokens.push(part.substring(currentIndex,part.length)),tokens},_replaceToken:function(token){var re=/^\${(.*?)}$/,match=token.match(re);if(match){var _name=match[1].trim(),variable=this.getVariable(_name);if(null===variable)throw new Error('Variable "'+_name+'" does not exist.');if("string"==typeof variable)return variable;var rv=variable();if("string"!=typeof rv)throw new Error("Must return a string.");return rv}return token},_replaceTokens:function(tokens){return tokens.map(this._replaceToken.bind(this))},_parseExpression:function(expression){return expression.split(",").map(function(part){return part.trim()}).map(this._parsePart.bind(this)).map(this._replaceTokens.bind(this)).map(function(part){return part.join("")})},evaluate:function(expression){return expression?this._parseExpression(expression):[]}},ons.pageAttributeExpression.defineVariable("mobileOS",ons.platform.getMobileOS()),ons.pageAttributeExpression.defineVariable("iOSDevice",ons.platform.getIOSDevice()),ons.pageAttributeExpression.defineVariable("runtime",function(){return ons.platform.isWebView()?"cordova":"browser"})}(window.ons=window.ons||{}),function(ons){"use strict";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)})}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function SimpleSlideNavigatorTransitionAnimator(options){_classCallCheck(this,SimpleSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.3,timing:"cubic-bezier(.1, .7, .4, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(SimpleSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%; z-index: 2;\n background-color: black; opacity: 0;"></div>\n '),this.blackMaskOpacity=.4}return _inherits(SimpleSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(SimpleSlideNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentElement.insertBefore(this.backgroundMask,leavePage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().wait(.2).queue(function(done){callback(),done()}))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}}]),SimpleSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.SimpleSlideNavigatorTransitionAnimator=SimpleSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var TabbarAnimator=function(){function TabbarAnimator(options){_classCallCheck(this,TabbarAnimator),options=options||{},this.timing=options.timing||"linear",this.duration=void 0!==options.duration?options.duration:"0.4",this.delay=void 0!==options.delay?options.delay:"0"}return _createClass(TabbarAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){throw new Error("This method must be implemented.")}}]),TabbarAnimator}(),TabbarNoneAnimator=function(_TabbarAnimator){function TabbarNoneAnimator(){_classCallCheck(this,TabbarNoneAnimator),_get(Object.getPrototypeOf(TabbarNoneAnimator.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarNoneAnimator,_TabbarAnimator),_createClass(TabbarNoneAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){done()}}]),TabbarNoneAnimator}(TabbarAnimator),TabbarFadeAnimator=function(_TabbarAnimator2){function TabbarFadeAnimator(options){_classCallCheck(this,TabbarFadeAnimator),options.timing=void 0!==options.timing?options.timing:"linear",options.duration=void 0!==options.duration?options.duration:"0.4",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarFadeAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarFadeAnimator,_TabbarAnimator2),_createClass(TabbarFadeAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D(0, 0, 0)",opacity:0}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)",opacity:1}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:this.duration,timing:this.timing}))}}]),TabbarFadeAnimator}(TabbarAnimator),TabbarSlideAnimator=function(_TabbarAnimator3){function TabbarSlideAnimator(options){_classCallCheck(this,TabbarSlideAnimator),options.timing=void 0!==options.timing?options.timing:"ease-in",options.duration=void 0!==options.duration?options.duration:"0.15",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarSlideAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarSlideAnimator,_TabbarAnimator3), _createClass(TabbarSlideAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){var sgn=enterIndex>leaveIndex;animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D("+(sgn?"":"-")+"100%, 0, 0)"}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)"},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)"}).wait(this.delay).queue({transform:"translate3D("+(sgn?"-":"")+"100%, 0, 0)"},{duration:this.duration,timing:this.timing}))}}]),TabbarSlideAnimator}(TabbarAnimator);ons._internal=ons._internal||{},ons._internal.TabbarAnimator=TabbarAnimator,ons._internal.TabbarFadeAnimator=TabbarFadeAnimator,ons._internal.TabbarNoneAnimator=TabbarNoneAnimator,ons._internal.TabbarSlideAnimator=TabbarSlideAnimator}(window.ons=window.ons||{}),function(window){"use strict";function setup(){GestureDetector.READY||(Event.determineEventTypes(),Utils.each(GestureDetector.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(GestureDetector.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(GestureDetector.DOCUMENT,EVENT_END,Detection.detect),GestureDetector.READY=!0)}var GestureDetector=function GestureDetector(element,options){return new GestureDetector.Instance(element,options||{})};GestureDetector.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},GestureDetector.DOCUMENT=document,GestureDetector.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,GestureDetector.HAS_TOUCHEVENTS="ontouchstart"in window,GestureDetector.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),GestureDetector.NO_MOUSEEVENTS=GestureDetector.HAS_TOUCHEVENTS&&GestureDetector.IS_MOBILE||GestureDetector.HAS_POINTEREVENTS,GestureDetector.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=GestureDetector.DIRECTION_DOWN="down",DIRECTION_LEFT=GestureDetector.DIRECTION_LEFT="left",DIRECTION_UP=GestureDetector.DIRECTION_UP="up",DIRECTION_RIGHT=GestureDetector.DIRECTION_RIGHT="right",POINTER_MOUSE=GestureDetector.POINTER_MOUSE="mouse",POINTER_TOUCH=GestureDetector.POINTER_TOUCH="touch",POINTER_PEN=GestureDetector.POINTER_PEN="pen",EVENT_START=GestureDetector.EVENT_START="start",EVENT_MOVE=GestureDetector.EVENT_MOVE="move",EVENT_END=GestureDetector.EVENT_END="end",EVENT_RELEASE=GestureDetector.EVENT_RELEASE="release",EVENT_TOUCH=GestureDetector.EVENT_TOUCH="touch";GestureDetector.READY=!1,GestureDetector.plugins=GestureDetector.plugins||{},GestureDetector.gestures=GestureDetector.gestures||{};var Utils=GestureDetector.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||void 0!==dest[key]&&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(void 0!==obj.length){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=GestureDetector.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=GestureDetector.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=GestureDetector.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:GestureDetector.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(GestureDetector.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=GestureDetector.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=GestureDetector.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>GestureDetector.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 void 0===options[gesture.name]&&(options[gesture.name]=!0),Utils.extend(GestureDetector.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}};GestureDetector.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({},GestureDetector.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=[]},GestureDetector.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=GestureDetector.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&&(Utils.isVertical(lastDirection)?ev.direction=ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.direction=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;GestureDetector.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),GestureDetector.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;GestureDetector.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),GestureDetector.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},GestureDetector.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;GestureDetector.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),GestureDetector.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;GestureDetector.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),window.ons=window.ons||{},window.ons.GestureDetector=GestureDetector}(window),window.styler=function(){"use strict";var styler=function(element,style){return styler.css.apply(styler,arguments)};return styler.css=function(element,styles){var keys=Object.keys(styles);return keys.forEach(function(key){key in element.style?element.style[key]=styles[key]:styler._prefix(key)in element.style?element.style[styler._prefix(key)]=styles[key]:console.warn("No such style property: "+key)}),element},styler._prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),prefix=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return function(name){return prefix+name.substr(0,1).toUpperCase()+name.substr(1)}}(),styler.clear=function(element){styler._clear(element)},styler._clear=function(element){for(var len=element.style.length,style=element.style,keys=[],i=0;len>i;i++)keys.push(style[i]);keys.forEach(function(key){style[key]=""})},styler}(),function(ons){window.addEventListener("load",function(){return FastClick.attach(document.body)},!1),window.addEventListener("DOMContentLoaded",function(){ons._defaultDeviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(window.document.body,function(){navigator.app.exitApp()})},!1),ons.ready(function(){ons._setupLoadingPlaceHolders()}),(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"))}),"function"!=typeof HTMLElement?(ons._BaseElement=function(){},ons._BaseElement.prototype=document.createElement("div")):ons._BaseElement=HTMLElement,"undefined"!=typeof module&&module.exports&&(module.exports=ons)}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x11,_x12,_x13){for(var _again=!0;_again;){var object=_x11,property=_x12,receiver=_x13;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x11=parent,_x12=property,_x13=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,SplitterElement=function(_ons$_BaseElement){function SplitterElement(){_classCallCheck(this,SplitterElement),_get(Object.getPrototypeOf(SplitterElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterElement,_ons$_BaseElement),_createClass(SplitterElement,[{key:"createdCallback",value:function(){this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._boundOnModeChange=this._onModeChange.bind(this)}},{key:"_onModeChange",value:function(event){event.target.parentElement===this&&this._layout()}},{key:"_getSideElement",value:function(side){var result=util.findChild(this,function(element){return"ons-splitter-side"===element.nodeName.toLowerCase()&&element.getAttribute("side")===side});return result&&CustomElements.upgrade(result),result}},{key:"_layout",value:function(){var content=this._getContentElement(),left=this._getSideElement("left"),right=this._getSideElement("right");content&&(left&&left.getCurrentMode&&"split"===left.getCurrentMode()?content.style.left=left._getWidth():content.style.left="0px",right&&right.getCurrentMode&&"split"===right.getCurrentMode()?content.style.right=right._getWidth():content.style.right="0px")}},{key:"_getContentElement",value:function(){return util.findChild(this,"ons-splitter-content")}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"openRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("right",options)}},{key:"_getMaskElement",value:function(){var mask=util.findChild(this,"ons-splitter-mask");return mask||this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"openLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("left",options)}},{key:"_open",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.open(options):!1}},{key:"closeRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("right",options)}},{key:"closeLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("left",options)}},{key:"_close",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.close(options):!1}},{key:"toggleLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("left",options)}},{key:"toggleRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("right",options)}},{key:"_toggle",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.toggle(options):!1}},{key:"leftIsOpened",value:function(){return this._isOpened("left")}},{key:"rightIsOpened",value:function(){return this._isOpened("right")}},{key:"_isOpened",value:function(side){var menu=this._getSideElement(side);return menu?menu.isOpened():!1}},{key:"loadContentPage",value:function(page){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],content=this._getContentElement();if(content)return content.load(page,options);throw new Error('child "ons-splitter-content" element is not found in this element.')}},{key:"_onDeviceBackButton",value:function(handler){var left=this._getSideElement("left"),right=this._getSideElement("right");return left.isOpened()?void left.close():right.isOpened()?void right.close():void handler.callParentHandler()}},{key:"attachedCallback",value:function(){var _this=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),this._assertChildren(),this.addEventListener("modechange",this._boundOnModeChange,!1),setImmediate(function(){return _this._layout()})}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_assertChildren",value:function(){var names=["ons-splitter-content","ons-splitter-side","ons-splitter-mask"],contentCount=0,sideCount=0,maskCount=0;if(util.arrayFrom(this.children).forEach(function(element){var name=element.nodeName.toLowerCase();if(-1===names.indexOf(name))throw new Error('"'+name+'" element is not allowed in "ons-splitter" element.');"ons-splitter-content"===name?contentCount++:"ons-splitter-content"===name?sideCount++:"ons-splitter-mask"===name&&maskCount++}),contentCount>1)throw new Error("too many <ons-splitter-content> elements.");if(sideCount>2)throw new Error("too many <ons-splitter-side> elements.");if(maskCount>1)throw new Error("too many <ons-splitter-mask> elements.");0===maskCount&&this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this.removeEventListener("modechange",this._boundOnModeChange,!1)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}}]),SplitterElement}(ons._BaseElement);window.OnsSplitterElement||(window.OnsSplitterElement=document.registerElement("ons-splitter",{prototype:SplitterElement.prototype}),window.OnsSplitterElement._animatorDict={"default":ons._internal.OverlaySplitterAnimator,overlay:ons._internal.OverlaySplitterAnimator},window.OnsSplitterElement.registerAnimator=function(name,Animator){if(!(Animator instanceof ons._internal.SplitterAnimator))throw new Error("Animator parameter must be an instance of SplitterAnimator.");window.OnsSplitterElement._animatorDict[name]=Animator},window.OnsSplitterElement.SplitterAnimator=ons._internal.SplitterAnimator)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"tab-bar--*__item",".tab-bar__button":"tab-bar--*__button"},ModifierUtil=ons._internal.ModifierUtil,util=ons._util,templateSource=util.createElement('\n <div>\n <input type="radio" style="display: none">\n <button class="tab-bar__button tab-bar-inner"></button>\n </div>\n '),defaultInnerTemplateSource=util.createElement('\n <div>\n <div class="tab-bar__icon">\n <ons-icon icon="ion-cloud" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon>\n </div>\n <div class="tab-bar__label">label</div>\n </div>\n '),TabElement=function(_ons$_BaseElement){function TabElement(){_classCallCheck(this,TabElement),_get(Object.getPrototypeOf(TabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabElement,_ons$_BaseElement),_createClass(TabElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){for(var fragment=document.createDocumentFragment(),hasChildren=!1;this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),fragment.appendChild(node),node.nodeType==Node.ELEMENT_NODE&&(hasChildren=!0)}for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this.classList.add("tab-bar__item");var button=util.findChild(this,".tab-bar__button");hasChildren?(button.appendChild(fragment),this._hasDefaultTemplate=!1):(this._hasDefaultTemplate=!0,this._updateDefaultTemplate())}},{key:"_updateDefaultTemplate",value:function(){ function getLabelElement(){return self.querySelector(".tab-bar__label")}function getIconElement(){return self.querySelector("ons-icon")}if(this._hasDefaultTemplate){for(var button=util.findChild(this,".tab-bar__button"),template=defaultInnerTemplateSource.cloneNode(!0);template.children[0];)button.appendChild(template.children[0]);var self=this,icon=this.getAttribute("icon"),label=this.getAttribute("label");if("string"==typeof icon)getIconElement().setAttribute("icon",icon);else{var wrapper=button.querySelector(".tab-bar__icon");wrapper.parentNode.removeChild(wrapper)}"string"==typeof label?getLabelElement().textContent=label:getLabelElement().parentNode.removeChild(getLabelElement())}}},{key:"_onClick",value:function(){var tabbar=this._findTabbarElement();tabbar&&tabbar.setActiveTab(this._findTabIndex())}},{key:"isPersistent",value:function(){return this.hasAttribute("persistent")}},{key:"setActive",value:function(){var radio=util.findChild(this,"input");radio.checked=!0,this.classList.add("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="none"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="inherit"})}},{key:"setInactive",value:function(){var radio=util.findChild(this,"input");radio.checked=!1,this.classList.remove("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="inherit"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="none"})}},{key:"isLoaded",value:function(){return!1}},{key:"_loadPageElement",value:function(callback,link){var _this=this;this.isPersistent()?this._pageElement?callback(this._pageElement):this._createPageElement(this.getAttribute("page"),function(element){link(element,function(element){_this._pageElement=element,callback(element)})}):(this._pageElement=null,this._createPageElement(this.getAttribute("page"),callback))}},{key:"_createPageElement",value:function(page,callback){ons._internal.getPageHTMLAsync(page).then(function(html){callback(util.createElement(html.trim()))})}},{key:"isActive",value:function(){return this.classList.contains("active")}},{key:"canReload",value:function(){return!this.hasAttribute("no-reload")}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"attachedCallback",value:function(){var _this2=this;this._ensureElementPosition(),this.hasAttribute("active")&&!function(){var tabbar=_this2._findTabbarElement(),tabIndex=_this2._findTabIndex();window.OnsTabbarElement.rewritables.ready(tabbar,function(){setImmediate(function(){return tabbar.setActiveTab(tabIndex,{animation:"none"})})})}(),this.addEventListener("click",this._boundOnClick,!1)}},{key:"_findTabbarElement",value:function(){return this.parentNode&&"ons-tabbar"===this.parentNode.nodeName.toLowerCase()?this.parentNode:this.parentNode.parentNode&&"ons-tabbar"===this.parentNode.parentNode.nodeName.toLowerCase()?this.parentNode.parentNode:null}},{key:"_findTabIndex",value:function(){for(var elements=this.parentNode.children,i=0;i<elements.length;i++)if(this===elements[i])return i}},{key:"_ensureElementPosition",value:function(){if(!this._findTabbarElement())throw new Error("This ons-tab element is must be child of ons-tabbar element.")}},{key:"attributeChangedCallback",value:function(name,last,current){return this._hasDefaultTemplate&&("icon"===name||"label"===name)&&this._updateDefaultTemplate(),"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabElement}(ons._BaseElement);window.OnsTabElement||(window.OnsTabElement=document.registerElement("ons-tab",{prototype:TabElement.prototype}),document.registerElement("ons-tabbar-item",{prototype:Object.create(TabElement.prototype)}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={"":"alert-dialog--*",".alert-dialog-title":"alert-dialog-title--*",".alert-dialog-content":"alert-dialog-content--*",".alert-dialog-footer":"alert-dialog-footer--*",".alert-dialog-button":"alert-dialog-button--*",".alert-dialog-footer--one":"alert-dialog-footer--one--*",".alert-dialog-button--one":"alert-dialog-button--one--*",".alert-dialog-button--primal":"alert-dialog-button--primal--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidAlertDialogAnimator=ons._internal.AndroidAlertDialogAnimator,IOSAlertDialogAnimator=ons._internal.IOSAlertDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,AlertDialogAnimator=ons._internal.AlertDialogAnimator,_animatorDict={"default":ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,fade:ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,slide:SlideDialogAnimator,none:AlertDialogAnimator},AlertDialogElement=function(_ons$_BaseElement){function AlertDialogElement(){_classCallCheck(this,AlertDialogElement),_get(Object.getPrototypeOf(AlertDialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(AlertDialogElement,_ons$_BaseElement),_createClass(AlertDialogElement,[{key:"createdCallback",value:function(){this._compile(),this._mask=this._createMask(this.getAttribute("mask-color")),ModifierUtil.initModifier(this,scheme),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:AlertDialogAnimator,baseClassName:"AlertDialogAnimator",defaultAnimation:this.getAttribute("animation")}),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this)}},{key:"_compile",value:function(){if(this.style.display="none",this.style.zIndex="20001",this.classList.add("alert-dialog"),ons.platform.isAndroid()){var modifier=this.hasAttribute("modifier")?this.getAttribute("modifier"):"";this.setAttribute("modifier",(modifier+" android").trim())}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),util.triggerElementEvent(this,"preshow",{alertDialog:this,cancel:function(){_cancel2=!0}}),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock();_this._mask.style.display="block",_this._mask.style.opacity=1,_this.style.display="block";var animator=_this._animatorFactory.newAnimator(options);animator.show(_this,function(){_this._visible=!0,unlock(),util.triggerElementEvent(_this,"postshow",{alertDialog:_this}),callback()})})}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{alertDialog:this,cancel:function(){_cancel3=!0}}),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",_this2._mask.style.display="none",_this2._visible=!1,unlock(),util.triggerElementEvent(_this2,"posthide",{alertDialog:_this2}),callback()})})}},{key:"isShown",value:function(){return this._visible}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this),this._mask.parentElement&&this._mask.parentElement.removeChild(this._mask)}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this3=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this3,"cancel")}})}},{key:"_createMask",value:function(color){return this._mask=util.createElement("<div></div>"),this._mask.classList.add("alert-dialog-mask"),this._mask.style.zIndex=2e4,this._mask.style.display="none",color&&(this._mask.style.backgroundColor=color),document.body.appendChild(this._mask),this._mask}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_titleElement",get:function(){return util.findChild(this,".alert-dialog-title")}},{key:"_contentElement",get:function(){return util.findChild(this,".alert-dialog-content")}},{key:"_dialog",get:function(){return this}}]),AlertDialogElement}(ons._BaseElement);window.OnsAlertDialogElement||(window.OnsAlertDialogElement=document.registerElement("ons-alert-dialog",{prototype:AlertDialogElement.prototype}),window.OnsAlertDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof AlertDialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,iOSTemplateElement=util.createElement('\n <span\n class="toolbar-button--quiet"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n\n <i class="ion-ios-arrow-back ons-back-button__icon"\n style="\n vertical-align: top;\n background-color: transparent;\n height: 44px;\n line-height: 44px;\n font-size: 36px;\n margin-left: 8px;\n margin-right: 2px;\n width: 16px;\n display: inline-block;\n 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 '),MaterialTemplateElement=util.createElement('\n <span class="toolbar-button toolbar-button--material">\n <i class="zmdi zmdi-arrow-left"></i>\n </span>\n '),scheme={".toolbar-button--quiet":"toolbar-button--*"},BackButtonElement=function(_ons$_BaseElement){function BackButtonElement(){_classCallCheck(this,BackButtonElement),_get(Object.getPrototypeOf(BackButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BackButtonElement,_ons$_BaseElement),_createClass(BackButtonElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var toolbar=ons._util.findParent(this,"ons-toolbar"),template=void 0;template=toolbar&&ons._util.hasModifier(toolbar,"material")?MaterialTemplateElement.cloneNode(!0):iOSTemplateElement.cloneNode(!0);for(var inner=template.querySelector(".back-button__label");this.childNodes[0];)inner.appendChild(this.childNodes[0]);this.appendChild(template)}},{key:"_onClick",value:function(){var navigator=util.findParent(this,"ons-navigator");navigator&&navigator.popPage({cancelIfRunning:!0})}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}}]),BackButtonElement}(ons._BaseElement);window.OnsBackButtonElement||(window.OnsBackButtonElement=document.registerElement("ons-back-button",{prototype:BackButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"bottom-bar--*"},ModifierUtil=ons._internal.ModifierUtil,BottomToolbarElement=function(_ons$_BaseElement){function BottomToolbarElement(){_classCallCheck(this,BottomToolbarElement),_get(Object.getPrototypeOf(BottomToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BottomToolbarElement,_ons$_BaseElement),_createClass(BottomToolbarElement,[{key:"createdCallback",value:function(){this.classList.add("bottom-bar"),this.style.zIndex="0",this._update(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("inline"===name)this._update();else if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme)}},{key:"_update",value:function(){var inline="string"==typeof this.getAttribute("inline");this.style.position=inline?"static":"absolute"}}]),BottomToolbarElement}(ons._BaseElement);window.OnsBottomToolbarElement||(window.OnsBottomToolbarElement=document.registerElement("ons-bottom-toolbar",{prototype:BottomToolbarElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"button--*"},ModifierUtil=ons._internal.ModifierUtil,ButtonElement=function(_ons$_BaseElement){function ButtonElement(){_classCallCheck(this,ButtonElement),_get(Object.getPrototypeOf(ButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ButtonElement,_ons$_BaseElement),_createClass(ButtonElement,[{key:"createdCallback",value:function(){this.classList.add("button"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ButtonElement}(ons._BaseElement);window.OnsButtonElement||(window.OnsButtonElement=document.registerElement("ons-button",{prototype:ButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,scheme={"":"carousel-item--*"},CarouselItemElement=function(_ons$_BaseElement){function CarouselItemElement(){_classCallCheck(this,CarouselItemElement),_get(Object.getPrototypeOf(CarouselItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselItemElement,_ons$_BaseElement),_createClass(CarouselItemElement,[{key:"createdCallback",value:function(){this.style.width="100%",ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),CarouselItemElement}(ons._BaseElement);window.OnsCarouselItemElement||(window.OnsCarouselItemElement=document.registerElement("ons-carousel-item",{prototype:CarouselItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,util=ons._util,scheme={"":"carousel--*"},VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.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),computedStyle=window.getComputedStyle(this),totalWidth=this.getBoundingClientRect().width||0,finalWidth=totalWidth-parseInt(computedStyle.paddingLeft,10)-parseInt(computedStyle.paddingRight,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=sizeAttr,children[i].style.width=finalWidth+"px",children[i].style.visibility="visible",children[i].style.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.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),computedStyle=window.getComputedStyle(this),totalHeight=this.getBoundingClientRect().height||0,finalHeight=totalHeight-parseInt(computedStyle.paddingTop,10)-parseInt(computedStyle.paddingBottom,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=finalHeight+"px",children[i].style.width=sizeAttr,children[i].style.visibility="visible",children[i].style.left=i*sizeInfo.number+sizeInfo.unit}},CarouselElement=function(_ons$_BaseElement){function CarouselElement(){_classCallCheck(this,CarouselElement),_get(Object.getPrototypeOf(CarouselElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselElement,_ons$_BaseElement),_createClass(CarouselElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"_onResize",value:function(){this.refresh()}},{key:"_onDirectionChange",value:function(){this._isVertical()?(this.style.overflowX="auto",this.style.overflowY=""):(this.style.overflowX="",this.style.overflowY="auto"),this.refresh()}},{key:"_saveLastState",value:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this.getCarouselItemCount(),width:this._getCarouselItemSize()*this.getCarouselItemCount()}}},{key:"_getCarouselItemSize",value: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")}},{key:"_getInitialIndex",value:function(){var index=parseInt(this.getAttribute("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this.getCarouselItemCount()-1),0)}},{key:"_getCarouselItemSizeAttr",value:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this.getAttribute(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"}},{key:"_decomposeSizeString",value:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}}},{key:"_setupInitialIndex",value:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)}},{key:"setSwipeable",value:function(swipeable){swipeable?this.setAttribute("swipeable",""):this.removeAttribute("swipeable")}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"setAutoScrollRatio",value:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this.setAttribute("auto-scroll-ratio",ratio)}},{key:"getAutoScrollRatio",value:function(){var attr=this.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}},{key:"setActiveCarouselItemIndex",value: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()}},{key:"getActiveCarouselItemIndex",value:function(){var scroll=this._scroll,count=this.getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;var i=void 0;for(i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i}},{key:"next",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)}},{key:"prev",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)}},{key:"setAutoScrollEnabled",value:function(enabled){enabled?this.setAttribute("auto-scroll",""):this.removeAttribute("auto-scroll")}},{key:"isAutoScrollEnabled",value:function(){return this.hasAttribute("auto-scroll")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setOverscrollable",value:function(scrollable){scrollable?this.setAttribute("overscrollable",""):this.removeAttribute("overscrollable")}},{key:"isOverscrollable",value:function(){return this.hasAttribute("overscrollable")}},{key:"_isEnabledChangeEvent",value:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize}},{key:"_isVertical",value:function(){return"vertical"===this.getAttribute("direction")}},{key:"_prepareEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this,{dragMinDistance:1}),this._gestureDetector.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.on("dragend",this._boundOnDragEnd),window.addEventListener("resize",this._boundOnResize,!0)}},{key:"_removeEventListeners",value:function(){this._gestureDetector.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),window.removeEventListener("resize",this._boundOnResize,!0)}},{key:"_tryFirePostChangeEvent",value:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,util.triggerElementEvent(this,"postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}}},{key:"_onDrag",value: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()}}}},{key:"_onDragEnd",value:function(event){var _this=this;if(this._currentElementSize=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;util.triggerElementEvent(this,"overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){return _this._scrollToKillOverScroll()})}}),waitForAction||this._scrollToKillOverScroll()}else this._startMomentumScroll();this._lastDragEvent=null,event.gesture.preventDefault()}}},{key:"_mixin",value:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))}},{key:"_startMomentumScroll",value:function(){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,_scroll=this._normalizeScrollPosition(this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta));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()}}},{key:"_normalizeScrollPosition",value:function(scroll){var _this2=this,max=this._calculateMaxScroll();if(!this.isAutoScrollEnabled())return Math.max(0,Math.min(max,scroll));var _ret=function(){for(var arr=[],size=_this2._getCarouselItemSize(),i=0;i<_this2.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=_this2._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=_this2.getAutoScrollRatio()?{v:lastScroll}:scrollRatio>_this2.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?{v:arr[1]}:{v:arr[0]}}();return"object"==typeof _ret?_ret.v:void 0}},{key:"_getCarouselItemElements",value:function(){return ons._util.arrayFrom(this.children).filter(function(child){return"ons-carousel-item"===child.nodeName.toLowerCase()})}},{key:"_scrollTo",value:function(scroll,options){var _this3=this;options=options||{};var isOverscrollable=this.isOverscrollable(),normalizeScroll=function(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=_this3._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll};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)}},{key:"_calculateMaxScroll",value:function(){var max=this.getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)}},{key:"_isOverScroll",value:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1}},{key:"_getOverScrollDirection",value:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"}},{key:"_scrollToKillOverScroll",value: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)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).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)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=maxScroll)):void 0}},{key:"getCarouselItemCount",value:function(){return this._getCarouselItemElements().length}},{key:"refresh",value:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var _scroll2=this._scroll;this._isOverScroll(_scroll2)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(_scroll2=this._normalizeScrollPosition(_scroll2)),this._scrollTo(_scroll2))}this._saveLastState(),util.triggerElementEvent(this,"refresh",{carousel:this})}}},{key:"first",value:function(){this.setActiveCarouselItemIndex(0)}},{key:"last",value:function(){this.setActiveCarouselItemIndex(Math.max(this.getCarouselItemCount()-1,0))}},{key:"attachedCallback",value:function(){this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name&&this._onDirectionChange())}},{key:"detachedCallback",value:function(){this._removeEventListeners()}}]),CarouselElement}(ons._BaseElement);window.OnsCarouselElement||(window.OnsCarouselElement=document.registerElement("ons-carousel",{prototype:CarouselElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ColumnElement=function(_ons$_BaseElement){function ColumnElement(){_classCallCheck(this,ColumnElement),_get(Object.getPrototypeOf(ColumnElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ColumnElement,_ons$_BaseElement),_createClass(ColumnElement,[{key:"createdCallback",value:function(){this.getAttribute("width")&&this._updateWidth()}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name&&this._updateWidth()}},{key:"_updateWidth",value:function(){var width=this.getAttribute("width");"string"==typeof width&&(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,this.style.webkitBoxFlex="0",this.style.webkitFlex="0 0 "+width,this.style.mozBoxFlex="0",this.style.mozFlex="0 0 "+width,this.style.msFlex="0 0 "+width,this.style.flex="0 0 "+width,this.style.maxWidth=width)}}]),ColumnElement}(ons._BaseElement);window.OnsColElement||(window.OnsColElement=document.registerElement("ons-col",{prototype:ColumnElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".dialog":"dialog--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidDialogAnimator=ons._internal.AndroidDialogAnimator,IOSDialogAnimator=ons._internal.IOSDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,DialogAnimator=ons._internal.DialogAnimator,templateSource=util.createElement('\n <div>\n <div class="dialog-mask"></div>\n <div class="dialog"></div>\n </div>\n '),_animatorDict={"default":ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,fade:ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,slide:SlideDialogAnimator,none:DialogAnimator},DialogElement=function(_ons$_BaseElement){function DialogElement(){_classCallCheck(this,DialogElement),_get(Object.getPrototypeOf(DialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(DialogElement,_ons$_BaseElement),_createClass(DialogElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:DialogAnimator,baseClassName:"DialogAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"_compile",value:function(){var style=this.getAttribute("style");this.style.display="none";var template=templateSource.cloneNode(!0),dialog=template.children[1];for(style&&dialog.setAttribute("style",style);this.firstChild;)dialog.appendChild(this.firstChild);for(;template.firstChild;)this.appendChild(template.firstChild);this._dialog.style.zIndex=20001,this._mask.style.zIndex=2e4,this.setAttribute("no-status-bar-fill","")}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this,"cancel")}})}},{key:"show",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"preshow",{dialog:this,cancel:function(){_cancel2=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock();_this2.style.display="block",_this2._mask.style.opacity="1";var animator=_this2._animatorFactory.newAnimator(options);animator.show(_this2,function(){_this2._visible=!0,unlock(),util.triggerElementEvent(_this2,"postshow",{dialog:_this2}),callback()})})}},{key:"hide",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{dialog:this,cancel:function(){_cancel3=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock(),animator=_this3._animatorFactory.newAnimator(options);animator.hide(_this3,function(){_this3.style.display="none",_this3._visible=!1,unlock(),util.triggerElementEvent(_this3,"posthide",{dialog:_this3}),callback()})})}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"isShown",value:function(){return this._visible}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_mask",get:function(){return util.findChild(this,".dialog-mask")}},{key:"_dialog",get:function(){return util.findChild(this,".dialog")}}]),DialogElement}(ons._BaseElement);window.OnsDialogElement||(window.OnsDialogElement=document.registerElement("ons-dialog",{prototype:DialogElement.prototype}),window.OnsDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof DialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"fab--*"},ModifierUtil=ons._internal.ModifierUtil,FabElement=function(_ons$_BaseElement){function FabElement(){_classCallCheck(this,FabElement),_get(Object.getPrototypeOf(FabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(FabElement,_ons$_BaseElement),_createClass(FabElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this._updatePosition(),this.show()}},{key:"_compile",value:function(){var content=document.createElement("span");content.classList.add("fab__icon");ons._util.arrayFrom(this.childNodes).forEach(function(element){return content.appendChild(element)});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("position"===name&&this._updatePosition())}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(1)",this.style.webkitTransform="scale(1)"}},{key:"hide",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(0)",this.style.webkitTransform="scale(0)"}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return"scale(1)"===this.style.transform&&"none"!==this.style.display}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}}]),FabElement}(ons._BaseElement);window.OnsFabElement||(window.OnsFabElement=document.registerElement("ons-fab",{prototype:FabElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var GestureDetectorElement=function(_ons$_BaseElement){function GestureDetectorElement(){_classCallCheck(this,GestureDetectorElement),_get(Object.getPrototypeOf(GestureDetectorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(GestureDetectorElement,_ons$_BaseElement),_createClass(GestureDetectorElement,[{key:"createdCallback",value:function(){this._gestureDetector=new ons.GestureDetector(this)}}]),GestureDetectorElement}(ons._BaseElement);window.OnsGestureDetectorElement||(window.OnsGestureDetectorElement=document.registerElement("ons-gesture-detector",{prototype:GestureDetectorElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var IconElement=function(_ons$_BaseElement){function IconElement(){_classCallCheck(this,IconElement),_get(Object.getPrototypeOf(IconElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(IconElement,_ons$_BaseElement),_createClass(IconElement,[{key:"createdCallback",value:function(){this._update()}},{key:"attributeChangedCallback",value:function(name,last,current){-1!==["icon","size"].indexOf(name)&&this._update()}},{key:"_update",value:function(){var _this=this;this._cleanClassAttribute();var builded=this._buildClassAndStyle(this);for(var key in builded.style)builded.style.hasOwnProperty(key)&&(this.style[key]=builded.style[key]);builded.classList.forEach(function(className){return _this.classList.add(className)})}},{key:"_cleanClassAttribute",value:function(){var classList=this.classList;Array.apply(null,this.classList).filter(function(klass){return"fa"===klass||0===klass.indexOf("fa-")||0===klass.indexOf("ion-")||0===klass.indexOf("zmdi-")}).forEach(function(className){classList.remove(className)}),classList.remove("zmdi"),classList.remove("ons-icon--ion")}},{key:"_buildClassAndStyle",value:function(){var classList=["ons-icon"],style={},iconName=this._iconName;0===iconName.indexOf("ion-")?(classList.push(iconName),classList.push("ons-icon--ion")):0===iconName.indexOf("fa-")?(classList.push(iconName),classList.push("fa")):0===iconName.indexOf("md-")?(classList.push("zmdi"),classList.push("zmdi-"+iconName.split(/\-(.+)?/)[1])):(classList.push("fa"),classList.push("fa-"+iconName));var size=""+this.getAttribute("size");return size.match(/^[1-5]x|lg$/)?(classList.push("fa-"+size),this.style.removeProperty("font-size")):style.fontSize=size,{classList:classList,style:style}}},{key:"_iconName",get:function(){return""+this.getAttribute("icon")}}]),IconElement}(ons._BaseElement);window.OnsIconElement||(window.OnsIconElement=document.registerElement("ons-icon",{prototype:IconElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__header--*"},ModifierUtil=ons._internal.ModifierUtil,ListHeaderElement=function(_ons$_BaseElement){function ListHeaderElement(){_classCallCheck(this,ListHeaderElement),_get(Object.getPrototypeOf(ListHeaderElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListHeaderElement,_ons$_BaseElement),_createClass(ListHeaderElement,[{key:"createdCallback",value:function(){this.classList.add("list__header"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListHeaderElement}(ons._BaseElement);window.OnsListHeaderElement||(window.OnsListHeaderElement=document.registerElement("ons-list-header",{prototype:ListHeaderElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__item--*"},ModifierUtil=ons._internal.ModifierUtil,ListItemElement=function(_ons$_BaseElement){function ListItemElement(){_classCallCheck(this,ListItemElement),_get(Object.getPrototypeOf(ListItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListItemElement,_ons$_BaseElement),_createClass(ListItemElement,[{key:"createdCallback",value:function(){this.classList.add("list__item"),ModifierUtil.initModifier(this,scheme),this._gestureDetector=new ons.GestureDetector(this),this._boundOnDrag=this._onDrag.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("drag",this._boundOnDrag)}},{key:"detachedCallback",value:function(){this.removeEventListener("drag",this._boundOnDrag)}},{key:"_onDrag",value:function(event){var g=event.gesture;this._shouldLockOnDrag()&&["left","right"].indexOf(g.direction)>-1&&g.preventDefault()}},{key:"_shouldLockOnDrag",value:function(){return this.hasAttribute("lock-on-drag")}}]),ListItemElement}(ons._BaseElement);window.OnsListItemElement||(window.OnsListItemElement=document.registerElement("ons-list-item",{prototype:ListItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list--*"},ModifierUtil=ons._internal.ModifierUtil,ListElement=function(_ons$_BaseElement){function ListElement(){_classCallCheck(this,ListElement),_get(Object.getPrototypeOf(ListElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListElement,_ons$_BaseElement),_createClass(ListElement,[{key:"createdCallback",value:function(){this.classList.add("list"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListElement}(ons._BaseElement);window.OnsListElement||(window.OnsListElement=document.registerElement("ons-list",{prototype:ListElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".text-input--material":"text-input--material--*",".text-input--material__label":"text-input--material__label--*"},ModifierUtil=ons._internal.ModifierUtil,INPUT_ATTRIBUTES=["autocapitalize","autocomplete","autocorrect","autofocus","disabled","inputmode","max","maxlength","min","minlength","name","pattern","placeholder","readonly","size","step","type","validator","value"],MaterialInputElement=function(_ons$_BaseElement){function MaterialInputElement(){_classCallCheck(this,MaterialInputElement),_get(Object.getPrototypeOf(MaterialInputElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(MaterialInputElement,_ons$_BaseElement),_createClass(MaterialInputElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateLabel(),this._updateLabelColor(),this._updateBoundAttributes(),this._boundOnInput=this._onInput.bind(this),this._boundOnFocusin=this._onFocusin.bind(this),this._boundOnFocusout=this._onFocusout.bind(this),this._boundDelegateEvent=this._delegateEvent.bind(this)}},{key:"_compile",value:function(){this._input||(this.appendChild(document.createElement("input")),this._input.classList.add("text-input--material"),this.appendChild(document.createElement("span")),this._label.classList.add("text-input--material__label"))}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):"label"===name?this._updateLabel():INPUT_ATTRIBUTES.indexOf(name)>=0?this._updateBoundAttributes():void 0}},{key:"attachedCallback",value:function(){this._input.addEventListener("input",this._boundOnInput),this._input.addEventListener("focusin",this._boundOnFocusin),this._input.addEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"detachedCallback",value:function(){this._input.removeEventListener("input",this._boundOnInput),this._input.removeEventListener("focusin",this._boundOnFocusin),this._input.removeEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"_setLabel",value:function(value){"undefined"!=typeof this._label.textContent?this._label.textContent=value:this._label.innerText=value}},{key:"_updateLabel",value:function(){this._setLabel(this.hasAttribute("label")?this.getAttribute("label"):"")}},{key:"_updateBoundAttributes",value:function(){var _this=this;INPUT_ATTRIBUTES.forEach(function(attr){_this.hasAttribute(attr)?_this._input.setAttribute(attr,_this.getAttribute(attr)):_this._input.removeAttribute(attr)})}},{key:"_updateLabelColor",value:function(){this.value.length>0&&this._input===document.activeElement?this._label.style.color="":this._label.style.color="rgba(0, 0, 0, 0.5)"}},{key:"_updateLabelClass",value:function(){""===this.value?this._label.classList.remove("text-input--material__label--active"):this._label.classList.add("text-input--material__label--active")}},{key:"_delegateEvent",value:function(event){var e=new CustomEvent(event.type,{bubbles:!1,cancelable:!0});return this.dispatchEvent(e)}},{key:"_onInput",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusin",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusout",value:function(event){this._updateLabelColor()}},{key:"_input",get:function(){return this.querySelector("input")}},{key:"_label",get:function(){return this.querySelector("span")}},{key:"value",get:function(){return this._input.value},set:function(val){return this._input.value=val,this._onInput(),this._input.val}}]),MaterialInputElement}(ons._BaseElement);window.OnsMaterialInputElement||(window.OnsMaterialInputElement=document.registerElement("ons-material-input",{prototype:MaterialInputElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"modal--*",modal__content:"modal--*__content"},AnimatorFactory=ons._internal.AnimatorFactory,ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=ons._internal.FadeModalAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":ModalAnimator,fade:FadeModalAnimator,none:ModalAnimator},ModalElement=function(_ons$_BaseElement){function ModalElement(){_classCallCheck(this,ModalElement),_get(Object.getPrototypeOf(ModalElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ModalElement,_ons$_BaseElement),_createClass(ModalElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:ModalAnimator,baseClassName:"ModalAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"getDeviceBackButtonHandler", value:function(){return this._deviceBackButtonHandler}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback),this._onDeviceBackButton=callback}},{key:"_onDeviceBackButton",value:function(){}},{key:"_compile",value:function(){this.style.display="none",this.classList.add("modal");var wrapper=document.createElement("div");for(wrapper.classList.add("modal__content");this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),wrapper.insertBefore(node,null)}this.appendChild(wrapper)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy()}},{key:"attachedCallback",value:function(){setImmediate(this._ensureNodePosition.bind(this)),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this))}},{key:"_ensureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerExtraElement(this)}}},{key:"isShown",value:function(){return"none"!==this.style.display}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock(),animator=_this._animatorFactory.newAnimator(options);_this.style.display="table",animator.show(_this,function(){unlock(),callback()})})}},{key:"toggle",value:function(){return this.isShown()?this.hide.apply(this,arguments):this.show.apply(this,arguments)}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",unlock(),callback()})})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ModalElement}(ons._BaseElement);window.OnsModalElement||(window.OnsModalElement=document.registerElement("ons-modal",{prototype:ModalElement.prototype}),window.OnsModalElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof ModalAnimator))throw new Error('"Animator" param must inherit ModalAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var AnimatorFactory=ons._internal.AnimatorFactory,NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=ons._internal.IOSSlideNavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=ons._internal.SimpleSlideNavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=ons._internal.LiftNavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=ons._internal.FadeNavigatorTransitionAnimator,NoneNavigatorTransitionAnimator=ons._internal.NoneNavigatorTransitionAnimator,util=ons._util,NavigatorPage=ons._internal.NavigatorPage,_animatorDict={"default":ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,slide:ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,simpleslide:SimpleSlideNavigatorTransitionAnimator,lift:LiftNavigatorTransitionAnimator,fade:FadeNavigatorTransitionAnimator,none:NoneNavigatorTransitionAnimator},rewritables={ready:function(navigatorElement,callback){callback()},link:function(navigatorElement,target,callback){callback(target)}},NavigatorElement=function(_ons$_BaseElement){function NavigatorElement(){_classCallCheck(this,NavigatorElement),_get(Object.getPrototypeOf(NavigatorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(NavigatorElement,_ons$_BaseElement),_createClass(NavigatorElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._pages=[],this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._isPushing=this._isPopping=!1,this._initialHTML=this.innerHTML,this.innerHTML="",this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:NavigatorTransitionAnimator,baseClassName:"NavigatorTransitionAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"canPopPage",value:function(){return this._pages.length>1}},{key:"replacePage",value:function(page,options){var _this=this;options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};return options.onTransitionEnd=function(){_this._pages.length>1&&_this._pages[_this._pages.length-2].destroy(),onTransitionEnd()},this.pushPage(page,options)}},{key:"popPage",value:function(options){var _this2=this;options=options||{},options.cancelIfRunning&&this._isPopping||(options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),this._doorLock.waitUnlock(function(){if(_this2._pages.length<=1)throw new Error("ons-navigator's page stack is empty.");if(!_this2._emitPrePopEvent()){var unlock=_this2._doorLock.lock();options.refresh?!function(){var index=_this2.pages.length-2;if(!_this2._pages[index].page)throw new Error("Refresh option cannot be used with pages directly inside the Navigator. Use ons-template instead.");ons._internal.getPageHTMLAsync(_this2._pages[index].page).then(function(templateHTML){var element=_this2._createPageElement(templateHTML),pageObject=_this2._createPageObject(_this2._pages[index].page,element,options);rewritables.link(_this2,element,function(element){_this2.insertBefore(element,_this2._pages[index]?_this2._pages[index].element:null),_this2._pages.splice(index,0,pageObject),_this2._pages[index+1].destroy(),_this2._popPage(options,unlock)})})}():_this2._popPage(options,unlock)}}))}},{key:"_popPage",value:function(options,unlock){var _this3=this;options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var leavePage=this._pages.pop(),enterPage=this._pages[this._pages.length-1];leavePage.element._hide(),enterPage&&(enterPage.element.style.display="block",enterPage.element._show());var eventDetail={leavePage:leavePage,enterPage:this._pages[this._pages.length-1],navigator:this},callback=function(){leavePage.destroy(),_this3._isPopping=!1,unlock();var event=util.triggerElementEvent(_this3,"postpop",eventDetail);event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()};this._isPopping=!0;var animator=this._animatorFactory.newAnimator(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)}},{key:"insertPage",value:function(index,page,options){var _this4=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);return index=this._normalizeIndex(index),index>=this.pages.length?this.pushPage.apply(this,[].slice.call(arguments,1)):void this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock();ons._internal.getPageHTMLAsync(page).then(function(templateHTML){var element=_this4._createPageElement(templateHTML),pageObject=_this4._createPageObject(page,element,options);rewritables.link(_this4,element,function(element){element.style.display="none",_this4.insertBefore(element,_this4._pages[index].element),_this4._pages.splice(index,0,pageObject),setTimeout(function(){unlock(),element=null},1e3/60)})})})}},{key:"_normalizeIndex",value:function(index){return 0>index&&(index=Math.abs(this.pages.length+index)%this.pages.length),index}},{key:"getCurrentPage",value:function(){if(this._pages.length<=0)throw new Error("Invalid state");return this._pages[this._pages.length-1]}},{key:"_show",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._show()}},{key:"_hide",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._hide()}},{key:"_destroy",value:function(){for(var i=this._pages.length-1;i>=0;i--)this._pages[i].destroy();this.remove()}},{key:"_onDeviceBackButton",value:function(event){this._pages.length>1?this.popPage():event.callParentHandler()}},{key:"resetToPage",value:function(page,options){var _this5=this;options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){for(;_this5._pages.length>1;)_this5._pages.shift().destroy();onTransitionEnd()},(void 0===page||""===page)&&(this.hasAttribute("page")?page=this.getAttribute("page"):(options.pageHTML=this._initialHTML,page="")),this.pushPage(page,options)}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){var _this6=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),rewritables.ready(this,function(){if(0===_this6._pages.length)if(_this6.getAttribute("page"))_this6.pushPage(_this6.getAttribute("page"),{animation:"none"});else{var element=_this6._createPageElement(_this6._initialHTML||"");_this6._pushPageDOM(_this6._createPageObject("",element,{}),function(){})}})}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null}},{key:"pushPage",value:function(page,options){var _this7=this;if(options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-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(){return _this7._pushPage(page,options)})}}},{key:"_pushPage",value:function(page,options){var _this8=this,unlock=this._doorLock.lock(),done=function(){unlock()},run=function(templateHTML){var element=_this8._createPageElement(templateHTML);_this8._pushPageDOM(_this8._createPageObject(page,element,options),done)};options.pageHTML?run(options.pageHTML):ons._internal.getPageHTMLAsync(page).then(run)}},{key:"_pushPageDOM",value:function(pageObject,unlock){var _this9=this;unlock=unlock||function(){};var element=pageObject.element,options=pageObject.options,eventDetail={enterPage:pageObject,leavePage:this._pages[this._pages.length-1],navigator:this};this._pages.push(pageObject);var done=function(){_this9._pages[_this9._pages.length-2]&&(_this9._pages[_this9._pages.length-2].element.style.display="none"),_this9._isPushing=!1,unlock(),util.triggerElementEvent(_this9,"postpush",eventDetail),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null};this._isPushing=!0,rewritables.link(this,element,function(element){CustomElements.upgrade(element),setTimeout(function(){if(_this9._pages.length>1){var leavePage=_this9._pages.slice(-2)[0],enterPage=_this9._pages.slice(-1)[0];_this9.appendChild(element),leavePage.element._hide(),enterPage.element._show(),options.animator.push(enterPage,leavePage,done)}else _this9.appendChild(element),element._show(),done()},1e3/60)})}},{key:"bringPageTop",value:function(item,options){var _this10=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(!(options.cancelIfRunning&&this._isPushing||this._emitPrePushEvent())){var index=void 0,page=void 0;if("string"==typeof item)page=item,index=this._lastIndexOfPage(page);else{if("number"!=typeof item)throw new Error("First argument must be a page name or the index of an existing page. You supplied "+item);if(index=this._normalizeIndex(item),item>=this._pages.length)throw new Error("The provided index does not match an existing page.");page=this._pages[index].page}0>index?this._doorLock.waitUnlock(function(){return _this10._pushPage(page,options)}):index<this._pages.length-1&&this._doorLock.waitUnlock(function(){var unlock=_this10._doorLock.lock(),done=function(){unlock()},pageObject=_this10._pages.splice(index,1)[0];pageObject.element.style.display="block",pageObject.element.setAttribute("_skipinit",""),options.animator=_this10._animatorFactory.newAnimator(options),pageObject.options=options,_this10._pushPageDOM(pageObject,done)})}}},{key:"_lastIndexOfPage",value:function(page){var index=void 0;for(index=this._pages.length-1;index>=0&&this._pages[index].page!==page;index--);return index}},{key:"_emitPrePushEvent",value:function(){var isCanceled=!1;return util.triggerElementEvent(this,"prepush",{navigator:this,currentPage:this._pages.length>0?this.getCurrentPage():void 0,cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_emitPrePopEvent",value:function(){var isCanceled=!1,leavePage=this.getCurrentPage();return util.triggerElementEvent(this,"prepop",{navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this._pages[this._pages.length-2],cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_createPageObject",value:function(page,element,options){return options.animator=this._animatorFactory.newAnimator(options),new NavigatorPage({page:page,element:element,options:options,navigator:this})}},{key:"_createPageElement",value:function(templateHTML){var pageElement=util.createElement(ons._internal.normalizePageHTML(templateHTML));if("ons-page"!==pageElement.nodeName.toLowerCase())throw new Error('You must supply an "ons-page" element to "ons-navigator".');return pageElement}},{key:"pages",get:function(){return this._pages.slice(0)}}]),NavigatorElement}(ons._BaseElement);window.OnsNavigatorElement||(window.OnsNavigatorElement=document.registerElement("ons-navigator",{prototype:NavigatorElement.prototype}),window.OnsNavigatorElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof NavigatorTransitionAnimator))throw new Error('"Animator" param must inherit NavigatorTransitionAnimator');_animatorDict[name]=Animator},window.OnsNavigatorElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"page--*",".page__content":"page--*__content",".page__background":"page--*__background"},ModifierUtil=ons._internal.ModifierUtil,nullToolbarElement=document.createElement("ons-toolbar"),util=ons._util,PageElement=function(_ons$_BaseElement){function PageElement(){_classCallCheck(this,PageElement),_get(Object.getPrototypeOf(PageElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PageElement,_ons$_BaseElement),_createClass(PageElement,[{key:"createdCallback",value:function(){this.classList.add("page"),this._compile(),ModifierUtil.initModifier(this,scheme),this._isShown=!1,this._isMuted=this.hasAttribute("_muted"),this._skipInit=this.hasAttribute("_skipinit"),this.eventDetail={page:this}}},{key:"attachedCallback",value:function(){this._isMuted||(this._skipInit?this.removeAttribute("_skipinit"):util.triggerElementEvent(this,"init",this.eventDetail)),util.hasAnyComponentAsParent(this)||this._show()}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler||null}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback)}},{key:"_getContentElement",value:function(){var result=ons._util.findChild(this,".page__content");if(result)return result;throw Error('fail to get ".page__content" element.')}},{key:"_hasToolbarElement",value:function(){return!!ons._util.findChild(this,"ons-toolbar")}},{key:"_canAnimateToolbar",value:function(){var toolbar=ons._util.findChild(this,"ons-toolbar");if(toolbar)return!0;for(var elements=this._getContentElement().children,i=0;i<elements.length;i++)if("ons-toolbar"===elements[i].nodeName.toLowerCase()&&!elements[i].hasAttribute("inline"))return!0;return!1}},{key:"_getBackgroundElement",value:function(){var result=ons._util.findChild(this,".page__background");if(result)return result;throw Error('fail to get ".page__background" element.')}},{key:"_getBottomToolbarElement",value:function(){return ons._util.findChild(this,"ons-bottom-toolbar")||ons._internal.nullElement}},{key:"_getToolbarElement",value:function(){return ons._util.findChild(this,"ons-toolbar")||nullToolbarElement}},{key:"_registerToolbar",value:function(element){this._getContentElement().setAttribute("no-status-bar-fill",""),ons._util.findChild(this,".page__status-bar-fill")?this.insertBefore(element,this.children[1]):this.insertBefore(element,this.children[0])}},{key:"_registerBottomToolbar",value:function(element){if(!ons._util.findChild(this,".page__status-bar-fill")){var fill=document.createElement("div");fill.classList.add("page__bottom-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0]),this.insertBefore(element,null)}}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("_muted"===name?this._isMuted=this.hasAttribute("_muted"):"_skipinit"===name&&(this._skipInit=this.hasAttribute("_skipinit")))}},{key:"_compile",value:function(){if(!ons._util.findChild(this,".page__background")||!ons._util.findChild(this,".page__content")){var background=document.createElement("div");background.classList.add("page__background");var content=document.createElement("div");for(content.classList.add("page__content");this.childNodes[0];)content.appendChild(this.childNodes[0]);this.hasAttribute("style")&&(background.setAttribute("style",this.getAttribute("style")),this.removeAttribute("style",null));var fragment=document.createDocumentFragment();fragment.appendChild(background),fragment.appendChild(content),this.appendChild(fragment)}}},{key:"_registerExtraElement",value:function(element){var extra=ons._util.findChild(this,".page__extra");extra||(extra=document.createElement("div"),extra.classList.add("page__extra"),extra.style.zIndex="10001",this.insertBefore(extra,null)),extra.insertBefore(element,null)}},{key:"_tryToFillStatusBar",value:function(){if(ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("page__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_show",value:function(){!this.isShown&&ons._util.isAttached(this)&&(this.isShown=!0,this._isMuted||util.triggerElementEvent(this,"show",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_show"))}},{key:"_hide",value:function(){this.isShown&&(this.isShown=!1,this._isMuted||util.triggerElementEvent(this,"hide",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_hide"))}},{key:"_destroy",value:function(){this._hide(),this._isMuted||util.triggerElementEvent(this,"destroy",this.eventDetail),this.getDeviceBackButtonHandler()&&this.getDeviceBackButtonHandler().destroy(),ons._util.propagateAction(this._getContentElement(),"_destroy"),this.remove()}},{key:"isShown",get:function(){return this._isShown},set:function(value){this._isShown=value}}]),PageElement}(ons._BaseElement);window.OnsPageElement||(window.OnsPageElement=document.registerElement("ons-page",{prototype:PageElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".popover":"popover--*",".popover__content":"popover__content--*"},PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=ons._internal.FadePopoverAnimator,templateSource=util.createElement('\n <div>\n <div class="popover-mask"></div>\n <div class="popover">\n <div class="popover__content"></div>\n <div class="popover__arrow"></div>\n </div>\n </div>\n '),AnimatorFactory=ons._internal.AnimatorFactory,_animatorDict={fade:FadePopoverAnimator,none:PopoverAnimator},PopoverElement=function(_ons$_BaseElement){function PopoverElement(){_classCallCheck(this,PopoverElement),_get(Object.getPrototypeOf(PopoverElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PopoverElement,_ons$_BaseElement),_createClass(PopoverElement,[{key:"createdCallback",value:function(){this._compile(),this.style.display="none",ModifierUtil.initModifier(this,scheme),this._mask.style.zIndex="20000",this._popover.style.zIndex="20001",this.hasAttribute("mask-color")&&(this._mask.style.backgroundColor=this.getAttribute("mask-color")),this._visible=!1,this._doorLock=new DoorLock,this._boundOnChange=this._onChange.bind(this),this._boundCancel=this._cancel.bind(this),this._animatorFactory=this._createAnimatorFactory()}},{key:"_createAnimatorFactory",value:function(){return new AnimatorFactory({animators:_animatorDict,baseClass:PopoverAnimator,baseClassName:"PopoverAnimator",defaultAnimation:this.getAttribute("animation")||"fade"})}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_setDirection",value:function(direction){var arrowPosition=void 0;if("up"===direction)arrowPosition="bottom";else if("left"===direction)arrowPosition="right";else if("down"===direction)arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");arrowPosition="left"}var popoverClassList=this._popover.classList;popoverClassList.remove("popover--up"),popoverClassList.remove("popover--down"),popoverClassList.remove("popover--left"),popoverClassList.remove("popover--right"),popoverClassList.add("popover--"+direction);var arrowClassList=this._arrow.classList;arrowClassList.remove("popover__top-arrow"),arrowClassList.remove("popover__bottom-arrow"),arrowClassList.remove("popover__left-arrow"),arrowClassList.remove("popover__right-arrow"),arrowClassList.add("popover__"+arrowPosition+"-arrow")}},{key:"_positionPopoverByDirection",value:function(target,direction){var el=this._popover,pos=target.getBoundingClientRect(),own=el.getBoundingClientRect(),arrow=el.children[1],offset=14,margin=6,radius=parseInt(window.getComputedStyle(el.querySelector(".popover__content")).borderRadius);arrow.style.top="",arrow.style.left="",this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.style.left=pos.right-pos.width-own.width-offset+"px":el.style.left=pos.right+offset+"px",el.style.top=pos.bottom-pos.height/2-own.height/2+"px"):("up"==direction?el.style.top=pos.bottom-pos.height-own.height-offset+"px":el.style.top=pos.bottom+offset+"px",el.style.left=pos.right-pos.width/2-own.width/2+"px"),own=el.getBoundingClientRect();var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow).width)),limit=margin+radius+diff+2;["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.style.top=Math.max(own.height/2+own.top-margin,limit)+"px",el.style.top=margin+"px"):own.bottom>window.innerHeight-margin&&(arrow.style.top=Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px",el.style.top=window.innerHeight-own.height-margin+"px"):own.left<margin?(arrow.style.left=Math.max(own.width/2+own.left-margin,limit)+"px",el.style.left=margin+"px"):own.right>window.innerWidth-margin&&(arrow.style.left=Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px",el.style.left=window.innerWidth-own.width-margin+"px"),el.removeAttribute("data-animit-orig-style")}},{key:"_positionPopover",value:function(target){for(var _this=this,directions=function(){return _this.hasAttribute("direction")?_this.getAttribute("direction").split(/\s+/):["up","down","left","right"]}(),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)}}},{key:"_onChange",value:function(){var _this2=this;setImmediate(function(){_this2._currentTarget&&_this2._positionPopover(_this2._currentTarget)})}},{key:"_compile",value:function(){var templateElement=templateSource.cloneNode(!0),content=templateElement.querySelector(".popover__content"),style=this.getAttribute("style");for(style&&this.removeAttribute("style");this.childNodes[0];)content.appendChild(this.childNodes[0]);for(;templateElement.children[0];)this.appendChild(templateElement.children[0]);style&&this._popover.setAttribute("style",style)}},{key:"show",value:function(target,options){var _this3=this;if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");if(options=options||{},options.animation&&!(options.animation in _animatorDict))throw new Error("Animator "+options.animation+" is not registered.");options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var canceled=!1;util.triggerElementEvent(this,"preshow",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock();_this3.style.display="block",_this3._currentTarget=target,_this3._positionPopover(target);var animator=_this3._animatorFactory.newAnimator(options);animator.show(_this3,function(){_this3._visible=!0,unlock(),util.triggerElementEvent(_this3,"postshow",{popover:_this3})})})}},{key:"hide",value:function(options){var _this4=this;options=options||{};var canceled=!1;util.triggerElementEvent(this,"prehide",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock(),animator=_this4._animatorFactory.newAnimator(options);animator.hide(_this4,function(){_this4.style.display="none",_this4._visible=!1,unlock(),util.triggerElementEvent(_this4,"posthide",{popover:_this4})})})}},{key:"isShown",value:function(){return this._visible}},{key:"attachedCallback",value:function(){this._mask.addEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._popover.addEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.addEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.addEventListener("resize",this._boundOnChange,!1)}},{key:"detachedCallback",value:function(){this._mask.removeEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._popover.removeEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.removeEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.removeEventListener("resize",this._boundOnChange,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._boundOnChange():("animation"===name||"animation-options"===name)&&(this._animatorFactory=this._createAnimatorFactory()))}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"_cancel",value:function(){this.isCancelable()&&this.hide()}},{key:"_mask",get:function(){return this.children[0]}},{key:"_popover",get:function(){return this.children[1]}},{key:"_content",get:function(){return this._popover.children[0]}},{key:"_arrow",get:function(){return this._popover.children[1]}}]),PopoverElement}(ons._BaseElement);window.OnsPopoverElement||(window.OnsPopoverElement=document.registerElement("ons-popover",{prototype:PopoverElement.prototype}),window.OnsPopoverElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof PopoverAnimator))throw new Error('"Animator" param must inherit PopoverAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0), Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".progress-bar":"progress-bar--*",".progress-circular":"progress-circular--*",".progress-circular__primary":"progress-circular__primary--*",".progress-circular__secondary":"progress-circular__secondary--*",".progress-bar__primary":"progress-bar__primary--*",".progress-bar__secondary":"progress-bar__secondary--*"},barTemplate=util.createElement('\n <div class="progress-bar">\n <div class="progress-bar__secondary"></div>\n <div class="progress-bar__primary"></div>\n </div>\n '),circularTemplate=util.createElement('\n <svg class="progress-circular">\n <circle class="progress-circular__secondary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n <circle class="progress-circular__primary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n </svg>\n '),ProgressElement=function(_ons$_BaseElement){function ProgressElement(){_classCallCheck(this,ProgressElement),_get(Object.getPrototypeOf(ProgressElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ProgressElement,_ons$_BaseElement),_createClass(ProgressElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme);if("value"===name||"secondary-value"===name)this._updateValue();else{if("type"===name)throw new Error("Can not change type attribute.");"indeterminate"===name&&this._updateDeterminate()}}},{key:"_updateDeterminate",value:function(){this.hasAttribute("indeterminate")?(this._template.classList.add("progress-"+this._type+"--indeterminate"),this._template.classList.remove("progress-"+this._type+"--determinate")):(this._template.classList.add("progress-"+this._type+"--determinate"),this._template.classList.remove("progress-"+this._type+"--indeterminate"))}},{key:"_updateValue",value:function(){if("bar"===this._type)this._primary.style.width=this.hasAttribute("value")?this.getAttribute("value")+"%":"0%",this._secondary.style.width=this.hasAttribute("secondary-value")?this.getAttribute("secondary-value")+"%":"0%";else{if(this.hasAttribute("value")){var per=Math.ceil(251.32*this.getAttribute("value")*.01);this._primary.style["stroke-dasharray"]=per+"%, 251.32%"}if(this.hasAttribute("secondary-value")){var per=Math.ceil(251.32*this.getAttribute("secondary-value")*.01);this._secondary.style["stroke-dasharray"]=per+"%, 251.32%"}}}},{key:"_compile",value:function(){"bar"===this._type?this._template=barTemplate.cloneNode(!0):this._template=circularTemplate.cloneNode(!0),this._primary=this._template.childNodes[3],this._secondary=this._template.childNodes[1],this._updateDeterminate(),this._updateValue(),this.appendChild(this._template)}},{key:"_type",get:function(){return this.hasAttribute("type")&&"circular"===this.getAttribute("type")?"circular":"bar"}}]),ProgressElement}(ons._BaseElement);window.OnsProgressElement||(window.OnsProgressElement=document.registerElement("ons-progress",{prototype:ProgressElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var STATE_INITIAL="initial",STATE_PREACTION="preaction",STATE_ACTION="action",util=ons._util,PullHookElement=function(_ons$_BaseElement){function PullHookElement(){_classCallCheck(this,PullHookElement),_get(Object.getPrototypeOf(PullHookElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PullHookElement,_ons$_BaseElement),_createClass(PullHookElement,[{key:"createdCallback",value:function(){if(this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parentElement,!this._pageElement.classList.contains("page__content")&&!this._pageElement.classList.contains("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragStart=this._onDragStart.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnScroll=this._onScroll.bind(this),this._currentTranslation=0,this._setState(STATE_INITIAL,!0),this._setStyle()}},{key:"_createScrollElement",value:function(){var scrollElement=util.createElement('<div class="scroll"><div>'),pageElement=this.parentElement;for(scrollElement.appendChild(this);pageElement.firstChild;)scrollElement.appendChild(pageElement.firstChild);return pageElement.appendChild(scrollElement),scrollElement}},{key:"_setStyle",value:function(){var height=this.getHeight();this.style.top="-"+height+"px",this.style.height=height+"px",this.style.lineHeight=height+"px"}},{key:"_onScroll",value:function(event){var element=this._pageElement;element.scrollTop<0&&(element.scrollTop=0)}},{key:"_generateTranslationTransform",value:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"}},{key:"_onDrag",value:function(event){var _this=this;if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var element=this._pageElement;if(element.scrollTop=this._startScroll-event.gesture.deltaY,element.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=Math.max(event.gesture.deltaY-this._startScroll,0);this._thresholdHeightEnabled()&&scroll>=this.getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){_this._setState(STATE_ACTION),_this._translateTo(_this.getHeight(),{animate:!0}),_this._waitForAction(_this._onDone.bind(_this))})):scroll>=this.getHeight()?this._setState(STATE_PREACTION):this._setState(STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}}},{key:"_onDragStart",value:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())}},{key:"_onDragEnd",value:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var _scroll=this._currentTranslation;_scroll>this.getHeight()?(this._setState(STATE_ACTION),this._translateTo(this.getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}}},{key:"setActionCallback",value:function(callback){this._callback=callback}},{key:"_waitForAction",value:function(done){this._callback instanceof Function?this._callback.call(null,done):done()}},{key:"_onDone",value:function(done){this._translateTo(0,{animate:!0}),this._setState(STATE_INITIAL)}},{key:"getHeight",value:function(){return parseInt(this.getAttribute("height")||"64",10)}},{key:"setHeight",value:function(height){this.setAttribute("height",height+"px"),this._setStyle()}},{key:"setThresholdHeight",value:function(thresholdHeight){this.setAttribute("threshold-height",thresholdHeight+"px")}},{key:"getThresholdHeight",value:function(){return parseInt(this.getAttribute("threshold-height")||"96",10)}},{key:"_thresholdHeightEnabled",value:function(){var th=this.getThresholdHeight();return th>0&&th>=this.getHeight()}},{key:"_setState",value:function(state,noEvent){var lastState=this._getState();this.setAttribute("state",state),noEvent||lastState===this._getState()||util.triggerElementEvent(this,"changestate",{pullHook:this,state:state,lastState:lastState})}},{key:"_getState",value:function(){return this.getAttribute("state")}},{key:"getCurrentState",value:function(){return this._getState()}},{key:"_getCurrentScroll",value:function(){return this._pageElement.scrollTop}},{key:"getPullDistance",value:function(){return this._currentTranslation}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"_isContentFixed",value:function(){return this.hasAttribute("fixed-content")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"_getScrollableElement",value:function(){return this._isContentFixed()?this:this._scrollElement}},{key:"_translateTo",value:function(scroll){var _this2=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(0!=this._currentTranslation||0!=scroll){var done=function(){0===scroll&&_this2._getScrollableElement().removeAttribute("style"),options.callback&&options.callback()};this._currentTranslation=scroll,options.animate?animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(done):animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)}).play(done)}}},{key:"_getMinimumScroll",value:function(){var scrollHeight=this._scrollElement.getBoundingClientRect().height,pageHeight=this._pageElement.getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0}},{key:"_createEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this._pageElement,{dragMinDistance:1,dragDistanceCorrection:!1}),this._gestureDetector.on("drag",this._boundOnDrag),this._gestureDetector.on("dragstart",this._boundOnDragStart),this._gestureDetector.on("dragend",this._boundOnDragEnd),this._scrollElement.parentElement.addEventListener("scroll",this._boundOnScroll,!1)}},{key:"_destroyEventListeners",value:function(){this._gestureDetector.off("drag",this._boundOnDrag),this._gestureDetector.off("dragstart",this._boundOnDragStart),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),this._gestureDetector=null,this._scrollElement.parentElement.removeEventListener("scroll",this._boundOnScroll,!1)}},{key:"attachedCallback",value:function(){this._createEventListeners()}},{key:"detachedCallback",value:function(){this._destroyEventListeners()}},{key:"attributeChangedCallback",value:function(name,last,current){}}]),PullHookElement}(ons._BaseElement);window.OnsPullHookElement||(window.OnsPullHookElement=document.registerElement("ons-pull-hook",{prototype:PullHookElement.prototype}),window.OnsPullHookElement.STATE_ACTION=STATE_ACTION,window.OnsPullHookElement.STATE_INITIAL=STATE_INITIAL,window.OnsPullHookElement.STATE_PREACTION=STATE_PREACTION)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var RippleElement=function(_ons$_BaseElement){function RippleElement(){_classCallCheck(this,RippleElement),_get(Object.getPrototypeOf(RippleElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(RippleElement,_ons$_BaseElement),_createClass(RippleElement,[{key:"createdCallback",value:function(){this.classList.add("ripple"),this._compile(),this._boundOnClick=this._onMouseDown.bind(this)}},{key:"_compile",value:function(){this._wave=document.createElement("span"),this._wave.classList.add("ripple__wave"),this.insertBefore(this._wave,this.children[0]),this.hasAttribute("color")&&(this._wave.style.background=this.getAttribute("color"))}},{key:"_updateTarget",value:function(){this.hasAttribute("target")&&"children"===this.getAttribute("target")?(this._target=this,this.style.display="inline-block",this.style.position="relative"):(this._target=this.parentNode,"static"===window.getComputedStyle(this._target).getPropertyValue("position")&&(this._target.style.position="relative"),this.style.display="block",this.style.position="absolute")}},{key:"_updateCenter",value:function(){this.hasAttribute("center")?this._center=!0:this._center=!1,this._wave.classList.remove("ripple__wave--done-center"),this._wave.classList.remove("ripple__wave--animate-center"),this._wave.classList.remove("ripple__wave--done"),this._wave.classList.remove("ripple__wave--animate")}},{key:"attributeChangedCallback",value:function(name,last,current){"target"===name&&this._updateTarget(),"color"===name&&(this._wave.style.background=current),"center"===name&&this._updateCenter()}},{key:"_isTouchDevice",value:function(){return"ontouchstart"in window||"onmsgesturechange"in window}},{key:"_addListener",value:function(){this._isTouchDevice()?this.addEventListener("touchstart",this._boundOnClick):this.addEventListener("mousedown",this._boundOnClick)}},{key:"_removeListener",value:function(){this._isTouchDevice()?this.removeEventListener("touchstart",this._boundOnClick):this.removeEventListener("mousedown",this._boundOnClick)}},{key:"attachedCallback",value:function(){this._updateCenter(),this._updateTarget(),this._addListener()}},{key:"detachedCallback",value:function(){this._removeListener()}},{key:"_onMouseDown",value:function(e){var _this=this,eventType=e.type,wave=this._wave,el=this._target,pos=el.getBoundingClientRect();if(!this.isDisabled()){this._center?(wave.classList.remove("ripple__wave--done-center"),wave.classList.remove("ripple__wave--animate-center")):(wave.classList.remove("ripple__wave--done"),wave.classList.remove("ripple__wave--animate"));var animationEnded=new Promise(function(resolve){var onAnimationEnd=function onAnimationEnd(){_this.removeEventListener("webkitAnimationEnd",onAnimationEnd),_this.removeEventListener("animationend",onAnimationEnd),resolve()};_this.addEventListener("webkitAnimationEnd",onAnimationEnd),_this.addEventListener("animationend",onAnimationEnd)}),mouseReleased=new Promise(function(resolve){var onMouseUp=function onMouseUp(){document.removeEventListener("webkitAnimationEnd",onMouseUp),document.removeEventListener("animationend",onMouseUp),resolve()};document.addEventListener("mouseup",onMouseUp),document.addEventListener("touchend",onMouseUp)});Promise.all([animationEnded,mouseReleased]).then(function(){_this._center?(wave.classList.remove("ripple__wave--animate-center"),wave.classList.add("ripple__wave--done-center")):(wave.classList.remove("ripple__wave--animate"),wave.classList.add("ripple__wave--done"))});var x=e.clientX,y=e.clientY;"touchstart"===eventType&&(x=e.changedTouches[0].clientX,y=e.changedTouches[0].clientY);var sizeX=void 0,sizeY=0;this._center?(sizeX=el.offsetWidth,sizeY=el.offsetHeight,sizeX=sizeX-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-left-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-right-width")),sizeY=sizeY-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-top-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-bottom-width"))):sizeX=sizeY=Math.max(el.offsetWidth,el.offsetHeight),wave.style.width=sizeX+"px",wave.style.height=sizeY+"px",x=x-pos.left-sizeX/2,y=y-pos.top-sizeY/2,wave.style.left=x+"px",wave.style.top=y+"px",this._center?wave.classList.add("ripple__wave--animate-center"):wave.classList.add("ripple__wave--animate")}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}}]),RippleElement}(ons._BaseElement);window.OnsRippleElement||(window.OnsRippleElement=document.registerElement("ons-ripple",{prototype:RippleElement.prototype}))}(),window.OnsRowElement=window.OnsRowElement?window.OnsRowElement:document.registerElement("ons-row"),window.OnsScrollerElement=window.OnsScrollerElement?window.OnsScrollerElement:document.registerElement("ons-scroller");var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial__item--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialItemElement=function(_ons$_BaseElement){function SpeedDialItemElement(){_classCallCheck(this,SpeedDialItemElement),_get(Object.getPrototypeOf(SpeedDialItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialItemElement,_ons$_BaseElement),_createClass(SpeedDialItemElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this.classList.add("fab--mini"),this.classList.add("speed-dial__item"),this._boundOnClick=this._onClick.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){e.stopPropagation()}}]),SpeedDialItemElement}(ons._BaseElement);window.OnsSpeedDialItemElement||(window.OnsSpeedDialItemElement=document.registerElement("ons-speed-dial-item",{prototype:SpeedDialItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialElement=function(_ons$_BaseElement){function SpeedDialElement(){_classCallCheck(this,SpeedDialElement),_get(Object.getPrototypeOf(SpeedDialElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialElement,_ons$_BaseElement),_createClass(SpeedDialElement,[{key:"createdCallback",value:function(){this._compile(),this._shown=!0,this._itemShown=!1,ModifierUtil.initModifier(this,scheme),this._boundOnClick=this._onClick.bind(this),this.classList.add("speed__dial"),this.hasAttribute("direction")?this._updateDirection(this.getAttribute("direction")):this._updateDirection("up"),this._updatePosition(),this.hasAttribute("disabled")&&this.setDisabled(!0)}},{key:"_compile",value:function(){var content=document.createElement("ons-fab");ons._util.arrayFrom(this.childNodes).forEach(function(element){return"ons-speed-dial-item"!==element.nodeName.toLowerCase()?content.firstChild.appendChild(element):!0});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._updateDirection(current):"position"===name?this._updatePosition():"disabled"===name&&(null!==current?this.setDisabled(!0):this.setDisabled(!1)))}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){this.isDisabled()||this.toggleItems()}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updateDirection",value:function(direction){for(var children=this.items,i=0;i<children.length;i++)children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms",children[i].style.bottom="auto",children[i].style.right="auto",children[i].style.top="auto",children[i].style.left="auto";switch(direction){case"up":for(var i=0;i<children.length;i++)children[i].style.bottom=72+56*i+"px",children[i].style.right="8px";break;case"down":for(var i=0;i<children.length;i++)children[i].style.top=72+56*i+"px",children[i].style.left="8px";break;case"left":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.right=72+56*i+"px";break;case"right":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.left=72+56*i+"px";break;default:throw new Error("Argument must be one of up, down, left or right.")}}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.querySelector("ons-fab").show(),this._shown=!0}},{key:"hide",value:function(){var _this=this;arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.hideItems(),setTimeout(function(){_this.querySelector("ons-fab").hide()},200),this._shown=!1}},{key:"showItems",value:function(){if(!this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(1)",children[i].style.webkitTransform="scale(1)",children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms";this._itemShown=!0}},{key:"hideItems",value:function(){if(this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(0)",children[i].style.webkitTransform="scale(0)",children[i].style.transitionDelay=25*(children.length-i)+"ms",children[i].style.webkitTransitionDelay=25*(children.length-i)+"ms";this._itemShown=!1}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?(this.hideItems(),this.setAttribute("disabled",""),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.setAttribute("disabled",""):!0})):(this.removeAttribute("disabled"),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.removeAttribute("disabled"):!0}))}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return this._shown&&"none"!==this.style.display}},{key:"isItemShown",value:function(){return this._itemShown}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}},{key:"toggleItems",value:function(){this.isItemShown()?this.hideItems():this.showItems()}},{key:"items",get:function(){return ons._util.arrayFrom(this.querySelectorAll("ons-speed-dial-item"))}}]),SpeedDialElement}(ons._BaseElement);window.OnsSpeedDialElement||(window.OnsSpeedDialElement=document.registerElement("ons-speed-dial",{prototype:SpeedDialElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},SplitterContentElement=function(_ons$_BaseElement){function SplitterContentElement(){_classCallCheck(this,SplitterContentElement),_get(Object.getPrototypeOf(SplitterContentElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterContentElement,_ons$_BaseElement),_createClass(SplitterContentElement,[{key:"createdCallback",value:function(){this._page=null}},{key:"load",value:function(page){var _this=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this,util.createFragment(html),function(fragment){for(;_this.childNodes[0];)_this.childNodes[0]._hide instanceof Function&&_this.childNodes[0]._hide(),_this.removeChild(_this.childNodes[0]);_this.appendChild(fragment),util.arrayFrom(fragment.children).forEach(function(child){child._show instanceof Function&&child._show()}),options.callback()})})}},{key:"attachedCallback",value:function(){var _this2=this;this._assertParent(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this2,function(){return _this2.load(_this2.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"page",get:function(){return this._page}}]),SplitterContentElement}(ons._BaseElement);window.OnsSplitterContentElement||(window.OnsSplitterContentElement=document.registerElement("ons-splitter-content",{prototype:SplitterContentElement.prototype}),window.OnsSplitterContentElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var SplitterMaskElement=function(_ons$_BaseElement){function SplitterMaskElement(){_classCallCheck(this,SplitterMaskElement),_get(Object.getPrototypeOf(SplitterMaskElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterMaskElement,_ons$_BaseElement),_createClass(SplitterMaskElement,[{key:"createdCallback",value:function(){this._boundOnClick=this._onClick.bind(this)}},{key:"_onClick",value:function(event){this.parentElement&&"ons-splitter"===this.parentElement.nodeName.toLowerCase()&&(this.parentElement.closeRight(),this.parentElement.closeLeft()),event.stopPropagation()}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick); }},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick)}}]),SplitterMaskElement}(ons._BaseElement);window.OnsSplitterMaskElement||(window.OnsSplitterMaskElement=document.registerElement("ons-splitter-mask",{prototype:SplitterMaskElement.prototype}))}();var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_get=function(_x9,_x10,_x11){for(var _again=!0;_again;){var object=_x9,property=_x10,receiver=_x11;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x9=parent,_x10=property,_x11=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(){"use strict";var util=ons._util,AnimatorFactory=ons._internal.AnimatorFactory,SPLIT_MODE="split",COLLAPSE_MODE="collapse",CollapseDetection=function(){function CollapseDetection(){_classCallCheck(this,CollapseDetection)}return _createClass(CollapseDetection,[{key:"activate",value:function(element){}},{key:"inactivate",value:function(){}}]),CollapseDetection}(),rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},OrientationCollapseDetection=function(_CollapseDetection){function OrientationCollapseDetection(orientation){if(_classCallCheck(this,OrientationCollapseDetection),_get(Object.getPrototypeOf(OrientationCollapseDetection.prototype),"constructor",this).call(this),"portrait"!==orientation&&"landscape"!==orientation)throw new Error("Invalid orientation: "+orientation);this._boundOnOrientationChange=this._onOrientationChange.bind(this),this._targetOrientation=orientation}return _inherits(OrientationCollapseDetection,_CollapseDetection),_createClass(OrientationCollapseDetection,[{key:"activate",value:function(element){this._element=element,ons.orientation.on("change",this._boundOnOrientationChange),this._update(ons.orientation.isPortrait())}},{key:"_onOrientationChange",value:function(info){this._update(info.isPortrait)}},{key:"_update",value:function(isPortrait){isPortrait&&"portrait"===this._targetOrientation?this._element._updateMode(COLLAPSE_MODE):isPortrait||"landscape"!==this._targetOrientation?this._element._updateMode(SPLIT_MODE):this._element._updateMode(COLLAPSE_MODE)}},{key:"inactivate",value:function(){this._element=null,ons.orientation.off("change",this._boundOnOrientationChange)}}]),OrientationCollapseDetection}(CollapseDetection),StaticCollapseDetection=function(_CollapseDetection2){function StaticCollapseDetection(){_classCallCheck(this,StaticCollapseDetection),_get(Object.getPrototypeOf(StaticCollapseDetection.prototype),"constructor",this).apply(this,arguments)}return _inherits(StaticCollapseDetection,_CollapseDetection2),_createClass(StaticCollapseDetection,[{key:"activate",value:function(element){element._updateMode(COLLAPSE_MODE)}}]),StaticCollapseDetection}(CollapseDetection),MediaQueryCollapseDetection=function(_CollapseDetection3){function MediaQueryCollapseDetection(query){_classCallCheck(this,MediaQueryCollapseDetection),_get(Object.getPrototypeOf(MediaQueryCollapseDetection.prototype),"constructor",this).call(this),this._mediaQueryString=query,this._boundOnChange=this._onChange.bind(this)}return _inherits(MediaQueryCollapseDetection,_CollapseDetection3),_createClass(MediaQueryCollapseDetection,[{key:"_onChange",value:function(queryList){this._element._updateMode(queryList.matches?COLLAPSE_MODE:SPLIT_MODE)}},{key:"activate",value:function(element){this._element=element,this._queryResult=window.matchMedia(this._mediaQueryString),this._queryResult.addListener(this._boundOnChange),this._onChange(this._queryResult)}},{key:"inactivate",value:function(){this._element=null,this._queryResult.removeListener(this._boundOnChange),this._queryResult=null}}]),MediaQueryCollapseDetection}(CollapseDetection),BaseMode=function(){function BaseMode(){_classCallCheck(this,BaseMode)}return _createClass(BaseMode,[{key:"isOpened",value:function(){return!1}},{key:"openMenu",value:function(){return!1}},{key:"closeMenu",value:function(){return!1}},{key:"enterMode",value:function(){}},{key:"exitMode",value:function(){}},{key:"handleGesture",value:function(){}}]),BaseMode}(),SplitMode=function(_BaseMode){function SplitMode(element){_classCallCheck(this,SplitMode),_get(Object.getPrototypeOf(SplitMode.prototype),"constructor",this).call(this),this._element=element}return _inherits(SplitMode,_BaseMode),_createClass(SplitMode,[{key:"isOpened",value:function(){return!1}},{key:"layout",value:function(){var element=this._element;element.style.width=element._getWidth(),element._isLeftSide()?(element.style.left="0",element.style.right="auto"):(element.style.left="auto",element.style.right="0")}},{key:"enterMode",value:function(){this.layout()}},{key:"exitMode",value:function(){var element=this._element;element.style.left="",element.style.right="",element.style.width="",element.style.zIndex=""}}]),SplitMode}(BaseMode),CollapseMode=function(_BaseMode2){function CollapseMode(element){_classCallCheck(this,CollapseMode),_get(Object.getPrototypeOf(CollapseMode.prototype),"constructor",this).call(this),this._state=CollapseMode.CLOSED_STATE,this._distance=0,this._element=element,this._lock=new DoorLock}return _inherits(CollapseMode,_BaseMode2),_createClass(CollapseMode,[{key:"_animator",get:function(){return this._element._getAnimator()}}],[{key:"CLOSED_STATE",get:function(){return"closed"}},{key:"OPENED_STATE",get:function(){return"opened"}},{key:"CHANGING_STATE",get:function(){return"changing"}}]),_createClass(CollapseMode,[{key:"_isLocked",value:function(){return this._lock.isLocked()}},{key:"isOpened",value:function(){return this._state!==CollapseMode.CLOSED_STATE}},{key:"isClosed",value:function(){return this._state===CollapseMode.CLOSED_STATE}},{key:"handleGesture",value:function(event){if(!this._isLocked()&&!this._openedOtherSideMenu())if("dragstart"===event.type)this._onDragStart(event);else if("dragleft"===event.type||"dragright"===event.type)this._ignoreDrag||this._onDrag(event);else{if("dragend"!==event.type)throw new Error("Invalid state");this._ignoreDrag||this._onDragEnd(event)}}},{key:"_onDragStart",value:function(event){if(this._ignoreDrag=!1,!this.isOpened()&&this._openedOtherSideMenu())this._ignoreDrag=!0;else if(this._element._swipeTargetWidth>0){var distance=this._element._isLeftSide()?event.gesture.center.clientX:window.innerWidth-event.gesture.center.clientX;distance>this._element._swipeTargetWidth&&(this._ignoreDrag=!0)}}},{key:"_onDrag",value:function(event){event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,startEvent=event.gesture.startEvent;"isOpened"in startEvent||(startEvent.isOpened=this.isOpened(),startEvent.distance=startEvent.isOpened?this._element._getWidthInPixel():0,startEvent.width=this._element._getWidthInPixel());var width=this._element._getWidthInPixel();if(!(0>deltaDistance&&startEvent.distance<=0||deltaDistance>0&&startEvent.distance>=width)){var distance=startEvent.isOpened?deltaDistance+width:deltaDistance,normalizedDistance=Math.max(0,Math.min(width,distance));startEvent.distance=normalizedDistance,this._state=CollapseMode.CHANGING_STATE,this._animator.translate(normalizedDistance)}}},{key:"_onDragEnd",value:function(event){var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,width=event.gesture.startEvent.width,distance=event.gesture.startEvent.isOpened?deltaDistance+width:deltaDistance,direction=event.gesture.interimDirection,shouldOpen=this._element._isLeftSide()&&"right"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen()||!this._element._isLeftSide()&&"left"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen();shouldOpen?this._openMenu():this._closeMenu()}},{key:"layout",value:function(){if(this._state!==CollapseMode.CHANGING_STATE)if(this._state===CollapseMode.CLOSED_STATE)this._animator.isActivated()&&this._animator.layoutOnClose();else{if(this._state!==CollapseMode.OPENED_STATE)throw new Error("Invalid state");this._animator.isActivated()&&this._animator.layoutOnOpen()}}},{key:"enterMode",value:function(){this._animator.activate(this._element._getContentElement(),this._element,this._element._getMaskElement()),this.layout()}},{key:"exitMode",value:function(){this._animator.inactivate()}},{key:"_openedOtherSideMenu",value:function(){var _this=this;return util.arrayFrom(this._element.parentElement.children).filter(function(child){return"ons-splitter-side"===child.nodeName.toLowerCase()&&_this._element!==child}).filter(function(side){return side.isOpened()}).length>0}},{key:"openMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.CLOSED_STATE?!1:this._openMenu(options)}},{key:"_openMenu",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._openedOtherSideMenu())return!1;if(this._element._emitPreOpenEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this2._element._emitPostOpenEvent(),options.callback()};return options.withoutAnimation?(this._state=CollapseMode.OPENED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.open(function(){_this2._state=CollapseMode.OPENED_STATE,_this2.layout(),done()})),!0}},{key:"closeMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.OPENED_STATE?!1:this._closeMenu(options)}},{key:"_closeMenu",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._element._emitPreCloseEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this3._element._emitPostCloseEvent(),setImmediate(options.callback)};return options.withoutAnimation?(this._state=CollapseMode.CLOSED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.close(function(){_this3._state=CollapseMode.CLOSED_STATE,_this3.layout(),done()})),!0}}]),CollapseMode}(BaseMode),SplitterSideElement=function(_ons$_BaseElement){function SplitterSideElement(){_classCallCheck(this,SplitterSideElement),_get(Object.getPrototypeOf(SplitterSideElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterSideElement,_ons$_BaseElement),_createClass(SplitterSideElement,[{key:"_updateForAnimationOptionsAttribute",value:function(){this._animationOptions=util.parseJSONObjectSafely(this.getAttribute("animation-options"),{})}},{key:"_getMaskElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-mask")}},{key:"_getContentElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-content")}},{key:"_getModeStrategy",value:function(){return this._mode===COLLAPSE_MODE?this._collapseMode:this._mode===SPLIT_MODE?this._splitMode:void 0}},{key:"createdCallback",value:function(){this._mode=null,this._page=null,this._isAttached=!1,this._collapseStrategy=new CollapseDetection,this._animatorFactory=new AnimatorFactory({animators:window.OnsSplitterElement._animatorDict,baseClass:ons._internal.SplitterAnimator,baseClassName:"SplitterAnimator",defaultAnimation:this.getAttribute("animation")}),this._collapseMode=new CollapseMode(this),this._splitMode=new SplitMode(this),this._boundHandleGesture=this._handleGesture.bind(this),this._cancelModeDetection=function(){},this._updateMode(SPLIT_MODE),this._updateForAnimationAttribute(),this._updateForWidthAttribute(),this._updateForSideAttribute(),this._updateForCollapseAttribute(),this._updateForSwipeableAttribute(),this._updateForSwipeTargetWidthAttribute(),this._updateForAnimationOptionsAttribute()}},{key:"_getAnimator",value:function(){return this._animator}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"_emitPostOpenEvent",value:function(){util.triggerElementEvent(this,"postopen",{side:this})}},{key:"_emitPostCloseEvent",value:function(){util.triggerElementEvent(this,"postclose",{side:this})}},{key:"_emitPreOpenEvent",value:function(){return this._emitCancelableEvent("preopen")}},{key:"_emitCancelableEvent",value:function(name){var isCanceled=!1;return util.triggerElementEvent(this,name,{side:this,cancel:function(){return isCanceled=!0}}),isCanceled}},{key:"_emitPreCloseEvent",value:function(){return this._emitCancelableEvent("preclose")}},{key:"_updateForCollapseAttribute",value:function(){if(!this.hasAttribute("collapse"))return void this._updateMode(SPLIT_MODE);var collapse=(""+this.getAttribute("collapse")).trim();""===collapse?this._updateCollapseStrategy(new StaticCollapseDetection):"portrait"===collapse||"landscape"===collapse?this._updateCollapseStrategy(new OrientationCollapseDetection(collapse)):this._updateCollapseStrategy(new MediaQueryCollapseDetection(collapse))}},{key:"_updateCollapseStrategy",value:function(strategy){this._isAttached&&(this._collapseStrategy.inactivate(),strategy.activate(this)),this._collapseStrategy=strategy}},{key:"_updateMode",value:function(mode){if(mode!==COLLAPSE_MODE&&mode!==SPLIT_MODE)throw new Error("invalid mode: "+mode);if(mode!==this._mode){var lastMode=this._getModeStrategy();lastMode&&lastMode.exitMode(),this._mode=mode;var currentMode=this._getModeStrategy();currentMode.enterMode(),this.setAttribute("mode",mode),util.triggerElementEvent(this,"modechange",{side:this,mode:mode})}}},{key:"_getThresholdRatioIfShouldOpen",value:function(){if(this.hasAttribute("threshold-ratio-should-open")){var value=parseFloat(this.getAttribute("threshold-ratio-should-open"));return Math.max(0,Math.min(1,value))}return.3}},{key:"_layout",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSwipeTargetWidthAttribute",value:function(){this.hasAttribute("swipe-target-width")?this._swipeTargetWidth=Math.max(0,parseInt(this.getAttribute("swipe-target-width"),10)):this._swipeTargetWidth=-1}},{key:"_getWidth",value:function(){function normalize(width){return width=width.trim(),width.match(/^\d+(px|%)$/)?width:"80%"}return this.hasAttribute("width")?normalize(this.getAttribute("width")):"80%"}},{key:"_getWidthInPixel",value:function(){var width=this._getWidth(),_width$match=width.match(/^(\d+)(px|%)$/),_width$match2=_slicedToArray(_width$match,3),num=_width$match2[1],unit=_width$match2[2];if("px"===unit)return parseInt(num,10);if("%"===unit){var percent=parseInt(num,10);return Math.round(this.parentElement.offsetWidth*percent/100)}throw new Error("Invalid state")}},{key:"_getSide",value:function(){function normalize(side){return side=(""+side).trim(),"left"===side||"right"===side?side:"left"}return normalize(this.getAttribute("side"))}},{key:"_isLeftSide",value:function(){return"left"===this._getSide()}},{key:"_updateForWidthAttribute",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSideAttribute",value:function(){this._getModeStrategy().layout()}},{key:"getCurrentMode",value:function(){return this._mode}},{key:"isOpened",value:function(){return this._getModeStrategy().isOpened()}},{key:"open",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().openMenu(options)}},{key:"close",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().closeMenu(options)}},{key:"load",value:function(page){var _this4=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this4,util.createFragment(html),function(fragment){for(;_this4.childNodes[0];)_this4.childNodes[0]._hide instanceof Function&&_this4.childNodes[0]._hide(),_this4.removeChild(_this4.childNodes[0]);_this4.appendChild(fragment),util.arrayFrom(fragment.childNodes).forEach(function(node){node._show instanceof Function&&node._show()}),options.callback()})})}},{key:"toggle",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this.isOpened()?this.close(options):this.open(options)}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name?this._updateForWidthAttribute():"side"===name?this._updateForSideAttribute():"collapse"===name?this._updateForCollapseAttribute():"swipeable"===name?this._updateForSwipeableAttribute():"swipe-target-width"===name?this._updateForSwipeTargetWidthAttribute():"animation-options"===name?this._updateForAnimationOptionsAttribute():"animation"===name&&this._updateForAnimationAttribute()}},{key:"_updateForAnimationAttribute",value:function(){var isActivated=this._animator&&this._animator.isActivated();isActivated&&this._animator.inactivate(),this._animator=this._createAnimator(),isActivated&&this._animator.activate(this._getContentElement(),this,this._getMaskElement())}},{key:"_updateForSwipeableAttribute",value:function(){this._gestureDetector&&(this.isSwipeable()?this._gestureDetector.on("dragstart dragleft dragright dragend",this._boundHandleGesture):this._gestureDetector.off("dragstart dragleft dragright dragend",this._boundHandleGesture))}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"attachedCallback",value:function(){var _this5=this;this._isAttached=!0,this._collapseStrategy.activate(this),this._assertParent(),this._gestureDetector=new ons.GestureDetector(this.parentElement,{dragMinDistance:1}),this._updateForSwipeableAttribute(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this5,function(){return _this5.load(_this5.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){this._isAttached=!1,this._collapseStrategy.inactivate(),this._gestureDetector.dispose(),this._gestureDetector=null,this._updateForSwipeableAttribute()}},{key:"_handleGesture",value:function(event){return this._getModeStrategy().handleGesture(event)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_createAnimator",value:function(){return this._animatorFactory.newAnimator({animation:this.getAttribute("animation"),animationOptions:AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))})}},{key:"page",get:function(){return this._page}},{key:"mode",get:function(){this._mode}}]),SplitterSideElement}(ons._BaseElement);window.OnsSplitterSideElement||(window.OnsSplitterSideElement=document.registerElement("ons-splitter-side",{prototype:SplitterSideElement.prototype}),window.OnsSplitterSideElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"switch--*",".switch__input":"switch--*__input",".switch__toggle":"switch--*__toggle"},ModifierUtil=ons._internal.ModifierUtil,templateSource=ons._util.createElement('\n <div>\n <input type="checkbox" class="switch__input">\n <div class="switch__toggle"></div>\n </div>\n '),ExtendableLabelElement=void 0;"function"!=typeof HTMLLabelElement?(ExtendableLabelElement=function(){},ExtendableLabelElement.prototype=document.createElement("label")):ExtendableLabelElement=HTMLLabelElement;var generateId=function(){var i=0;return function(){return"ons-switch-id-"+i++}}(),SwitchElement=function(_ExtendableLabelElement){function SwitchElement(){_classCallCheck(this,SwitchElement),_get(Object.getPrototypeOf(SwitchElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SwitchElement,_ExtendableLabelElement),_createClass(SwitchElement,[{key:"isChecked",value:function(){return this.checked}},{key:"setChecked",value:function(isChecked){this.checked=!!isChecked}},{key:"getCheckboxElement",value:function(){return this._getCheckbox()}},{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateForCheckedAttribute(),this._updateForDisabledAttribute()}},{key:"_updateForCheckedAttribute",value:function(){this.hasAttribute("checked")?this._getCheckbox().checked=!0:this._getCheckbox().checked=!1}},{key:"_updateForDisabledAttribute",value:function(){this.hasAttribute("disabled")?this._getCheckbox().setAttribute("disabled",""):this._getCheckbox().removeAttribute("disabled")}},{key:"_compile",value:function(){this.classList.add("switch");for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this._getCheckbox().setAttribute("name",generateId())}},{key:"detachedCallback",value:function(){this._getCheckbox().removeEventListener("change",this._onChangeListener)}},{key:"attachedCallback",value:function(){this._getCheckbox().addEventListener("change",this._onChangeListener)}},{key:"_onChangeListener",value:function(){this.checked!==!0?this.removeAttribute("checked"):this.setAttribute("checked","")}},{key:"_isChecked",value:function(){return this._getCheckbox().checked}},{key:"_setChecked",value:function(isChecked){isChecked=!!isChecked;var checkbox=this._getCheckbox();checkbox.checked!=isChecked&&(checkbox.checked=isChecked)}},{key:"_getCheckbox",value:function(){return this.querySelector("input[type=checkbox]")}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("checked"===name?this._updateForCheckedAttribute():"disabled"===name&&this._updateForDisabledAttribute())}},{key:"checked",get:function(){return this._getCheckbox().checked},set:function(value){this._getCheckbox().checked=value,this.checked?this.setAttribute("checked",""):this.removeAttribute("checked"),this._updateForCheckedAttribute()}},{key:"disabled",get:function(){return this._getCheckbox().disabled},set:function(value){this._getCheckbox().disabled=value,this.disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}}]),SwitchElement}(ExtendableLabelElement);window.OnsSwitchElement||(window.OnsSwitchElement=document.registerElement("ons-switch",{prototype:SwitchElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".tab-bar__content":"tab-bar--*__content",".tab-bar":"tab-bar--*"},AnimatorFactory=ons._internal.AnimatorFactory,TabbarAnimator=ons._internal.TabbarAnimator,TabbarFadeAnimator=ons._internal.TabbarFadeAnimator,TabbarNoneAnimator=ons._internal.TabbarNoneAnimator,TabbarSlideAnimator=ons._internal.TabbarSlideAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":TabbarNoneAnimator,fade:TabbarFadeAnimator,slide:TabbarSlideAnimator,none:TabbarNoneAnimator},rewritables={ready:function(tabbarElement,callback){callback()},link:function(tabbarElement,target,callback){callback(target)},unlink:function(tabbarElement,target,callback){callback(target)}},generateId=function(){var i=0;return function(){return"ons-tabbar-gen-"+i++}}(),TabbarElement=function(_ons$_BaseElement){function TabbarElement(){_classCallCheck(this,TabbarElement),_get(Object.getPrototypeOf(TabbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarElement,_ons$_BaseElement),_createClass(TabbarElement,[{key:"createdCallback",value:function(){this._tabbarId=generateId(),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:TabbarAnimator,baseClassName:"TabbarAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),this._contentElement=ons._util.findChild(this,".tab-bar__content"),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var wrapper=document.createDocumentFragment(),content=document.createElement("div");content.classList.add("ons-tab-bar__content"),content.classList.add("tab-bar__content");var tabbar=document.createElement("div");for(tabbar.classList.add("tab-bar"),tabbar.classList.add("ons-tab-bar__footer"),tabbar.classList.add("ons-tabbar-inner"),wrapper.appendChild(content),wrapper.appendChild(tabbar);this.childNodes[0];)tabbar.appendChild(this.removeChild(this.childNodes[0]));this.appendChild(wrapper),this._hasTopTabbar()&&this._prepareForTopTabbar()}},{key:"_hasTopTabbar",value:function(){return"top"===this.getAttribute("position")}},{key:"_prepareForTopTabbar",value:function(){var content=ons._util.findChild(this,".tab-bar__content"),tabbar=ons._util.findChild(this,".tab-bar");content.setAttribute("no-status-bar-fill",""),content.classList.add("tab-bar--top__content"),tabbar.classList.add("tab-bar--top");var page=ons._util.findParent(this,"ons-page");if(page&&(this.style.top=window.getComputedStyle(page._getContentElement(),null).getPropertyValue("padding-top")),ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("tab-bar__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_getTabbarElement",value:function(){return util.findChild(this,".tab-bar")}},{key:"loadPage",value:function(page,options){return options=options||{},options._removeElement=!0,this._loadPage(page,options)}},{key:"_loadPage",value:function(page,options){var _this=this;OnsTabElement.prototype._createPageElement(page,function(pageElement){_this._loadPageDOMAsync(pageElement,options)})}},{key:"_loadPageDOMAsync",value:function(pageElement,options){var _this2=this;options=options||{},rewritables.link(this,pageElement,function(pageElement){_this2._contentElement.appendChild(pageElement),_this2._switchPage(pageElement,options)})}},{key:"getTabbarId",value:function(){return this._tabbarId}},{key:"_getCurrentPageElement",value:function(){for(var pages=this._contentElement.children,page=null,i=0;i<pages.length;i++)if("none"!==pages[i].style.display){page=pages[i];break}if(page&&"ons-page"!==page.nodeName.toLowerCase())throw new Error('Invalid state: page element must be a "ons-page" element.');return page}},{key:"_switchPage",value:function(element,options){if(-1!==this.getActiveTabIndex()){var oldPageElement=this._oldPageElement||ons._internal.nullElement;this._oldPageElement=element;var animator=this._animatorFactory.newAnimator(options);animator.apply(element,oldPageElement,options.selectedTabIndex,options.previousTabIndex,function(){oldPageElement!==ons._internal.nullElement&&(options._removeElement?rewritables.unlink(this,oldPageElement,function(pageElement){oldPageElement._destroy()}):(oldPageElement.style.display="none",oldPageElement._hide())),element.style.display="block",element._show(),options.callback instanceof Function&&options.callback()})}else options.callback instanceof Function&&options.callback()}},{key:"setActiveTab",value:function(index,options){var _this3=this;options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var previousTab=this._getActiveTabElement(),selectedTab=this._getTabElement(index),previousTabIndex=this.getActiveTabIndex(),selectedTabIndex=index;if(!selectedTab)return!1;if((selectedTab.hasAttribute("no-reload")||selectedTab.isPersistent())&&index===previousTabIndex)return util.triggerElementEvent(this,"reactive",{index:index,tabItem:selectedTab}),!1;var canceled=!1;if(util.triggerElementEvent(this,"prechange",{index:index,tabItem:selectedTab,cancel:function(){return canceled=!0}}),canceled)return selectedTab.setInactive(),previousTab&&previousTab.setActive(),!1;selectedTab.setActive();var needLoad=!selectedTab.isLoaded()&&!options.keepPage;if(needLoad){var removeElement=!0;previousTab&&previousTab.isPersistent()&&(removeElement=!1);var params={callback:function(){util.triggerElementEvent(_this3,"postchange",{index:index,tabItem:selectedTab}),options.callback instanceof Function&&options.callback()},previousTabIndex:previousTabIndex,selectedTabIndex:selectedTabIndex,_removeElement:removeElement};if(options.animation&&(params.animation=options.animation),selectedTab.isPersistent()){var link=function(element,callback){rewritables.link(_this3,element,callback)};selectedTab._loadPageElement(function(pageElement){_this3._loadPersistentPageDOM(pageElement,params)},link)}else this._loadPage(selectedTab.getAttribute("page"),params)}return util.arrayFrom(this._getTabbarElement().children).forEach(function(tab){tab!=selectedTab?tab.setInactive():needLoad||util.triggerElementEvent(_this3,"postchange",{ index:index,tabItem:selectedTab})}),!0}},{key:"_loadPersistentPageDOM",value:function(element,options){options=options||{},util.isAttached(element)||this._contentElement.appendChild(element),this._switchPage(element,options)}},{key:"setTabbarVisibility",value:function(visible){this._contentElement.style[this._hasTopTabbar()?"top":"bottom"]=visible?"":"0px",this._getTabbarElement().style.display=visible?"":"none"}},{key:"getActiveTabIndex",value:function(){for(var tabs=this._getTabbarElement().children,i=0;i<tabs.length;i++)if(tabs[i]instanceof window.OnsTabElement&&tabs[i].isActive&&tabs[i].isActive())return i;return-1}},{key:"_getActiveTabElement",value:function(){return this._getTabElement(this.getActiveTabIndex())}},{key:"_getTabElement",value:function(index){return this._getTabbarElement().children[index]}},{key:"detachedCallback",value:function(){}},{key:"attachedCallback",value:function(){}},{key:"_show",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._show()}},{key:"_hide",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._hide()}},{key:"_destroy",value:function(){for(var pages=this._contentElement.children,i=pages.length-1;i>=0;i--)pages[i]._destroy();this.remove()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabbarElement}(ons._BaseElement);window.OnsTabbarElement||(window.OnsTabbarElement=document.registerElement("ons-tabbar",{prototype:TabbarElement.prototype}),window.OnsTabbarElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof TabbarAnimator))throw new Error('"Animator" param must inherit TabbarAnimator');_animatorDict[name]=Animator},window.OnsTabbarElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var TemplateElement=function(_ons$_BaseElement){function TemplateElement(){_classCallCheck(this,TemplateElement),_get(Object.getPrototypeOf(TemplateElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TemplateElement,_ons$_BaseElement),_createClass(TemplateElement,[{key:"createdCallback",value:function(){for(this.template=this.innerHTML;this.firstChild;)this.removeChild(this.firstChild)}},{key:"attachedCallback",value:function(){var event=new CustomEvent("_templateloaded",{bubbles:!0,cancelable:!0});event.template=this.template,event.templateId=this.getAttribute("id"),this.dispatchEvent(event)}}]),TemplateElement}(ons._BaseElement);window.OnsTemplateElement||(window.OnsTemplateElement=document.registerElement("ons-template",{prototype:TemplateElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"toolbar-button--*"},ModifierUtil=ons._internal.ModifierUtil,ToolbarButtonElement=function(_ons$_BaseElement){function ToolbarButtonElement(){_classCallCheck(this,ToolbarButtonElement),_get(Object.getPrototypeOf(ToolbarButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarButtonElement,_ons$_BaseElement),_createClass(ToolbarButtonElement,[{key:"createdCallback",value:function(){this.classList.add("toolbar-button"),this.classList.add("navigation-bar__line-height"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ToolbarButtonElement}(ons._BaseElement);window.OnsToolbarButton||(window.OnsToolbarButton=document.registerElement("ons-toolbar-button",{prototype:ToolbarButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"navigation-bar--*",".navigation-bar__left":"navigation-bar--*__left",".navigation-bar__center":"navigation-bar--*__center",".navigation-bar__right":"navigation-bar--*__right"},ModifierUtil=ons._internal.ModifierUtil,ToolbarElement=function(_ons$_BaseElement){function ToolbarElement(){_classCallCheck(this,ToolbarElement),_get(Object.getPrototypeOf(ToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarElement,_ons$_BaseElement),_createClass(ToolbarElement,[{key:"createdCallback",value:function(){var _this=this;this._compile(),ModifierUtil.initModifier(this,scheme),this._tryToEnsureNodePosition(),setImmediate(function(){return _this._tryToEnsureNodePosition()})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){var _this2=this;this._tryToEnsureNodePosition(),setImmediate(function(){return _this2._tryToEnsureNodePosition()})}},{key:"_tryToEnsureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerToolbar(this)}}},{key:"_getToolbarLeftItemsElement",value:function(){return this.querySelector(".left")||ons._internal.nullElement}},{key:"_getToolbarCenterItemsElement",value:function(){return this.querySelector(".center")||ons._internal.nullElement}},{key:"_getToolbarRightItemsElement",value:function(){return this.querySelector(".right")||ons._internal.nullElement}},{key:"_getToolbarBackButtonLabelElement",value:function(){return this.querySelector("ons-back-button .back-button__label")||ons._internal.nullElement}},{key:"_compile",value:function(){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!this.hasAttribute("fixed-style"),inline=this.hasAttribute("inline");this.classList.add("navigation-bar"),shouldAppendAndroidModifier&&this.classList.add("navigation-bar--android"),inline||(this.style.position="absolute",this.style.zIndex="10000",this.style.left="0px",this.style.right="0px",this.style.top="0px"),this._ensureToolbarItemElements()}},{key:"_ensureToolbarItemElements",value:function(){for(var center,hasCenterClassElementOnly=1===this.children.length&&this.children[0].classList.contains("center"),i=0;i<this.childNodes.length;i++)1!=this.childNodes[i].nodeType&&this.removeChild(this.childNodes[i]);if(hasCenterClassElementOnly)center=this._ensureToolbarItemContainer("center");else{center=this._ensureToolbarItemContainer("center");var left=this._ensureToolbarItemContainer("left"),right=this._ensureToolbarItemContainer("right");if(this.children[0]!==left||this.children[1]!==center||this.children[2]!==right){left.parentNode&&this.removeChild(left),center.parentNode&&this.removeChild(center),right.parentNode&&this.removeChild(right);var fragment=document.createDocumentFragment();fragment.appendChild(left),fragment.appendChild(center),fragment.appendChild(right),this.appendChild(fragment)}}center.classList.add("navigation-bar__title")}},{key:"_ensureToolbarItemContainer",value:function(name){var container=ons._util.findChild(this,"."+name);return container||(container=document.createElement("div"),container.classList.add(name)),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),container.classList.add("navigation-bar__"+name),container}}]),ToolbarElement}(ons._BaseElement);window.OnsToolbarElement||(window.OnsToolbarElement=document.registerElement("ons-toolbar",{prototype:ToolbarElement.prototype}))}();
assets/skin_admin/panel-admin/js/jquery-1.7.2.min.js
project2you/students-attendance
/*! jQuery v1.7.2 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='../a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f .clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
src/svg-icons/toggle/indeterminate-check-box.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleIndeterminateCheckBox = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z"/> </SvgIcon> ); ToggleIndeterminateCheckBox = pure(ToggleIndeterminateCheckBox); ToggleIndeterminateCheckBox.displayName = 'ToggleIndeterminateCheckBox'; ToggleIndeterminateCheckBox.muiName = 'SvgIcon'; export default ToggleIndeterminateCheckBox;
app/components/Menu/WorldIcon.js
juanda99/arasaac-frontend
import React from 'react' import PropTypes from 'prop-types' import pure from 'recompose/pure' import SvgIcon from 'material-ui/SvgIcon' /* eslint-disable import/no-mutable-exports */ let WorldIcon = (props) => ( <SvgIcon {...props} viewBox='0 0 24 24'> <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z' /> </SvgIcon> ) WorldIcon.propTypes = { color: PropTypes.string } WorldIcon = pure(WorldIcon) WorldIcon.displayName = 'World' export default WorldIcon
src/components/Form/Reset.js
cantonjs/re-admin
import React, { Component } from 'react'; import { createRef } from 'utils/reactPolyfill'; import PropTypes from 'prop-types'; import { Form, Button } from 'antd'; import { DemonButton } from 'react-form-mobx'; const { Item } = Form; export default class Reset extends Component { static propTypes = { wrapperStyle: PropTypes.object, }; demonButtonRef = createRef(); handleClick = (ev) => { ev.preventDefault(); const demon = this.demonButtonRef.current; demon.clear(); demon.submit(); }; render() { const { wrapperStyle, ...props } = this.props; return ( <DemonButton forwardedProps={props} ref={this.demonButtonRef}> {(forwardedProps) => ( <Item style={wrapperStyle}> <Button {...forwardedProps} onClick={this.handleClick} /> </Item> )} </DemonButton> ); } }
src/Tab.js
downzer0/react-tabs
import React from 'react'; class Tab extends React.Component { constructor(props) { super(props); this.state = { expanded: this.props.index === this.props.selectedIndex, selected: this.props.index === this.props.selectedIndex }; if (this.props.index === this.props.selectedIndex && this.props.callback) { this.props.callback(); } } componentWillReceiveProps(nextProps) { this.setState({ expanded: this.props.index === nextProps.selectedIndex, selected: this.props.index === nextProps.selectedIndex }); } render() { return ( <button role="tab" id={"tab-" + this.props.index} className={(this.props.index === this.props.selectedIndex) ? 'dz0-tab is-selected' : 'dz0-tab'} aria-selected={this.state.selected} aria-expanded={this.state.expanded} aria-controls={"tabpanel-" + this.props.index} tabIndex={(this.props.selectedIndex === this.props.index) ? '0' : -1} onClick={(event) => this.props.onClick(event, this.props.index)} onKeyDown={(event) => this.props.onKeyDown(event, this.props.index)}> {this.props.label} </button> ) } } export default Tab;
packages/material-ui-icons/src/SimCardRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19.99 4c0-1.1-.89-2-1.99-2h-7.17c-.53 0-1.04.21-1.42.59L4.59 7.41C4.21 7.79 4 8.3 4 8.83V20c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM8 19c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm8 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-8-4c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1zm4 4c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1zm0-6c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm4 2c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1z" /> , 'SimCardRounded');
src/components/d3charts/MiniPieChart.js
nbuechler/friendly-finder
import React from 'react'; import d3 from 'd3'; export default class MiniPieChart extends React.Component { static defaultProps = { width: 50, height: 50, x: 0, y: 0, } constructor (props) { super(props); this.state = { }; } render () { var {props} = this, {width, height, data} = props; var radius = Math.min(width, height) / 2; var layout = d3.layout.pie()(data); var arcGen = d3.svg.arc() .innerRadius(radius * 0.0) .outerRadius(radius * 0.9); var color = ['#EB493A', '#5078A9', '#8B2E74', '#4E981F', '#D69C30']; return ( <svg {...props} visibility={'hidden'}> <g transform={`translate(${width / 2},${height / 2})`}> {layout.map((d, i) => { return ( <path d={arcGen(d)} key={i} style={{ fill: color[i % 5], stroke: 'black', strokeWidth: '2px', }} /> ); })} </g> </svg> ); } }
misc/tabledrag.js
pjobst/development
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery);
ajax/libs/golden-layout/1.5.3/goldenlayout.min.js
pvnr0082t/cdnjs
!function(t){var e={config:{},controls:{},errors:{},utils:{},items:{},container:{}};e.utils.F=function(){},e.utils.extend=function(t,i){t.prototype=e.utils.createObject(i.prototype),t.prototype.contructor=t},e.utils.createObject=function(t){return"function"==typeof Object.create?Object.create(t):(e.utils.F.prototype=t,new e.utils.F)},e.utils.objectKeys=function(t){var e,i;if("function"==typeof Object.keys)return Object.keys(t);e=[];for(i in t)e.push(i);return e},e.utils.getQueryStringParam=function(t){if(!window.location.search)return null;var e,i,n=window.location.search.substr(1).split("&"),o={};for(i=0;i<n.length;i++)e=n[i].split("="),o[e[0]]=e[1];return o[t]||null},e.utils.copy=function(t,e){for(var i in e)t[i]=e[i];return t},e.utils.animFrame=function(t){return(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){window.setTimeout(t,1e3/60)})(function(){t()})},e.utils.indexOf=function(t,e){if(!(e instanceof Array))throw new Error("Haystack is not an Array");if(e.indexOf)return e.indexOf(t);for(var i=0;i<e.length;i++)if(e[i]===t)return i;return-1},e.utils.fnBind=function(t,e,i){if(void 0!==Function.prototype.bind)return Function.prototype.bind.apply(t,[e].concat(i||[]));var n=function(){var o=(i||[]).concat(Array.prototype.slice.call(arguments,0));return this instanceof n?void t.apply(this,o):t.apply(e,o)};return n.prototype=t.prototype,n},e.utils.removeFromArray=function(t,i){var n=e.utils.indexOf(t,i);if(n===-1)throw new Error("Can't remove item from array. Item is not in the array");i.splice(n,1)},e.utils.now=function(){return"function"==typeof Date.now?Date.now():(new Date).getTime()},e.utils.getUniqueId=function(){return(1e15*Math.random()).toString(36).replace(".","")},e.utils.filterXss=function(t,e){var i=t.replace(/javascript/gi,"j&#97;vascript").replace(/expression/gi,"expr&#101;ssion").replace(/onload/gi,"onlo&#97;d").replace(/script/gi,"&#115;cript").replace(/onerror/gi,"on&#101;rror");return e===!0?i:i.replace(/>/g,"&gt;").replace(/</g,"&lt;")},e.utils.stripTags=function(e){return t.trim(e.replace(/(<([^>]+)>)/gi,""))},e.utils.EventEmitter=function(){this._mSubscriptions={},this._mSubscriptions[e.utils.EventEmitter.ALL_EVENT]=[],this.on=function(t,e,i){this._mSubscriptions[t]||(this._mSubscriptions[t]=[]),this._mSubscriptions[t].push({fn:e,ctx:i})},this.emit=function(t){var i,n,o;if(o=Array.prototype.slice.call(arguments,1),this._mSubscriptions[t])for(i=0;i<this._mSubscriptions[t].length;i++)n=this._mSubscriptions[t][i].ctx||{},this._mSubscriptions[t][i].fn.apply(n,o);for(o.unshift(t),i=0;i<this._mSubscriptions[e.utils.EventEmitter.ALL_EVENT].length;i++)n=this._mSubscriptions[e.utils.EventEmitter.ALL_EVENT][i].ctx||{},this._mSubscriptions[e.utils.EventEmitter.ALL_EVENT][i].fn.apply(n,o)},this.unbind=function(t,e,i){if(!this._mSubscriptions[t])throw new Error("No subscribtions to unsubscribe for event "+t);var n,o=!1;for(n=0;n<this._mSubscriptions[t].length;n++)this._mSubscriptions[t][n].fn!==e||i&&i!==this._mSubscriptions[t][n].ctx||(this._mSubscriptions[t].splice(n,1),o=!0);if(o===!1)throw new Error("Nothing to unbind for "+t)},this.off=this.unbind,this.trigger=this.emit},e.utils.EventEmitter.ALL_EVENT="__all",e.utils.DragListener=function(i,n){e.utils.EventEmitter.call(this),this._eElement=t(i),this._oDocument=t(document),this._eBody=t(document.body),this._nButtonCode=n||0,this._nDelay=200,this._nDistance=10,this._nX=0,this._nY=0,this._nOriginalX=0,this._nOriginalY=0,this._bDragging=!1,this._fMove=e.utils.fnBind(this.onMouseMove,this),this._fUp=e.utils.fnBind(this.onMouseUp,this),this._fDown=e.utils.fnBind(this.onMouseDown,this),this._eElement.on("mousedown touchstart",this._fDown)},e.utils.DragListener.timeout=null,e.utils.copy(e.utils.DragListener.prototype,{destroy:function(){this._eElement.unbind("mousedown touchstart",this._fDown)},onMouseDown:function(t){t.preventDefault();var i=this._getCoordinates(t);this._nOriginalX=i.x,this._nOriginalY=i.y,this._oDocument.on("mousemove touchmove",this._fMove),this._oDocument.one("mouseup touchend",this._fUp),0==t.button&&(this._timeout=setTimeout(e.utils.fnBind(this._startDrag,this),this._nDelay))},onMouseMove:function(t){if(null!=this._timeout){t.preventDefault();var e=this._getCoordinates(t);this._nX=e.x-this._nOriginalX,this._nY=e.y-this._nOriginalY,this._bDragging===!1&&(Math.abs(this._nX)>this._nDistance||Math.abs(this._nY)>this._nDistance)&&(clearTimeout(this._timeout),this._startDrag()),this._bDragging&&this.emit("drag",this._nX,this._nY,t)}},onMouseUp:function(t){null!=this._timeout&&(clearTimeout(this._timeout),this._eBody.removeClass("lm_dragging"),this._oDocument.find("iframe").css("pointer-events",""),this._oDocument.unbind("mousemove touchmove",this._fMove),this._bDragging===!0&&(this._bDragging=!1,this.emit("dragStop",t,this._nOriginalX+this._nX)))},_startDrag:function(){this._bDragging=!0,this._eBody.addClass("lm_dragging"),this._oDocument.find("iframe").css("pointer-events","none"),this.emit("dragStart",this._nOriginalX,this._nOriginalY)},_getCoordinates:function(t){var e={};return"touch"===t.type.substr(0,5)?(e.x=t.originalEvent.targetTouches[0].pageX,e.y=t.originalEvent.targetTouches[0].pageY):(e.x=t.pageX,e.y=t.pageY),e}}),e.LayoutManager=function(i,n){if(!t||"function"!=typeof t.noConflict){var o="jQuery is missing as dependency for GoldenLayout. ";throw o+='Please either expose $ on GoldenLayout\'s scope (e.g. window) or add "jquery" to ',o+="your paths when using RequireJS/AMD",new Error(o)}e.utils.EventEmitter.call(this),this.isInitialised=!1,this._isFullPage=!1,this._resizeTimeoutId=null,this._components={"lm-react-component":e.utils.ReactComponentHandler},this._itemAreas=[],this._resizeFunction=e.utils.fnBind(this._onResize,this),this._maximisedItem=null,this._maximisePlaceholder=t('<div class="lm_maximise_place"></div>'),this._creationTimeoutPassed=!1,this._subWindowsCreated=!1,this.width=null,this.height=null,this.root=null,this.openPopouts=[],this.selectedItem=null,this.isSubWindow=!1,this.eventHub=new e.utils.EventHub(this),this.config=this._createConfig(i),this.container=n,this.dropTargetIndicator=null,this.transitionIndicator=null,this.tabDropPlaceholder=t('<div class="lm_drop_tab_placeholder"></div>'),this.isSubWindow===!0&&t("body").css("visibility","hidden"),t(window).on("unload beforeunload",e.utils.fnBind(this._onUnload,this)),this._typeToItem={column:e.utils.fnBind(e.items.RowOrColumn,this,[!0]),row:e.utils.fnBind(e.items.RowOrColumn,this,[!1]),stack:e.items.Stack,component:e.items.Component}},e.LayoutManager.__lm=e,e.LayoutManager.minifyConfig=function(t){return(new e.utils.ConfigMinifier).minifyConfig(t)},e.LayoutManager.unminifyConfig=function(t){return(new e.utils.ConfigMinifier).unminifyConfig(t)},e.utils.copy(e.LayoutManager.prototype,{registerComponent:function(t,e){if("function"!=typeof e)throw new Error("Please register a constructor function");if(void 0!==this._components[t])throw new Error("Component "+t+" is already registered");this._components[t]=e},toConfig:function(t){var i,n,o;if(this.isInitialised===!1)throw new Error("Can't create config, layout not yet initialised");if(t&&!(t instanceof e.items.AbstractContentItem))throw new Error("Root must be a ContentItem");for(i={settings:e.utils.copy({},this.config.settings),dimensions:e.utils.copy({},this.config.dimensions),labels:e.utils.copy({},this.config.labels)},i.content=[],n=function(t,e){var i,o;for(i in e.config)"content"!==i&&(t[i]=e.config[i]);if(e.contentItems.length)for(t.content=[],o=0;o<e.contentItems.length;o++)t.content[o]={},n(t.content[o],e.contentItems[o])},t?n(i,{contentItems:[t]}):n(i,this.root),this._$reconcilePopoutWindows(),i.openPopouts=[],o=0;o<this.openPopouts.length;o++)i.openPopouts.push(this.openPopouts[o].toConfig());return i.maximisedItemId=this._maximisedItem?"__glMaximised":null,i},getComponent:function(t){if(void 0===this._components[t])throw new e.errors.ConfigurationError('Unknown component "'+t+'"');return this._components[t]},init:function(){return this._subWindowsCreated===!1&&(this._createSubWindows(),this._subWindowsCreated=!0),"loading"===document.readyState||null===document.body?void t(document).ready(e.utils.fnBind(this.init,this)):this.isSubWindow===!0&&this._creationTimeoutPassed===!1?(setTimeout(e.utils.fnBind(this.init,this),7),void(this._creationTimeoutPassed=!0)):(this.isSubWindow===!0&&this._adjustToWindowMode(),this._setContainer(),this.dropTargetIndicator=new e.controls.DropTargetIndicator(this.container),this.transitionIndicator=new e.controls.TransitionIndicator,this.updateSize(),this._create(this.config),this._bindEvents(),this.isInitialised=!0,void this.emit("initialised"))},updateSize:function(t,e){2===arguments.length?(this.width=t,this.height=e):(this.width=this.container.width(),this.height=this.container.height()),this.isInitialised===!0&&(this.root.callDownwards("setSize"),this._maximisedItem&&(this._maximisedItem.element.width(this.container.width()),this._maximisedItem.element.height(this.container.height()),this._maximisedItem.callDownwards("setSize")))},destroy:function(){this.isInitialised!==!1&&(this._onUnload(),t(window).off("resize",this._resizeFunction),this.root.callDownwards("_$destroy",[],!0),this.root.contentItems=[],this.tabDropPlaceholder.remove(),this.dropTargetIndicator.destroy(),this.transitionIndicator.destroy())},createContentItem:function(t,i){var n,o;if("string"!=typeof t.type)throw new e.errors.ConfigurationError("Missing parameter 'type'",t);if("react-component"===t.type&&(t.type="component",t.componentName="lm-react-component"),!this._typeToItem[t.type])throw n="Unknown type '"+t.type+"'. Valid types are "+e.utils.objectKeys(this._typeToItem).join(","),new e.errors.ConfigurationError(n);return"component"!==t.type||i instanceof e.items.Stack||!i||this.isSubWindow===!0&&i instanceof e.items.Root||(t={type:"stack",isClosable:t.isClosable,width:t.width,height:t.height,content:[t]}),o=new this._typeToItem[t.type](this,t,i)},createPopout:function(t,i,n,o){var s,r,a,h,l,c,m=t,d=t instanceof e.items.AbstractContentItem,u=this;if(n=n||null,d){for(m=this.toConfig(t).content,n=e.utils.getUniqueId(),h=t.parent,l=t;1===h.contentItems.length&&!h.isRoot;)h=h.parent,l=l.parent;h.addId(n),isNaN(o)&&(o=e.utils.indexOf(l,h.contentItems))}else m instanceof Array||(m=[m]);return!i&&d&&(s=window.screenX||window.screenLeft,r=window.screenY||window.screenTop,a=t.element.offset(),i={left:s+a.left,top:r+a.top,width:t.element.width(),height:t.element.height()}),i||d||(i={left:window.screenX||window.screenLeft+20,top:window.screenY||window.screenTop+20,width:500,height:309}),d&&t.remove(),c=new e.controls.BrowserPopout(m,i,n,o,this),c.on("initialised",function(){u.emit("windowOpened",c)}),c.on("closed",function(){u._$reconcilePopoutWindows()}),this.openPopouts.push(c),c},createDragSource:function(i,n){this.config.settings.constrainDragToContainer=!1,new e.controls.DragSource(t(i),n,this)},selectItem:function(t,e){if(this.config.settings.selectionEnabled!==!0)throw new Error("Please set selectionEnabled to true to use this feature");t!==this.selectedItem&&(null!==this.selectedItem&&this.selectedItem.deselect(),t&&e!==!0&&t.select(),this.selectedItem=t,this.emit("selectionChanged",t))},_$maximiseItem:function(t){null!==this._maximisedItem&&this._$minimiseItem(this._maximisedItem),this._maximisedItem=t,this._maximisedItem.addId("__glMaximised"),t.element.addClass("lm_maximised"),t.element.after(this._maximisePlaceholder),this.root.element.prepend(t.element),t.element.width(this.container.width()),t.element.height(this.container.height()),t.callDownwards("setSize"),this._maximisedItem.emit("maximised"),this.emit("stateChanged")},_$minimiseItem:function(t){t.element.removeClass("lm_maximised"),t.removeId("__glMaximised"),this._maximisePlaceholder.after(t.element),this._maximisePlaceholder.remove(),t.parent.callDownwards("setSize"),this._maximisedItem=null,t.emit("minimised"),this.emit("stateChanged")},_$closeWindow:function(){window.setTimeout(function(){window.close()},1)},_$getArea:function(t,e){var i,n,o=1/0,s=null;for(i=0;i<this._itemAreas.length;i++)n=this._itemAreas[i],t>n.x1&&t<n.x2&&e>n.y1&&e<n.y2&&o>n.surface&&(o=n.surface,s=n);return s},_$calculateItemAreas:function(){var t,e,i=this._getAllContentItems();if(this._itemAreas=[],1===i.length)return void this._itemAreas.push(this.root._$getArea());for(t=0;t<i.length;t++)i[t].isStack&&(e=i[t]._$getArea(),null!==e&&(e instanceof Array?this._itemAreas=this._itemAreas.concat(e):this._itemAreas.push(e)))},_$normalizeContentItem:function(i,n){if(!i)throw new Error("No content item defined");if(i instanceof e.items.AbstractContentItem)return i;if(t.isPlainObject(i)&&i.type){var o=this.createContentItem(i,n);return o.callDownwards("_$init"),o}throw new Error("Invalid contentItem")},_$reconcilePopoutWindows:function(){var t,e=[];for(t=0;t<this.openPopouts.length;t++)this.openPopouts[t].getWindow().closed===!1?e.push(this.openPopouts[t]):this.emit("windowClosed",this.openPopouts[t]);this.openPopouts.length!==e.length&&(this.emit("stateChanged"),this.openPopouts=e)},_getAllContentItems:function(){var t=[],e=function(i){if(t.push(i),i.contentItems instanceof Array)for(var n=0;n<i.contentItems.length;n++)e(i.contentItems[n])};return e(this.root),t},_bindEvents:function(){this._isFullPage&&t(window).resize(this._resizeFunction)},_onResize:function(){clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout(e.utils.fnBind(this.updateSize,this),100)},_createConfig:function(i){var n=e.utils.getQueryStringParam("gl-window");n&&(this.isSubWindow=!0,i=localStorage.getItem(n),i=JSON.parse(i),i=(new e.utils.ConfigMinifier).unminifyConfig(i),localStorage.removeItem(n)),i=t.extend(!0,{},e.config.defaultConfig,i);var o=function(t){for(var e in t)"props"!==e&&"object"==typeof t[e]?o(t[e]):"type"===e&&"react-component"===t[e]&&(t.type="component",t.componentName="lm-react-component")};return o(i),i.settings.hasHeaders===!1&&(i.dimensions.headerHeight=0),i},_adjustToWindowMode:function(){var i=t('<div class="lm_popin" title="'+this.config.labels.popin+'"><div class="lm_icon"></div><div class="lm_bg"></div></div>');i.click(e.utils.fnBind(function(){this.emit("popIn")},this)),document.title=e.utils.stripTags(this.config.content[0].title),t("head").append(t("body link, body style, template, .gl_keep")),this.container=t("body").html("").css("visibility","visible").append(i);document.body.offsetHeight;window.__glInstance=this},_createSubWindows:function(){var t,e;for(t=0;t<this.config.openPopouts.length;t++)e=this.config.openPopouts[t],this.createPopout(e.content,e.dimensions,e.parentId,e.indexInParent)},_setContainer:function(){var e=t(this.container||"body");if(0===e.length)throw new Error("GoldenLayout container not found");if(e.length>1)throw new Error("GoldenLayout more than one container element specified");e[0]===document.body&&(this._isFullPage=!0,t("html, body").css({height:"100%",margin:0,padding:0,overflow:"hidden"})),this.container=e},_create:function(t){var i;if(!(t.content instanceof Array))throw i=void 0===t.content?"Missing setting 'content' on top level of configuration":"Configuration parameter 'content' must be an array",new e.errors.ConfigurationError(i,t);if(t.content.length>1)throw i="Top level content can't contain more then one element.",new e.errors.ConfigurationError(i,t);this.root=new e.items.Root(this,{content:t.content},this.container),this.root.callDownwards("_$init"),"__glMaximised"===t.maximisedItemId&&this.root.getItemsById(t.maximisedItemId)[0].toggleMaximise()},_onUnload:function(){if(this.config.settings.closePopoutsOnUnload===!0)for(var t=0;t<this.openPopouts.length;t++)this.openPopouts[t].close()}}),function(){"function"==typeof define&&define.amd?define(["jquery"],function(i){return t=i,e.LayoutManager}):"object"==typeof exports?module.exports=e.LayoutManager:window.GoldenLayout=e.LayoutManager}(),e.config.itemDefaultConfig={isClosable:!0,reorderEnabled:!0,title:""},e.config.defaultConfig={openPopouts:[],settings:{hasHeaders:!0,constrainDragToContainer:!0,reorderEnabled:!0,selectionEnabled:!1,popoutWholeStack:!1,blockedPopoutsThrowError:!0,closePopoutsOnUnload:!0,showPopoutIcon:!0,showMaximiseIcon:!0,showCloseIcon:!0},dimensions:{borderWidth:5,minItemHeight:10,minItemWidth:10,headerHeight:20,dragProxyWidth:300,dragProxyHeight:200},labels:{close:"close",maximise:"maximise",minimise:"minimise",popout:"open in new window",popin:"pop in"}},e.container.ItemContainer=function(i,n,o){e.utils.EventEmitter.call(this),this.width=null,this.height=null,this.title=i.componentName,this.parent=n,this.layoutManager=o,this.isHidden=!1,this._config=i,this._element=t(['<div class="lm_item_container">','<div class="lm_content"></div>',"</div>"].join("")),this._contentElement=this._element.find(".lm_content")},e.utils.copy(e.container.ItemContainer.prototype,{getElement:function(){return this._contentElement},hide:function(){this.emit("hide"),this.isHidden=!0,this._element.hide()},show:function(){this.emit("show"),this.isHidden=!1,this._element.show()},setSize:function(t,e){for(var i,n,o,s,r,a,h=this.parent,l=this;!h.isColumn&&!h.isRow;)if(l=h,h=h.parent,h.isRoot)return!1;for(o=h.isColumn?"height":"width",s="height"===o?e:t,i=this[o]*(1/(l.config[o]/100)),n=s/i*100,r=(l.config[o]-n)/h.contentItems.length,a=0;a<h.contentItems.length;a++)h.contentItems[a]===l?h.contentItems[a].config[o]=n:h.contentItems[a].config[o]+=r;return h.callDownwards("setSize"),!0},close:function(){this._config.isClosable&&(this.emit("close"),this.parent.close())},getState:function(){return this._config.componentState},extendState:function(e){this.setState(t.extend(!0,this.getState(),e))},setState:function(t){this._config.componentState=t,this.parent.emitBubblingEvent("stateChanged")},setTitle:function(t){this.parent.setTitle(t)},_$setSize:function(t,e){t===this.width&&e===this.height||(this.width=t,this.height=e,this._contentElement.width(this.width).height(this.height),this.emit("resize"))}}),e.controls.BrowserPopout=function(t,i,n,o,s){e.utils.EventEmitter.call(this),this.isInitialised=!1,this._config=t,this._dimensions=i,this._parentId=n,this._indexInParent=o,this._layoutManager=s,this._popoutWindow=null,this._id=null,this._createWindow()},e.utils.copy(e.controls.BrowserPopout.prototype,{toConfig:function(){return{dimensions:{width:this.getGlInstance().width,height:this.getGlInstance().height,left:this._popoutWindow.screenX||this._popoutWindow.screenLeft,top:this._popoutWindow.screenY||this._popoutWindow.screenTop},content:this.getGlInstance().toConfig().content,parentId:this._parentId,indexInParent:this._indexInParent}},getGlInstance:function(){return this._popoutWindow.__glInstance},getWindow:function(){return this._popoutWindow},close:function(){if(this.getGlInstance())this.getGlInstance()._$closeWindow();else try{this.getWindow().close()}catch(t){}},popIn:function(){var e,i,n=this._indexInParent;this._parentId&&(e=t.extend(!0,{},this.getGlInstance().toConfig()).content[0],i=this._layoutManager.root.getItemsById(this._parentId)[0],i||(i=this._layoutManager.root.contentItems.length>0?this._layoutManager.root.contentItems[0]:this._layoutManager.root,n=0)),i.addChild(e,this._indexInParent),this.close()},_createWindow:function(){var i,n=this._createUrl(),o=Math.floor(1e6*Math.random()).toString(36),s=this._serializeWindowOptions({width:this._dimensions.width,height:this._dimensions.height,innerWidth:this._dimensions.width,innerHeight:this._dimensions.height,menubar:"no",toolbar:"no",location:"no",personalbar:"no",resizable:"yes",scrollbars:"no",status:"no"});if(this._popoutWindow=window.open(n,o,s),this._popoutWindow)t(this._popoutWindow).on("load",e.utils.fnBind(this._positionWindow,this)).on("unload beforeunload",e.utils.fnBind(this._onClose,this)),i=setInterval(e.utils.fnBind(function(){this._popoutWindow.__glInstance&&this._popoutWindow.__glInstance.isInitialised&&(this._onInitialised(),clearInterval(i))},this),10);else if(this._layoutManager.config.settings.blockedPopoutsThrowError===!0){var r=new Error("Popout blocked");throw r.type="popoutBlocked",r}},_serializeWindowOptions:function(t){var e,i=[];for(e in t)i.push(e+"="+t[e]);return i.join(",")},_createUrl:function(){var t,i={content:this._config},n="gl-window-config-"+e.utils.getUniqueId();i=(new e.utils.ConfigMinifier).minifyConfig(i);try{localStorage.setItem(n,JSON.stringify(i))}catch(o){throw new Error("Error while writing to localStorage "+o.toString())}return t=document.location.href.split("?"),1===t.length?t[0]+"?gl-window="+n:document.location.href+"&gl-window="+n},_positionWindow:function(){this._popoutWindow.moveTo(this._dimensions.left,this._dimensions.top),this._popoutWindow.focus()},_onInitialised:function(){this.isInitialised=!0,this.getGlInstance().on("popIn",this.popIn,this),this.emit("initialised")},_onClose:function(){setTimeout(e.utils.fnBind(this.emit,this,["closed"]),50)}}),e.controls.DragProxy=function(i,n,o,s,r,a){e.utils.EventEmitter.call(this),this._dragListener=o,this._layoutManager=s,this._contentItem=r,this._originalParent=a,this._area=null,this._lastValidArea=null,this._dragListener.on("drag",this._onDrag,this),this._dragListener.on("dragStop",this._onDrop,this),this.element=t(e.controls.DragProxy._template),this.element.css({left:i,top:n}),this.element.find(".lm_title").html(this._contentItem.config.title),this.childElementContainer=this.element.find(".lm_content"),this.childElementContainer.append(r.element),this._updateTree(),this._layoutManager._$calculateItemAreas(),this._setDimensions(),t(document.body).append(this.element);var h=this._layoutManager.container.offset();this._minX=h.left,this._minY=h.top,this._maxX=this._layoutManager.container.width()+this._minX,this._maxY=this._layoutManager.container.height()+this._minY,this._width=this.element.width(),this._height=this.element.height()},e.controls.DragProxy._template='<div class="lm_dragProxy"><div class="lm_header"><ul class="lm_tabs"><li class="lm_tab lm_active"><i class="lm_left"></i><span class="lm_title"></span><i class="lm_right"></i></li></ul></div><div class="lm_content"></div></div>',e.utils.copy(e.controls.DragProxy.prototype,{_onDrag:function(t,e,i){var n=i.pageX,o=i.pageY,s=n>this._minX&&n<this._maxX&&o>this._minY&&o<this._maxY;(s||this._layoutManager.config.settings.constrainDragToContainer!==!0)&&(this.element.css({left:n,top:o}),this._area=this._layoutManager._$getArea(n,o),null!==this._area&&(this._lastValidArea=this._area,this._area.contentItem._$highlightDropZone(n,o,this._area)))},_onDrop:function(){this._layoutManager.dropTargetIndicator.hide(),null!==this._area?this._area.contentItem._$onDrop(this._contentItem):null!==this._lastValidArea?this._lastValidArea.contentItem._$onDrop(this._contentItem):this._originalParent?this._originalParent.addChild(this._contentItem):this._contentItem._$destroy(),this.element.remove(),this._layoutManager.emit("itemDropped",this._contentItem)},_updateTree:function(){this._contentItem.parent&&this._contentItem.parent.removeChild(this._contentItem,!0),this._contentItem._$setParent(this)},_setDimensions:function(){var t=this._layoutManager.config.dimensions,e=t.dragProxyWidth,i=t.dragProxyHeight-t.headerHeight;this.childElementContainer.width(e),this.childElementContainer.height(i),this._contentItem.element.width(e),this._contentItem.element.height(i),this._contentItem.callDownwards("_$show"),this._contentItem.callDownwards("setSize")}}),e.controls.DragSource=function(t,e,i){this._element=t,this._itemConfig=e,this._layoutManager=i,this._dragListener=null,this._createDragListener()},e.utils.copy(e.controls.DragSource.prototype,{_createDragListener:function(){null!==this._dragListener&&this._dragListener.destroy(),this._dragListener=new e.utils.DragListener(this._element),this._dragListener.on("dragStart",this._onDragStart,this),this._dragListener.on("dragStop",this._createDragListener,this)},_onDragStart:function(t,i){var n=this._layoutManager._$normalizeContentItem(this._itemConfig),o=new e.controls.DragProxy(t,i,this._dragListener,this._layoutManager,n,null);this._layoutManager.transitionIndicator.transitionElements(this._element,o.element)}}),e.controls.DropTargetIndicator=function(){this.element=t(e.controls.DropTargetIndicator._template),t(document.body).append(this.element)},e.controls.DropTargetIndicator._template='<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>',e.utils.copy(e.controls.DropTargetIndicator.prototype,{destroy:function(){this.element.remove()},highlight:function(t,e,i,n){this.highlightArea({x1:t,y1:e,x2:i,y2:n})},highlightArea:function(t){this.element.css({left:t.x1,top:t.y1,width:t.x2-t.x1,height:t.y2-t.y1}).show()},hide:function(){this.element.hide()}}),e.controls.Header=function(i,n){e.utils.EventEmitter.call(this),this.layoutManager=i,this.element=t(e.controls.Header._template),this.layoutManager.config.settings.selectionEnabled===!0&&(this.element.addClass("lm_selectable"),this.element.click(e.utils.fnBind(this._onHeaderClick,this))),this.element.height(i.config.dimensions.headerHeight),this.tabsContainer=this.element.find(".lm_tabs"),this.controlsContainer=this.element.find(".lm_controls"),this.parent=n,this.parent.on("resize",this._updateTabSizes,this),this.tabs=[],this.activeContentItem=null,this._createControls()},e.controls.Header._template=['<div class="lm_header">','<ul class="lm_tabs"></ul>','<ul class="lm_controls"></ul>',"</div>"].join(""),e.utils.copy(e.controls.Header.prototype,{createTab:function(t,i){var n,o;for(o=0;o<this.tabs.length;o++)if(this.tabs[o].contentItem===t)return;return n=new e.controls.Tab(this,t),0===this.tabs.length?(this.tabs.push(n),void this.tabsContainer.append(n.element)):(void 0===i&&(i=this.tabs.length),i>0?this.tabs[i-1].element.after(n.element):this.tabs[0].element.before(n.element),this.tabs.splice(i,0,n),void this._updateTabSizes())},removeTab:function(t){for(var e=0;e<this.tabs.length;e++)if(this.tabs[e].contentItem===t)return this.tabs[e]._$destroy(),void this.tabs.splice(e,1);throw new Error("contentItem is not controlled by this header")},setActiveContentItem:function(t){var e,i;for(e=0;e<this.tabs.length;e++)i=this.tabs[e].contentItem===t,this.tabs[e].setActive(i),i===!0&&(this.activeContentItem=t,this.parent.config.activeItemIndex=e);this._updateTabSizes(),this.parent.emitBubblingEvent("stateChanged")},_$destroy:function(){this.emit("destroy");for(var t=0;t<this.tabs.length;t++)this.tabs[t]._$destroy();this.element.remove()},_createControls:function(){var t,i,n,o,s,r,a;this.layoutManager.config.settings.showPopoutIcon&&(i=e.utils.fnBind(this._onPopoutClick,this),n=this.layoutManager.config.labels.popout,new e.controls.HeaderButton(this,n,"lm_popout",i)),this.layoutManager.config.settings.showMaximiseIcon&&(r=e.utils.fnBind(this.parent.toggleMaximise,this.parent),o=this.layoutManager.config.labels.maximise,s=this.layoutManager.config.labels.minimise,a=new e.controls.HeaderButton(this,o,"lm_maximise",r),this.parent.on("maximised",function(){a.element.attr("title",s)}),this.parent.on("minimised",function(){a.element.attr("title",o)})),this.parent.config.isClosable&&this.layoutManager.config.settings.showCloseIcon&&(t=e.utils.fnBind(this.parent.remove,this.parent),n=this.layoutManager.config.labels.close,new e.controls.HeaderButton(this,n,"lm_close",t))},_onPopoutClick:function(){this.layoutManager.config.settings.popoutWholeStack===!0?this.parent.popout():this.activeContentItem.popout()},_onHeaderClick:function(t){t.target===this.element[0]&&this.parent.select()},_updateTabSizes:function(){if(0!==this.tabs.length){var t,e,i,n,o=this.element.outerWidth()-this.controlsContainer.outerWidth(),s=0;for(e=0;e<this.tabs.length;e++)t=this.tabs[e].element,t.css("z-index",this.tabs.length-e),s+=t.outerWidth()+parseInt(t.css("margin-right"),10);for(n=(s-o)/(this.tabs.length-1),e=0;e<this.tabs.length;e++)i=!this.tabs[e].isActive&&n>0?"-"+Math.floor(n)+"px":"",this.tabs[e].element.css("margin-left",i);o<s?this.element.css("overflow","hidden"):this.element.css("overflow","visible")}}}),e.controls.HeaderButton=function(e,i,n,o){this._header=e,this.element=t('<li class="'+n+'" title="'+i+'"></li>'),this._header.on("destroy",this._$destroy,this),this._action=o,this.element.click(this._action),this._header.controlsContainer.append(this.element)},e.utils.copy(e.controls.HeaderButton.prototype,{_$destroy:function(){this.element.off(),this.element.remove()}}),e.controls.Splitter=function(t,i){this._isVertical=t,this._size=i,this.element=this._createElement(),this._dragListener=new e.utils.DragListener(this.element)},e.utils.copy(e.controls.Splitter.prototype,{on:function(t,e,i){this._dragListener.on(t,e,i)},_$destroy:function(){this.element.remove()},_createElement:function(){var e=t('<div class="lm_splitter"><div class="lm_drag_handle"></div></div>');return e.addClass("lm_"+(this._isVertical?"vertical":"horizontal")),e[this._isVertical?"height":"width"](this._size),e}}),e.controls.Tab=function(i,n){this.header=i,this.contentItem=n,this.element=t(e.controls.Tab._template),this.titleElement=this.element.find(".lm_title"),this.closeElement=this.element.find(".lm_close_tab"),this.closeElement[n.config.isClosable?"show":"hide"](),this.isActive=!1,this.setTitle(n.config.title),this.contentItem.on("titleChanged",this.setTitle,this),this._layoutManager=this.contentItem.layoutManager,this._layoutManager.config.settings.reorderEnabled===!0&&n.config.reorderEnabled===!0&&(this._dragListener=new e.utils.DragListener(this.element),this._dragListener.on("dragStart",this._onDragStart,this)),this._onTabClickFn=e.utils.fnBind(this._onTabClick,this),this._onCloseClickFn=e.utils.fnBind(this._onCloseClick,this),this.element.click(this._onTabClickFn),this._layoutManager.config.settings.showCloseIcon===!0?this.closeElement.click(this._onCloseClickFn):this.closeElement.remove(),this.contentItem.tab=this,this.contentItem.emit("tab",this),this.contentItem.layoutManager.emit("tabCreated",this),this.contentItem.isComponent&&(this.contentItem.container.tab=this,this.contentItem.container.emit("tab",this))},e.controls.Tab._template='<li class="lm_tab"><i class="lm_left"></i><span class="lm_title"></span><div class="lm_close_tab"></div><i class="lm_right"></i></li>',e.utils.copy(e.controls.Tab.prototype,{setTitle:function(t){this.element.attr("title",e.utils.stripTags(t)),this.titleElement.html(t)},setActive:function(t){t!==this.isActive&&(this.isActive=t,t?this.element.addClass("lm_active"):this.element.removeClass("lm_active"))},_$destroy:function(){this.element.off("click",this._onTabClickFn),this.closeElement.off("click",this._onCloseClickFn),this.element.remove()},_onDragStart:function(t,i){this.contentItem.parent.isMaximised===!0&&this.contentItem.parent.toggleMaximise(),new e.controls.DragProxy(t,i,this._dragListener,this._layoutManager,this.contentItem,this.header.parent)},_onTabClick:function(t){0===t.button?this.header.parent.setActiveContentItem(this.contentItem):1===t.button&&this.contentItem.config.isClosable&&this._onCloseClick(t)},_onCloseClick:function(t){t.stopPropagation(),this.header.parent.removeChild(this.contentItem)}}),e.controls.TransitionIndicator=function(){this._element=t('<div class="lm_transition_indicator"></div>'),t(document.body).append(this._element),this._toElement=null,this._fromDimensions=null,this._totalAnimationDuration=200,this._animationStartTime=null},e.utils.copy(e.controls.TransitionIndicator.prototype,{destroy:function(){this._element.remove()},transitionElements:function(t,e){},_nextAnimationFrame:function(){var t,i=this._measure(this._toElement),n=(e.utils.now()-this._animationStartTime)/this._totalAnimationDuration,o={};if(n>=1)return void this._element.hide();i.opacity=0;for(t in this._fromDimensions)o[t]=this._fromDimensions[t]+(i[t]-this._fromDimensions[t])*n;this._element.css(o),e.utils.animFrame(e.utils.fnBind(this._nextAnimationFrame,this))},_measure:function(t){var e=t.offset();return{left:e.left, top:e.top,width:t.outerWidth(),height:t.outerHeight()}}}),e.errors.ConfigurationError=function(t,e){Error.call(this),this.name="Configuration Error",this.message=t,this.node=e},e.errors.ConfigurationError.prototype=new Error,e.items.AbstractContentItem=function(t,i,n){e.utils.EventEmitter.call(this),this.config=this._extendItemNode(i),this.type=i.type,this.contentItems=[],this.parent=n,this.isInitialised=!1,this.isMaximised=!1,this.isRoot=!1,this.isRow=!1,this.isColumn=!1,this.isStack=!1,this.isComponent=!1,this.layoutManager=t,this._pendingEventPropagations={},this._throttledEvents=["stateChanged"],this.on(e.utils.EventEmitter.ALL_EVENT,this._propagateEvent,this),i.content&&this._createContentItems(i)},e.utils.copy(e.items.AbstractContentItem.prototype,{setSize:function(){throw new Error("Abstract Method")},callDownwards:function(t,e,i,n){var o;for(i!==!0&&n!==!0&&this[t].apply(this,e||[]),o=0;o<this.contentItems.length;o++)this.contentItems[o].callDownwards(t,e,i);i===!0&&n!==!0&&this[t].apply(this,e||[])},removeChild:function(t,i){var n=e.utils.indexOf(t,this.contentItems);if(n===-1)throw new Error("Can't remove child item. Unknown content item");i!==!0&&this.contentItems[n]._$destroy(),this.contentItems.splice(n,1),this.config.content.splice(n,1),this.contentItems.length>0?this.callDownwards("setSize"):this instanceof e.items.Root||this.config.isClosable!==!0||this.parent.removeChild(this)},addChild:function(t,e){void 0===e&&(e=this.contentItems.length),this.contentItems.splice(e,0,t),void 0===this.config.content&&(this.config.content=[]),this.config.content.splice(e,0,t.config),t.parent=this,t.parent.isInitialised===!0&&t.isInitialised===!1&&t._$init()},replaceChild:function(t,i,n){i=this.layoutManager._$normalizeContentItem(i);var o=e.utils.indexOf(t,this.contentItems),s=t.element[0].parentNode;if(o===-1)throw new Error("Can't replace child. oldChild is not child of this");s.replaceChild(i.element[0],t.element[0]),n===!0&&(t.parent=null,t._$destroy()),this.contentItems[o]=i,i.parent=this,this.isStack&&(this.header.tabs[o].contentItem=i),i.parent.isInitialised===!0&&i.isInitialised===!1&&i._$init(),this.callDownwards("setSize")},remove:function(){this.parent.removeChild(this)},popout:function(){var t=this.layoutManager.createPopout(this);return this.emitBubblingEvent("stateChanged"),t},toggleMaximise:function(){this.isMaximised===!0?this.layoutManager._$minimiseItem(this):this.layoutManager._$maximiseItem(this),this.isMaximised=!this.isMaximised,this.emitBubblingEvent("stateChanged")},select:function(){this.layoutManager.selectedItem!==this&&(this.layoutManager.selectItem(this,!0),this.element.addClass("lm_selected"))},deselect:function(){this.layoutManager.selectedItem===this&&(this.layoutManager.selectedItem=null,this.element.removeClass("lm_selected"))},setTitle:function(t){this.config.title=t,this.emit("titleChanged",t),this.emit("stateChanged")},hasId:function(t){return!!this.config.id&&("string"==typeof this.config.id?this.config.id===t:this.config.id instanceof Array?e.utils.indexOf(t,this.config.id)!==-1:void 0)},addId:function(t){this.hasId(t)||(this.config.id?"string"==typeof this.config.id?this.config.id=[this.config.id,t]:this.config.id instanceof Array&&this.config.id.push(t):this.config.id=t)},removeId:function(t){if(!this.hasId(t))throw new Error("Id not found");if("string"==typeof this.config.id)delete this.config.id;else if(this.config.id instanceof Array){var i=e.utils.indexOf(t,this.config.id);this.config.id.splice(i,1)}},getItemsByFilter:function(t){var e=[],i=function(n){for(var o=0;o<n.contentItems.length;o++)t(n.contentItems[o])===!0&&e.push(n.contentItems[o]),i(n.contentItems[o])};return i(this),e},getItemsById:function(t){return this.getItemsByFilter(function(i){return i.config.id instanceof Array?e.utils.indexOf(t,i.config.id)!==-1:i.config.id===t})},getItemsByType:function(t){return this._$getItemsByProperty("type",t)},getComponentsByName:function(t){var e,i=this._$getItemsByProperty("componentName",t),n=[];for(e=0;e<i.length;e++)n.push(i[e].instance);return n},_$getItemsByProperty:function(t,e){return this.getItemsByFilter(function(i){return i[t]===e})},_$setParent:function(t){this.parent=t},_$highlightDropZone:function(t,e,i){this.layoutManager.dropTargetIndicator.highlightArea(i)},_$onDrop:function(t){this.addChild(t)},_$hide:function(){this._callOnActiveComponents("hide"),this.element.hide(),this.layoutManager.updateSize()},_$show:function(){this._callOnActiveComponents("show"),this.element.show(),this.layoutManager.updateSize()},_callOnActiveComponents:function(t){var e,i,n=this.getItemsByType("stack");for(i=0;i<n.length;i++)e=n[i].getActiveContentItem(),e&&e.isComponent&&e.container[t]()},_$destroy:function(){this.emitBubblingEvent("beforeItemDestroyed"),this.callDownwards("_$destroy",[],!0,!0),this.element.remove(),this.emitBubblingEvent("itemDestroyed")},_$getArea:function(t){t=t||this.element;var e=t.offset(),i=t.width(),n=t.height();return{x1:e.left,y1:e.top,x2:e.left+i,y2:e.top+n,surface:i*n,contentItem:this}},_$init:function(){var t;for(this.setSize(),t=0;t<this.contentItems.length;t++)this.childElementContainer.append(this.contentItems[t].element);this.isInitialised=!0,this.emitBubblingEvent("itemCreated"),this.emitBubblingEvent(this.type+"Created")},emitBubblingEvent:function(t){var i=new e.utils.BubblingEvent(t,this);this.emit(t,i)},_createContentItems:function(t){var i,n;if(!(t.content instanceof Array))throw new e.errors.ConfigurationError("content must be an Array",t);for(n=0;n<t.content.length;n++)i=this.layoutManager.createContentItem(t.content[n],this),this.contentItems.push(i)},_extendItemNode:function(t){for(var i in e.config.itemDefaultConfig)void 0===t[i]&&(t[i]=e.config.itemDefaultConfig[i]);return t},_propagateEvent:function(t,i){i instanceof e.utils.BubblingEvent&&i.isPropagationStopped===!1&&this.isInitialised===!0&&(this.isRoot===!1&&this.parent?this.parent.emit.apply(this.parent,Array.prototype.slice.call(arguments,0)):this._scheduleEventPropagationToLayoutManager(t,i))},_scheduleEventPropagationToLayoutManager:function(t,i){e.utils.indexOf(t,this._throttledEvents)===-1?this.layoutManager.emit(t,i.origin):this._pendingEventPropagations[t]!==!0&&(this._pendingEventPropagations[t]=!0,e.utils.animFrame(e.utils.fnBind(this._propagateEventToLayoutManager,this,[t,i])))},_propagateEventToLayoutManager:function(t,e){this._pendingEventPropagations[t]=!1,this.layoutManager.emit(t,e)}}),e.items.Component=function(i,n,o){e.items.AbstractContentItem.call(this,i,n,o);var s=i.getComponent(this.config.componentName),r=t.extend(!0,{},this.config.componentState||{});r.componentName=this.config.componentName,this.componentName=this.config.componentName,""===this.config.title&&(this.config.title=this.config.componentName),this.isComponent=!0,this.container=new e.container.ItemContainer(this.config,this,i),this.instance=new s(this.container,r),this.element=this.container._element},e.utils.extend(e.items.Component,e.items.AbstractContentItem),e.utils.copy(e.items.Component.prototype,{close:function(){this.parent.removeChild(this)},setSize:function(){this.container._$setSize(this.element.width(),this.element.height())},_$init:function(){e.items.AbstractContentItem.prototype._$init.call(this),this.container.emit("open")},_$hide:function(){this.container.hide(),e.items.AbstractContentItem.prototype._$hide.call(this)},_$show:function(){this.container.show(),e.items.AbstractContentItem.prototype._$show.call(this)},_$destroy:function(){this.container.emit("destroy"),e.items.AbstractContentItem.prototype._$destroy.call(this)},_$getArea:function(){return null}}),e.items.Root=function(i,n,o){e.items.AbstractContentItem.call(this,i,n,null),this.isRoot=!0,this.type="root",this.element=t('<div class="lm_goldenlayout lm_item lm_root"></div>'),this.childElementContainer=this.element,this._containerElement=o,this._containerElement.append(this.element)},e.utils.extend(e.items.Root,e.items.AbstractContentItem),e.utils.copy(e.items.Root.prototype,{addChild:function(t){if(this.contentItems.length>0)throw new Error("Root node can only have a single child");t=this.layoutManager._$normalizeContentItem(t,this),this.childElementContainer.append(t.element),e.items.AbstractContentItem.prototype.addChild.call(this,t),this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")},setSize:function(){var t=this._containerElement.width(),e=this._containerElement.height();this.element.width(t),this.element.height(e),this.contentItems[0]&&(this.contentItems[0].element.width(t),this.contentItems[0].element.height(e))},_$onDrop:function(t){var e;t.isComponent===!0?(e=this.layoutManager.createContentItem({type:"stack"},this),e.addChild(t),this.addChild(e)):this.addChild(t)}}),e.items.RowOrColumn=function(i,n,o,s){e.items.AbstractContentItem.call(this,n,o,s),this.isRow=!i,this.isColumn=i,this.element=t('<div class="lm_item lm_'+(i?"column":"row")+'"></div>'),this.childElementContainer=this.element,this._splitterSize=n.config.dimensions.borderWidth,this._isColumn=i,this._dimension=i?"height":"width",this._splitter=[],this._splitterPosition=null,this._splitterMinPosition=null,this._splitterMaxPosition=null},e.utils.extend(e.items.RowOrColumn,e.items.AbstractContentItem),e.utils.copy(e.items.RowOrColumn.prototype,{addChild:function(t,i,n){var o,s,r,a;if(t=this.layoutManager._$normalizeContentItem(t,this),void 0===i&&(i=this.contentItems.length),this.contentItems.length>0?(a=this._createSplitter(Math.max(0,i-1)).element,i>0?(this.contentItems[i-1].element.after(a),a.after(t.element)):(this.contentItems[0].element.before(a),a.before(t.element))):this.childElementContainer.append(t.element),e.items.AbstractContentItem.prototype.addChild.call(this,t,i),o=1/this.contentItems.length*100,n===!0)return void this.emitBubblingEvent("stateChanged");for(r=0;r<this.contentItems.length;r++)this.contentItems[r]===t?t.config[this._dimension]=o:(s=this.contentItems[r].config[this._dimension]*=(100-o)/100,this.contentItems[r].config[this._dimension]=s);this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")},removeChild:function(t,i){var n,o,s=t.config[this._dimension],r=e.utils.indexOf(t,this.contentItems),a=Math.max(r-1,0);if(r===-1)throw new Error("Can't remove child. ContentItem is not child of this Row or Column");for(this._splitter[a]&&(this._splitter[a]._$destroy(),this._splitter.splice(a,1)),n=0;n<this.contentItems.length;n++)this.contentItems[n]!==t&&(this.contentItems[n].config[this._dimension]+=s/(this.contentItems.length-1));e.items.AbstractContentItem.prototype.removeChild.call(this,t,i),1===this.contentItems.length&&this.config.isClosable===!0?(o=this.contentItems[0],this.contentItems=[],this.parent.replaceChild(this,o,!0)):(this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged"))},replaceChild:function(t,i){var n=t.config[this._dimension];e.items.AbstractContentItem.prototype.replaceChild.call(this,t,i),i.config[this._dimension]=n,this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")},setSize:function(){this.contentItems.length>0&&(this._calculateRelativeSizes(),this._setAbsoluteSizes()),this.emitBubblingEvent("stateChanged"),this.emit("resize")},_$init:function(){if(this.isInitialised!==!0){var t;for(e.items.AbstractContentItem.prototype._$init.call(this),t=0;t<this.contentItems.length-1;t++)this.contentItems[t].element.after(this._createSplitter(t).element)}},_setAbsoluteSizes:function(){var t,e,i,n=(this.contentItems.length-1)*this._splitterSize,o=this.element.width(),s=this.element.height(),r=0,a=[];for(this._isColumn?s-=n:o-=n,t=0;t<this.contentItems.length;t++)i=this._isColumn?Math.floor(s*(this.contentItems[t].config.height/100)):Math.floor(o*(this.contentItems[t].config.width/100)),r+=i,a.push(i);for(e=Math.floor((this._isColumn?s:o)-r),t=0;t<this.contentItems.length;t++)e-t>0&&a[t]++,this._isColumn?(this.contentItems[t].element.width(o),this.contentItems[t].element.height(a[t])):(this.contentItems[t].element.width(a[t]),this.contentItems[t].element.height(s))},_calculateRelativeSizes:function(){var t,e=0,i=[],n=this._isColumn?"height":"width";for(t=0;t<this.contentItems.length;t++)void 0!==this.contentItems[t].config[n]?e+=this.contentItems[t].config[n]:i.push(this.contentItems[t]);if(100!==Math.round(e))if(Math.round(e)<100&&i.length>0)for(t=0;t<i.length;t++)i[t].config[n]=(100-e)/i.length;else{if(Math.round(e)>100)for(t=0;t<i.length;t++)i[t].config[n]=50,e+=50;for(t=0;t<this.contentItems.length;t++)this.contentItems[t].config[n]=this.contentItems[t].config[n]/e*100}},_createSplitter:function(t){var i;return i=new e.controls.Splitter(this._isColumn,this._splitterSize),i.on("drag",e.utils.fnBind(this._onSplitterDrag,this,[i]),this),i.on("dragStop",e.utils.fnBind(this._onSplitterDragStop,this,[i]),this),i.on("dragStart",e.utils.fnBind(this._onSplitterDragStart,this,[i]),this),this._splitter.splice(t,0,i),i},_getItemsForSplitter:function(t){var i=e.utils.indexOf(t,this._splitter);return{before:this.contentItems[i],after:this.contentItems[i+1]}},_onSplitterDragStart:function(t){var e=this._getItemsForSplitter(t),i=this.layoutManager.config.dimensions[this._isColumn?"minItemHeight":"minItemWidth"];this._splitterPosition=0,this._splitterMinPosition=-1*(e.before.element[this._dimension]()-i),this._splitterMaxPosition=e.after.element[this._dimension]()-i},_onSplitterDrag:function(t,e,i){var n=this._isColumn?i:e;n>this._splitterMinPosition&&n<this._splitterMaxPosition&&(this._splitterPosition=n,t.element.css(this._isColumn?"top":"left",n))},_onSplitterDragStop:function(t){var i=this._getItemsForSplitter(t),n=i.before.element[this._dimension](),o=i.after.element[this._dimension](),s=(this._splitterPosition+n)/(n+o),r=i.before.config[this._dimension]+i.after.config[this._dimension];i.before.config[this._dimension]=s*r,i.after.config[this._dimension]=(1-s)*r,t.element.css({top:0,left:0}),e.utils.animFrame(e.utils.fnBind(this.callDownwards,this,["setSize"]))}}),e.items.Stack=function(i,n,o){e.items.AbstractContentItem.call(this,i,n,o),this.element=t('<div class="lm_item lm_stack"></div>'),this._activeContentItem=null,this._dropZones={},this._dropSegment=null,this._contentAreaDimensions=null,this._dropIndex=null,this.isStack=!0,this.childElementContainer=t('<div class="lm_items"></div>'),this.header=new e.controls.Header(i,this),i.config.settings.hasHeaders===!0&&this.element.append(this.header.element),this.element.append(this.childElementContainer)},e.utils.extend(e.items.Stack,e.items.AbstractContentItem),e.utils.copy(e.items.Stack.prototype,{setSize:function(){var t,e=this.element.width(),i=this.element.height()-this.layoutManager.config.dimensions.headerHeight;for(this.childElementContainer.width(e),this.childElementContainer.height(i),t=0;t<this.contentItems.length;t++)this.contentItems[t].element.width(e).height(i);this.emit("resize"),this.emitBubblingEvent("stateChanged")},_$init:function(){var t,i;if(this.isInitialised!==!0){for(e.items.AbstractContentItem.prototype._$init.call(this),t=0;t<this.contentItems.length;t++)this.header.createTab(this.contentItems[t]),this.contentItems[t]._$hide();if(this.contentItems.length>0){if(i=this.contentItems[this.config.activeItemIndex||0],!i)throw new Error("Configured activeItemIndex out of bounds");this.setActiveContentItem(i)}}},setActiveContentItem:function(t){if(e.utils.indexOf(t,this.contentItems)===-1)throw new Error("contentItem is not a child of this stack");null!==this._activeContentItem&&this._activeContentItem._$hide(),this._activeContentItem=t,this.header.setActiveContentItem(t),t._$show(),this.emit("activeContentItemChanged",t),this.emitBubblingEvent("stateChanged")},getActiveContentItem:function(){return this.header.activeContentItem},addChild:function(t,i){t=this.layoutManager._$normalizeContentItem(t,this),e.items.AbstractContentItem.prototype.addChild.call(this,t,i),this.childElementContainer.append(t.element),this.header.createTab(t,i),this.setActiveContentItem(t),this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")},removeChild:function(t,i){var n=e.utils.indexOf(t,this.contentItems);e.items.AbstractContentItem.prototype.removeChild.call(this,t,i),this.header.removeTab(t),this.contentItems.length>0?this.setActiveContentItem(this.contentItems[Math.max(n-1,0)]):this._activeContentItem=null,this.emitBubblingEvent("stateChanged")},_$destroy:function(){e.items.AbstractContentItem.prototype._$destroy.call(this),this.header._$destroy()},_$onDrop:function(t){if("header"===this._dropSegment)return this._resetHeaderDropZone(),void this.addChild(t,this._dropIndex);if("body"===this._dropSegment)return void this.addChild(t);var i,n,o,s="top"===this._dropSegment||"bottom"===this._dropSegment,r="left"===this._dropSegment||"right"===this._dropSegment,a="top"===this._dropSegment||"left"===this._dropSegment,h=s&&this.parent.isColumn||r&&this.parent.isRow,l=s?"column":"row",c=s?"height":"width";t.isComponent&&(n=this.layoutManager.createContentItem({type:"stack"},this),n._$init(),n.addChild(t),t=n),h?(i=e.utils.indexOf(this,this.parent.contentItems),this.parent.addChild(t,a?i:i+1,!0),this.config[c]*=.5,t.config[c]=this.config[c],this.parent.callDownwards("setSize")):(l=s?"column":"row",o=this.layoutManager.createContentItem({type:l},this),this.parent.replaceChild(this,o),o.addChild(t,a?0:void 0,!0),o.addChild(this,a?void 0:0,!0),this.config[c]=50,t.config[c]=50,o.callDownwards("setSize"))},_$highlightDropZone:function(t,e){var i,n;for(i in this._contentAreaDimensions)if(n=this._contentAreaDimensions[i].hoverArea,n.x1<t&&n.x2>t&&n.y1<e&&n.y2>e)return void("header"===i?(this._dropSegment="header",this._highlightHeaderDropZone(t)):(this._resetHeaderDropZone(),this._highlightBodyDropZone(i)))},_$getArea:function(){if(this.element.is(":visible")===!1)return null;var t=e.items.AbstractContentItem.prototype._$getArea,i=t.call(this,this.header.element),n=t.call(this,this.childElementContainer),o=n.x2-n.x1,s=n.y2-n.y1;return this._contentAreaDimensions={header:{hoverArea:{x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2},highlightArea:{x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2}}},this._activeContentItem&&this._activeContentItem.isComponent===!1?i:0===this.contentItems.length?(this._contentAreaDimensions.body={hoverArea:{x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2},highlightArea:{x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2}},t.call(this,this.element)):(this._contentAreaDimensions.left={hoverArea:{x1:n.x1,y1:n.y1,x2:n.x1+.25*o,y2:n.y2},highlightArea:{x1:n.x1,y1:n.y1,x2:n.x1+.5*o,y2:n.y2}},this._contentAreaDimensions.top={hoverArea:{x1:n.x1+.25*o,y1:n.y1,x2:n.x1+.75*o,y2:n.y1+.5*s},highlightArea:{x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y1+.5*s}},this._contentAreaDimensions.right={hoverArea:{x1:n.x1+.75*o,y1:n.y1,x2:n.x2,y2:n.y2},highlightArea:{x1:n.x1+.5*o,y1:n.y1,x2:n.x2,y2:n.y2}},this._contentAreaDimensions.bottom={hoverArea:{x1:n.x1+.25*o,y1:n.y1+.5*s,x2:n.x1+.75*o,y2:n.y2},highlightArea:{x1:n.x1,y1:n.y1+.5*s,x2:n.x2,y2:n.y2}},t.call(this,this.element))},_highlightHeaderDropZone:function(t){var e,i,n,o,s,r,a,h,l,c=this.header.tabs.length,m=!1;if(0===c)return a=this.header.element.offset(),void this.layoutManager.dropTargetIndicator.highlightArea({x1:a.left,x2:a.left+100,y1:a.top+this.header.element.height()-20,y2:a.top+this.header.element.height()});for(e=0;e<c;e++)if(i=this.header.tabs[e].element,s=i.offset(),o=s.left,n=s.top,h=i.width(),t>o&&t<o+h){m=!0;break}m===!1&&t<o||(l=o+h/2,t<l?(this._dropIndex=e,i.before(this.layoutManager.tabDropPlaceholder)):(this._dropIndex=Math.min(e+1,c),i.after(this.layoutManager.tabDropPlaceholder)),r=this.layoutManager.tabDropPlaceholder.offset().left,this.layoutManager.dropTargetIndicator.highlightArea({x1:r,x2:r+this.layoutManager.tabDropPlaceholder.width(),y1:n,y2:n+i.innerHeight()}))},_resetHeaderDropZone:function(){this.layoutManager.tabDropPlaceholder.remove()},_highlightBodyDropZone:function(t){var e=this._contentAreaDimensions[t].highlightArea;this.layoutManager.dropTargetIndicator.highlightArea(e),this._dropSegment=t}}),e.utils.BubblingEvent=function(t,e){this.name=t,this.origin=e,this.isPropagationStopped=!1},e.utils.BubblingEvent.prototype.stopPropagation=function(){this.isPropagationStopped=!0},e.utils.ConfigMinifier=function(){this._keys=["settings","hasHeaders","constrainDragToContainer","selectionEnabled","dimensions","borderWidth","minItemHeight","minItemWidth","headerHeight","dragProxyWidth","dragProxyHeight","labels","close","maximise","minimise","popout","content","componentName","componentState","id","width","type","height","isClosable","title","popoutWholeStack","openPopouts","parentId","activeItemIndex","reorderEnabled"],this._values=[!0,!1,"row","column","stack","component","close","maximise","minimise","open in new window"]},e.utils.copy(e.utils.ConfigMinifier.prototype,{minifyConfig:function(t){var e={};return this._nextLevel(t,e,"_min"),e},unminifyConfig:function(t){var e={};return this._nextLevel(t,e,"_max"),e},_nextLevel:function(t,e,i){var n,o;for(n in t)t instanceof Array&&(n=parseInt(n,10)),t.hasOwnProperty(n)&&(o=this[i](n,this._keys),"object"==typeof t[n]?(e[o]=t[n]instanceof Array?[]:{},this._nextLevel(t[n],e[o],i)):e[o]=this[i](t[n],this._values))},_min:function(t,i){if("string"==typeof t&&1===t.length)return"___"+t;var n=e.utils.indexOf(t,i);return n===-1?t:n.toString(36)},_max:function(t,e){return"string"==typeof t&&1===t.length?e[parseInt(t,36)]:"string"==typeof t&&"___"===t.substr(0,3)?t[3]:t}}),e.utils.EventHub=function(i){e.utils.EventEmitter.call(this),this._layoutManager=i,this._dontPropagateToParent=null,this._childEventSource=null,this.on(e.utils.EventEmitter.ALL_EVENT,e.utils.fnBind(this._onEventFromThis,this)),t(window).on("gl_child_event",e.utils.fnBind(this._onEventFromChild,this))},e.utils.EventHub.prototype._onEventFromThis=function(){var t=Array.prototype.slice.call(arguments);this._layoutManager.isSubWindow&&t[0]!==this._dontPropagateToParent&&this._propagateToParent(t),this._propagateToChildren(t),this._dontPropagateToParent=null,this._childEventSource=null},e.utils.EventHub.prototype._$onEventFromParent=function(t){this._dontPropagateToParent=t[0],this.emit.apply(this,t)},e.utils.EventHub.prototype._onEventFromChild=function(t){this._childEventSource=t.originalEvent.__gl,this.emit.apply(this,t.originalEvent.__glArgs)},e.utils.EventHub.prototype._propagateToParent=function(t){var e,i="gl_child_event";document.createEvent?(e=window.opener.document.createEvent("HTMLEvents"),e.initEvent(i,!0,!0)):(e=window.opener.document.createEventObject(),e.eventType=i),e.eventName=i,e.__glArgs=t,e.__gl=this._layoutManager,document.createEvent?window.opener.dispatchEvent(e):window.opener.fireEvent("on"+e.eventType,e)},e.utils.EventHub.prototype._propagateToChildren=function(t){var e,i;for(i=0;i<this._layoutManager.openPopouts.length;i++)e=this._layoutManager.openPopouts[i].getGlInstance(),e!==this._childEventSource&&e.eventHub._$onEventFromParent(t)},e.utils.ReactComponentHandler=function(t,e){this._reactComponent=null,this._originalComponentWillUpdate=null,this._container=t,this._initialState=e,this._reactClass=this._getReactClass(),this._container.on("open",this._render,this),this._container.on("destroy",this._destroy,this)},e.utils.copy(e.utils.ReactComponentHandler.prototype,{_render:function(){this._reactComponent=ReactDOM.render(this._getReactComponent(),this._container.getElement()[0]),this._originalComponentWillUpdate=this._reactComponent.componentWillUpdate||function(){},this._reactComponent.componentWillUpdate=this._onUpdate.bind(this),this._container.getState()&&this._reactComponent.setState(this._container.getState())},_destroy:function(){ReactDOM.unmountComponentAtNode(this._container.getElement()[0]),this._container.off("open",this._render,this),this._container.off("destroy",this._destroy,this)},_onUpdate:function(t,e){this._container.setState(e),this._originalComponentWillUpdate.call(this._reactComponent,t,e)},_getReactClass:function(){var t,e=this._container._config.component;if(!e)throw new Error("No react component name. type: react-component needs a field `component`");if(t=this._container.layoutManager.getComponent(e),!t)throw new Error('React component "'+e+'" not found. Please register all components with GoldenLayout using `registerComponent(name, component)`');return t},_getReactComponent:function(){var e={glEventHub:this._container.layoutManager.eventHub,glContainer:this._container},i=t.extend(e,this._container._config.props);return React.createElement(this._reactClass,i)}})}(window.$);
ajax/libs/phaser/2.0.7/custom/p2.js
francescoagati/cdnjs
/** * The MIT License (MIT) * * Copyright (c) 2013 p2.js authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define('p2', (function() { return this.p2 = e(); })()):"undefined"!=typeof window?window.p2=e():"undefined"!=typeof global?self.p2=e():"undefined"!=typeof self&&(self.p2=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. 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. */ if(!GLMAT_EPSILON) { var GLMAT_EPSILON = 0.000001; } if(!GLMAT_ARRAY_TYPE) { var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; } /** * @class Common utilities * @name glMatrix */ var glMatrix = {}; /** * Sets the type of array used when creating new vectors and matricies * * @param {Type} type Array type, such as Float32Array or Array */ glMatrix.setMatrixArrayType = function(type) { GLMAT_ARRAY_TYPE = type; } if(typeof(exports) !== 'undefined') { exports.glMatrix = glMatrix; } /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. 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. */ /** * @class 2 Dimensional Vector * @name vec2 */ var vec2 = {}; /** * Creates a new, empty vec2 * * @returns {vec2} a new 2D vector */ vec2.create = function() { var out = new GLMAT_ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * * @param {vec2} a vector to clone * @returns {vec2} a new 2D vector */ vec2.clone = function(a) { var out = new GLMAT_ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new GLMAT_ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * * @param {vec2} out the receiving vector * @param {vec2} a the source vector * @returns {vec2} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * * @param {vec2} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Alias for {@link vec2.subtract} * @function */ vec2.sub = vec2.subtract; /** * Multiplies two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Alias for {@link vec2.multiply} * @function */ vec2.mul = vec2.multiply; /** * Divides two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Alias for {@link vec2.divide} * @function */ vec2.div = vec2.divide; /** * Returns the minimum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.min = function(out, a, b) { out[0] = Math.min(a[0], b[0]); out[1] = Math.min(a[1], b[1]); return out; }; /** * Returns the maximum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.max = function(out, a, b) { out[0] = Math.max(a[0], b[0]); out[1] = Math.max(a[1], b[1]); return out; }; /** * Scales a vec2 by a scalar number * * @param {vec2} out the receiving vector * @param {vec2} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {vec2} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for {@link vec2.distance} * @function */ vec2.dist = vec2.distance; /** * Calculates the squared euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Alias for {@link vec2.squaredDistance} * @function */ vec2.sqrDist = vec2.squaredDistance; /** * Calculates the length of a vec2 * * @param {vec2} a vector to calculate length of * @returns {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for {@link vec2.length} * @function */ vec2.len = vec2.length; /** * Calculates the squared length of a vec2 * * @param {vec2} a vector to calculate squared length of * @returns {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Alias for {@link vec2.squaredLength} * @function */ vec2.sqrLen = vec2.squaredLength; /** * Negates the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to negate * @returns {vec2} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to normalize * @returns {vec2} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Computes the cross product of two vec2's * Note that the cross product must by definition produce a 3D vector * * @param {vec3} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec3} out */ vec2.cross = function(out, a, b) { var z = a[0] * b[1] - a[1] * b[0]; out[0] = out[1] = 0; out[2] = z; return out; }; /** * Performs a linear interpolation between two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @param {Number} t interpolation amount between the two inputs * @returns {vec2} out */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Transforms the vec2 with a mat2 * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2} m matrix to transform with * @returns {vec2} out */ vec2.transformMat2 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y; out[1] = m[1] * x + m[3] * y; return out; }; /** * Transforms the vec2 with a mat2d * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2d} m matrix to transform with * @returns {vec2} out */ vec2.transformMat2d = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; }; /** * Transforms the vec2 with a mat3 * 3rd vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat3} m matrix to transform with * @returns {vec2} out */ vec2.transformMat3 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[3] * y + m[6]; out[1] = m[1] * x + m[4] * y + m[7]; return out; }; /** * Transforms the vec2 with a mat4 * 3rd vector component is implicitly '0' * 4th vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat4} m matrix to transform with * @returns {vec2} out */ vec2.transformMat4 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[4] * y + m[12]; out[1] = m[1] * x + m[5] * y + m[13]; return out; }; /** * Perform some operation over an array of vec2s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */ vec2.forEach = (function() { var vec = vec2.create(); return function(a, stride, offset, count, fn, arg) { var i, l; if(!stride) { stride = 2; } if(!offset) { offset = 0; } if(count) { l = Math.min((count * stride) + offset, a.length); } else { l = a.length; } for(i = offset; i < l; i += stride) { vec[0] = a[i]; vec[1] = a[i+1]; fn(vec, vec, arg); a[i] = vec[0]; a[i+1] = vec[1]; } return a; }; })(); /** * Returns a string representation of a vector * * @param {vec2} vec vector to represent as a string * @returns {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; if(typeof(exports) !== 'undefined') { exports.vec2 = vec2; } },{}],2:[function(require,module,exports){ var Scalar = require('./Scalar'); module.exports = Line; /** * Container for line-related functions * @class Line */ function Line(){}; /** * Compute the intersection between two lines. * @static * @method lineInt * @param {Array} l1 Line vector 1 * @param {Array} l2 Line vector 2 * @param {Number} precision Precision to use when checking if the lines are parallel * @return {Array} The intersection point. */ Line.lineInt = function(l1,l2,precision){ precision = precision || 0; var i = [0,0]; // point var a1, b1, c1, a2, b2, c2, det; // scalars a1 = l1[1][1] - l1[0][1]; b1 = l1[0][0] - l1[1][0]; c1 = a1 * l1[0][0] + b1 * l1[0][1]; a2 = l2[1][1] - l2[0][1]; b2 = l2[0][0] - l2[1][0]; c2 = a2 * l2[0][0] + b2 * l2[0][1]; det = a1 * b2 - a2*b1; if (!Scalar.eq(det, 0, precision)) { // lines are not parallel i[0] = (b2 * c1 - b1 * c2) / det; i[1] = (a1 * c2 - a2 * c1) / det; } return i; }; /** * Checks if two line segments intersects. * @method segmentsIntersect * @param {Array} p1 The start vertex of the first line segment. * @param {Array} p2 The end vertex of the first line segment. * @param {Array} q1 The start vertex of the second line segment. * @param {Array} q2 The end vertex of the second line segment. * @return {Boolean} True if the two line segments intersect */ Line.segmentsIntersect = function(p1, p2, q1, q2){ var dx = p2[0] - p1[0]; var dy = p2[1] - p1[1]; var da = q2[0] - q1[0]; var db = q2[1] - q1[1]; // segments are parallel if(da*dy - db*dx == 0) return false; var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx) var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy) return (s>=0 && s<=1 && t>=0 && t<=1); }; },{"./Scalar":5}],3:[function(require,module,exports){ module.exports = Point; /** * Point related functions * @class Point */ function Point(){}; /** * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. * @static * @method area * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Point.area = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))); }; Point.left = function(a,b,c){ return Point.area(a,b,c) > 0; }; Point.leftOn = function(a,b,c) { return Point.area(a, b, c) >= 0; }; Point.right = function(a,b,c) { return Point.area(a, b, c) < 0; }; Point.rightOn = function(a,b,c) { return Point.area(a, b, c) <= 0; }; var tmpPoint1 = [], tmpPoint2 = []; /** * Check if three points are collinear * @method collinear * @param {Array} a * @param {Array} b * @param {Array} c * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. * @return {Boolean} */ Point.collinear = function(a,b,c,thresholdAngle) { if(!thresholdAngle) return Point.area(a, b, c) == 0; else { var ab = tmpPoint1, bc = tmpPoint2; ab[0] = b[0]-a[0]; ab[1] = b[1]-a[1]; bc[0] = c[0]-b[0]; bc[1] = c[1]-b[1]; var dot = ab[0]*bc[0] + ab[1]*bc[1], magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]), magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]), angle = Math.acos(dot/(magA*magB)); return angle < thresholdAngle; } }; Point.sqdist = function(a,b){ var dx = b[0] - a[0]; var dy = b[1] - a[1]; return dx * dx + dy * dy; }; },{}],4:[function(require,module,exports){ var Line = require("./Line") , Point = require("./Point") , Scalar = require("./Scalar") module.exports = Polygon; /** * Polygon class. * @class Polygon * @constructor */ function Polygon(){ /** * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] * @property vertices * @type {Array} */ this.vertices = []; } /** * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. * @method at * @param {Number} i * @return {Array} */ Polygon.prototype.at = function(i){ var v = this.vertices, s = v.length; return v[i < 0 ? i % s + s : i % s]; }; /** * Get first vertex * @method first * @return {Array} */ Polygon.prototype.first = function(){ return this.vertices[0]; }; /** * Get last vertex * @method last * @return {Array} */ Polygon.prototype.last = function(){ return this.vertices[this.vertices.length-1]; }; /** * Clear the polygon data * @method clear * @return {Array} */ Polygon.prototype.clear = function(){ this.vertices.length = 0; }; /** * Append points "from" to "to"-1 from an other polygon "poly" onto this one. * @method append * @param {Polygon} poly The polygon to get points from. * @param {Number} from The vertex index in "poly". * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. * @return {Array} */ Polygon.prototype.append = function(poly,from,to){ if(typeof(from) == "undefined") throw new Error("From is not given!"); if(typeof(to) == "undefined") throw new Error("To is not given!"); if(to-1 < from) throw new Error("lol1"); if(to > poly.vertices.length) throw new Error("lol2"); if(from < 0) throw new Error("lol3"); for(var i=from; i<to; i++){ this.vertices.push(poly.vertices[i]); } }; /** * Make sure that the polygon vertices are ordered counter-clockwise. * @method makeCCW */ Polygon.prototype.makeCCW = function(){ var br = 0, v = this.vertices; // find bottom right point for (var i = 1; i < this.vertices.length; ++i) { if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) { br = i; } } // reverse poly if clockwise if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { this.reverse(); } }; /** * Reverse the vertices in the polygon * @method reverse */ Polygon.prototype.reverse = function(){ var tmp = []; for(var i=0, N=this.vertices.length; i!==N; i++){ tmp.push(this.vertices.pop()); } this.vertices = tmp; }; /** * Check if a point in the polygon is a reflex point * @method isReflex * @param {Number} i * @return {Boolean} */ Polygon.prototype.isReflex = function(i){ return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); }; var tmpLine1=[], tmpLine2=[]; /** * Check if two vertices in the polygon can see each other * @method canSee * @param {Number} a Vertex index 1 * @param {Number} b Vertex index 2 * @return {Boolean} */ Polygon.prototype.canSee = function(a,b) { var p, dist, l1=tmpLine1, l2=tmpLine2; if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) { return false; } dist = Point.sqdist(this.at(a), this.at(b)); for (var i = 0; i !== this.vertices.length; ++i) { // for each edge if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges continue; if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge l1[0] = this.at(a); l1[1] = this.at(b); l2[0] = this.at(i); l2[1] = this.at(i + 1); p = Line.lineInt(l1,l2); if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b return false; } } } return true; }; /** * Copy the polygon from vertex i to vertex j. * @method copy * @param {Number} i * @param {Number} j * @param {Polygon} [targetPoly] Optional target polygon to save in. * @return {Polygon} The resulting copy. */ Polygon.prototype.copy = function(i,j,targetPoly){ var p = targetPoly || new Polygon(); p.clear(); if (i < j) { // Insert all vertices from i to j for(var k=i; k<=j; k++) p.vertices.push(this.vertices[k]); } else { // Insert vertices 0 to j for(var k=0; k<=j; k++) p.vertices.push(this.vertices[k]); // Insert vertices i to end for(var k=i; k<this.vertices.length; k++) p.vertices.push(this.vertices[k]); } return p; }; /** * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon. * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices. * @method getCutEdges * @return {Array} */ Polygon.prototype.getCutEdges = function() { var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon(); var nDiags = Number.MAX_VALUE; for (var i = 0; i < this.vertices.length; ++i) { if (this.isReflex(i)) { for (var j = 0; j < this.vertices.length; ++j) { if (this.canSee(i, j)) { tmp1 = this.copy(i, j, tmpPoly).getCutEdges(); tmp2 = this.copy(j, i, tmpPoly).getCutEdges(); for(var k=0; k<tmp2.length; k++) tmp1.push(tmp2[k]); if (tmp1.length < nDiags) { min = tmp1; nDiags = tmp1.length; min.push([this.at(i), this.at(j)]); } } } } } return min; }; /** * Decomposes the polygon into one or more convex sub-Polygons. * @method decomp * @return {Array} An array or Polygon objects. */ Polygon.prototype.decomp = function(){ var edges = this.getCutEdges(); if(edges.length > 0) return this.slice(edges); else return [this]; }; /** * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. * @method slice * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() * @return {Array} */ Polygon.prototype.slice = function(cutEdges){ if(cutEdges.length == 0) return [this]; if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){ var polys = [this]; for(var i=0; i<cutEdges.length; i++){ var cutEdge = cutEdges[i]; // Cut all polys for(var j=0; j<polys.length; j++){ var poly = polys[j]; var result = poly.slice(cutEdge); if(result){ // Found poly! Cut and quit polys.splice(j,1); polys.push(result[0],result[1]); break; } } } return polys; } else { // Was given one edge var cutEdge = cutEdges; var i = this.vertices.indexOf(cutEdge[0]); var j = this.vertices.indexOf(cutEdge[1]); if(i != -1 && j != -1){ return [this.copy(i,j), this.copy(j,i)]; } else { return false; } } }; /** * Checks that the line segments of this polygon do not intersect each other. * @method isSimple * @param {Array} path An array of vertices e.g. [[0,0],[0,1],...] * @return {Boolean} * @todo Should it check all segments with all others? */ Polygon.prototype.isSimple = function(){ var path = this.vertices; // Check for(var i=0; i<path.length-1; i++){ for(var j=0; j<i-1; j++){ if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){ return false; } } } // Check the segment between the last and the first point to all others for(var i=1; i<path.length-2; i++){ if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){ return false; } } return true; }; function getIntersectionPoint(p1, p2, q1, q2, delta){ delta = delta || 0; var a1 = p2[1] - p1[1]; var b1 = p1[0] - p2[0]; var c1 = (a1 * p1[0]) + (b1 * p1[1]); var a2 = q2[1] - q1[1]; var b2 = q1[0] - q2[0]; var c2 = (a2 * q1[0]) + (b2 * q1[1]); var det = (a1 * b2) - (a2 * b1); if(!Scalar.eq(det,0,delta)) return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det] else return [0,0] } /** * Quickly decompose the Polygon into convex sub-polygons. * @method quickDecomp * @param {Array} result * @param {Array} [reflexVertices] * @param {Array} [steinerPoints] * @param {Number} [delta] * @param {Number} [maxlevel] * @param {Number} [level] * @return {Array} */ Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){ maxlevel = maxlevel || 100; level = level || 0; delta = delta || 25; result = typeof(result)!="undefined" ? result : []; reflexVertices = reflexVertices || []; steinerPoints = steinerPoints || []; var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons var poly = this, v = this.vertices; if(v.length < 3) return result; level++; if(level > maxlevel){ console.warn("quickDecomp: max level ("+maxlevel+") reached."); return result; } for (var i = 0; i < this.vertices.length; ++i) { if (poly.isReflex(i)) { reflexVertices.push(poly.vertices[i]); upperDist = lowerDist = Number.MAX_VALUE; for (var j = 0; j < this.vertices.length; ++j) { if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly d = Point.sqdist(poly.vertices[i], p); if (d < lowerDist) { // keep only the closest intersection lowerDist = d; lowerInt = p; lowerIndex = j; } } } if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); if (Point.left(poly.at(i - 1), poly.at(i), p)) { d = Point.sqdist(poly.vertices[i], p); if (d < upperDist) { upperDist = d; upperInt = p; upperIndex = j; } } } } // if there are no vertices to connect to, choose a point in the middle if (lowerIndex == (upperIndex + 1) % this.vertices.length) { //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); p[0] = (lowerInt[0] + upperInt[0]) / 2; p[1] = (lowerInt[1] + upperInt[1]) / 2; steinerPoints.push(p); if (i < upperIndex) { //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); lowerPoly.append(poly, i, upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); if (lowerIndex != 0){ //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); upperPoly.append(poly,lowerIndex,poly.vertices.length); } //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); upperPoly.append(poly,0,i+1); } else { if (i != 0){ //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); lowerPoly.append(poly,i,poly.vertices.length); } //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); lowerPoly.append(poly,0,upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); upperPoly.append(poly,lowerIndex,i+1); } } else { // connect to the closest point within the triangle //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); if (lowerIndex > upperIndex) { upperIndex += this.vertices.length; } closestDist = Number.MAX_VALUE; if(upperIndex < lowerIndex){ return result; } for (var j = lowerIndex; j <= upperIndex; ++j) { if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { d = Point.sqdist(poly.at(i), poly.at(j)); if (d < closestDist) { closestDist = d; closestIndex = j % this.vertices.length; } } } if (i < closestIndex) { lowerPoly.append(poly,i,closestIndex+1); if (closestIndex != 0){ upperPoly.append(poly,closestIndex,v.length); } upperPoly.append(poly,0,i+1); } else { if (i != 0){ lowerPoly.append(poly,i,v.length); } lowerPoly.append(poly,0,closestIndex+1); upperPoly.append(poly,closestIndex,i+1); } } // solve smallest poly first if (lowerPoly.vertices.length < upperPoly.vertices.length) { lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } else { upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } return result; } } result.push(this); return result; }; /** * Remove collinear points in the polygon. * @method removeCollinearPoints * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. * @return {Number} The number of points removed */ Polygon.prototype.removeCollinearPoints = function(precision){ var num = 0; for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ // Remove the middle point this.vertices.splice(i%this.vertices.length,1); i--; // Jump one point forward. Otherwise we may get a chain removal num++; } } return num; }; },{"./Line":2,"./Point":3,"./Scalar":5}],5:[function(require,module,exports){ module.exports = Scalar; /** * Scalar functions * @class Scalar */ function Scalar(){} /** * Check if two scalars are equal * @static * @method eq * @param {Number} a * @param {Number} b * @param {Number} [precision] * @return {Boolean} */ Scalar.eq = function(a,b,precision){ precision = precision || 0; return Math.abs(a-b) < precision; }; },{}],6:[function(require,module,exports){ module.exports = { Polygon : require("./Polygon"), Point : require("./Point"), }; },{"./Point":3,"./Polygon":4}],7:[function(require,module,exports){ module.exports={ "name": "p2", "version": "0.5.0", "description": "A JavaScript 2D physics engine.", "author": "Stefan Hedman <[email protected]> (http://steffe.se)", "keywords": [ "p2.js", "p2", "physics", "engine", "2d" ], "main": "./src/p2.js", "engines": { "node": "*" }, "repository": { "type": "git", "url": "https://github.com/schteppe/p2.js.git" }, "bugs": { "url": "https://github.com/schteppe/p2.js/issues" }, "licenses": [ { "type": "MIT" } ], "devDependencies": { "grunt": "~0.4.0", "grunt-contrib-jshint": "~0.9.2", "grunt-contrib-nodeunit": "~0.1.2", "grunt-contrib-uglify": "~0.4.0", "grunt-contrib-watch": "~0.5.0", "grunt-browserify": "~2.0.1", "z-schema": "~2.4.6" }, "dependencies": { "poly-decomp": "0.1.0", "gl-matrix": "2.1.0" } } },{}],8:[function(require,module,exports){ var vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = AABB; /** * Axis aligned bounding box class. * @class AABB * @constructor * @param {Object} [options] * @param {Array} [options.upperBound] * @param {Array} [options.lowerBound] */ function AABB(options){ /** * The lower bound of the bounding box. * @property lowerBound * @type {Array} */ this.lowerBound = vec2.create(); if(options && options.lowerBound){ vec2.copy(this.lowerBound, options.lowerBound); } /** * The upper bound of the bounding box. * @property upperBound * @type {Array} */ this.upperBound = vec2.create(); if(options && options.upperBound){ vec2.copy(this.upperBound, options.upperBound); } } var tmp = vec2.create(); /** * Set the AABB bounds from a set of points. * @method setFromPoints * @param {Array} points An array of vec2's. */ AABB.prototype.setFromPoints = function(points,position,angle){ var l = this.lowerBound, u = this.upperBound; vec2.set(l, Number.MAX_VALUE, Number.MAX_VALUE); vec2.set(u, -Number.MAX_VALUE, -Number.MAX_VALUE); for(var i=0; i<points.length; i++){ var p = points[i]; if(typeof(angle) === "number"){ vec2.rotate(tmp,p,angle); p = tmp; } for(var j=0; j<2; j++){ if(p[j] > u[j]){ u[j] = p[j]; } if(p[j] < l[j]){ l[j] = p[j]; } } } // Add offset if(position){ vec2.add(this.lowerBound, this.lowerBound, position); vec2.add(this.upperBound, this.upperBound, position); } }; /** * Copy bounds from an AABB to this AABB * @method copy * @param {AABB} aabb */ AABB.prototype.copy = function(aabb){ vec2.copy(this.lowerBound, aabb.lowerBound); vec2.copy(this.upperBound, aabb.upperBound); }; /** * Extend this AABB so that it covers the given AABB too. * @method extend * @param {AABB} aabb */ AABB.prototype.extend = function(aabb){ // Loop over x and y for(var i=0; i<2; i++){ // Extend lower bound if(aabb.lowerBound[i] < this.lowerBound[i]){ this.lowerBound[i] = aabb.lowerBound[i]; } // Upper if(aabb.upperBound[i] > this.upperBound[i]){ this.upperBound[i] = aabb.upperBound[i]; } } }; /** * Returns true if the given AABB overlaps this AABB. * @method overlaps * @param {AABB} aabb * @return {Boolean} */ AABB.prototype.overlaps = function(aabb){ var l1 = this.lowerBound, u1 = this.upperBound, l2 = aabb.lowerBound, u2 = aabb.upperBound; // l2 u2 // |---------| // |--------| // l1 u1 return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) && ((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1])); }; },{"../math/vec2":30,"../utils/Utils":47}],9:[function(require,module,exports){ var vec2 = require('../math/vec2') var Body = require('../objects/Body') module.exports = Broadphase; /** * Base class for broadphase implementations. * @class Broadphase * @constructor */ function Broadphase(type){ this.type = type; /** * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). * @property result * @type {Array} */ this.result = []; /** * The world to search for collision pairs in. To change it, use .setWorld() * @property world * @type {World} * @readOnly */ this.world = null; /** * The bounding volume type to use in the broadphase algorithms. * @property {Number} boundingVolumeType */ this.boundingVolumeType = Broadphase.AABB; } /** * Axis aligned bounding box type. * @static * @property {Number} AABB */ Broadphase.AABB = 1; /** * Bounding circle type. * @static * @property {Number} BOUNDING_CIRCLE */ Broadphase.BOUNDING_CIRCLE = 2; /** * Set the world that we are searching for collision pairs in * @method setWorld * @param {World} world */ Broadphase.prototype.setWorld = function(world){ this.world = world; }; /** * Get all potential intersecting body pairs. * @method getCollisionPairs * @param {World} world The world to search in. * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). */ Broadphase.prototype.getCollisionPairs = function(world){ throw new Error("getCollisionPairs must be implemented in a subclass!"); }; var dist = vec2.create(); /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.boundingRadiusCheck = function(bodyA, bodyB){ vec2.sub(dist, bodyA.position, bodyB.position); var d2 = vec2.squaredLength(dist), r = bodyA.boundingRadius + bodyB.boundingRadius; return d2 <= r*r; }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.aabbCheck = function(bodyA, bodyB){ if(bodyA.aabbNeedsUpdate){ bodyA.updateAABB(); } if(bodyB.aabbNeedsUpdate){ bodyB.updateAABB(); } return bodyA.aabb.overlaps(bodyB.aabb); }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.prototype.boundingVolumeCheck = function(bodyA, bodyB){ var result; switch(this.boundingVolumeType){ case Broadphase.BOUNDING_CIRCLE: result = Broadphase.boundingRadiusCheck(bodyA,bodyB); break; case Broadphase.AABB: result = Broadphase.aabbCheck(bodyA,bodyB); break; default: throw new Error('Bounding volume type not recognized: '+this.boundingVolumeType); } return result; }; /** * Check whether two bodies are allowed to collide at all. * @method canCollide * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.canCollide = function(bodyA, bodyB){ // Cannot collide static bodies if(bodyA.motionState === Body.STATIC && bodyB.motionState === Body.STATIC){ return false; } // Cannot collide static vs kinematic bodies if( (bodyA.motionState === Body.KINEMATIC && bodyB.motionState === Body.STATIC) || (bodyA.motionState === Body.STATIC && bodyB.motionState === Body.KINEMATIC)){ return false; } // Cannot collide kinematic vs kinematic if(bodyA.motionState === Body.KINEMATIC && bodyB.motionState === Body.KINEMATIC){ return false; } // Cannot collide both sleeping bodies if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ return false; } // Cannot collide if one is static and the other is sleeping if( (bodyA.sleepState === Body.SLEEPING && bodyB.motionState === Body.STATIC) || (bodyB.sleepState === Body.SLEEPING && bodyA.motionState === Body.STATIC)){ return false; } return true; }; Broadphase.NAIVE = 1; Broadphase.SAP = 2; },{"../math/vec2":30,"../objects/Body":31}],10:[function(require,module,exports){ var Circle = require('../shapes/Circle') , Plane = require('../shapes/Plane') , Particle = require('../shapes/Particle') , Broadphase = require('../collision/Broadphase') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils') module.exports = GridBroadphase; /** * Broadphase that uses axis-aligned bins. * @class GridBroadphase * @constructor * @extends Broadphase * @param {object} [options] * @param {number} [options.xmin] Lower x bound of the grid * @param {number} [options.xmax] Upper x bound * @param {number} [options.ymin] Lower y bound * @param {number} [options.ymax] Upper y bound * @param {number} [options.nx] Number of bins along x axis * @param {number} [options.ny] Number of bins along y axis * @todo Should have an option for dynamic scene size */ function GridBroadphase(options){ Broadphase.apply(this); options = Utils.defaults(options,{ xmin: -100, xmax: 100, ymin: -100, ymax: 100, nx: 10, ny: 10 }); this.xmin = options.xmin; this.ymin = options.ymin; this.xmax = options.xmax; this.ymax = options.ymax; this.nx = options.nx; this.ny = options.ny; this.binsizeX = (this.xmax-this.xmin) / this.nx; this.binsizeY = (this.ymax-this.ymin) / this.ny; } GridBroadphase.prototype = new Broadphase(); /** * Get collision pairs. * @method getCollisionPairs * @param {World} world * @return {Array} */ GridBroadphase.prototype.getCollisionPairs = function(world){ var result = [], bodies = world.bodies, Ncolliding = bodies.length, binsizeX = this.binsizeX, binsizeY = this.binsizeY, nx = this.nx, ny = this.ny, xmin = this.xmin, ymin = this.ymin, xmax = this.xmax, ymax = this.ymax; // Todo: make garbage free var bins=[], Nbins=nx*ny; for(var i=0; i<Nbins; i++){ bins.push([]); } var xmult = nx / (xmax-xmin); var ymult = ny / (ymax-ymin); // Put all bodies into bins for(var i=0; i!==Ncolliding; i++){ var bi = bodies[i]; var aabb = bi.aabb; var lowerX = Math.max(aabb.lowerBound[0], xmin); var lowerY = Math.max(aabb.lowerBound[1], ymin); var upperX = Math.min(aabb.upperBound[0], xmax); var upperY = Math.min(aabb.upperBound[1], ymax); var xi1 = Math.floor(xmult * (lowerX - xmin)); var yi1 = Math.floor(ymult * (lowerY - ymin)); var xi2 = Math.floor(xmult * (upperX - xmin)); var yi2 = Math.floor(ymult * (upperY - ymin)); // Put in bin for(var j=xi1; j<=xi2; j++){ for(var k=yi1; k<=yi2; k++){ var xi = j; var yi = k; var idx = xi*(ny-1) + yi; if(idx >= 0 && idx < Nbins){ bins[ idx ].push(bi); } } } } // Check each bin for(var i=0; i!==Nbins; i++){ var bin = bins[i]; for(var j=0, NbodiesInBin=bin.length; j!==NbodiesInBin; j++){ var bi = bin[j]; for(var k=0; k!==j; k++){ var bj = bin[k]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } } return result; }; },{"../collision/Broadphase":9,"../math/vec2":30,"../shapes/Circle":35,"../shapes/Particle":39,"../shapes/Plane":40,"../utils/Utils":47}],11:[function(require,module,exports){ var Circle = require('../shapes/Circle'), Plane = require('../shapes/Plane'), Shape = require('../shapes/Shape'), Particle = require('../shapes/Particle'), Broadphase = require('../collision/Broadphase'), vec2 = require('../math/vec2'); module.exports = NaiveBroadphase; /** * Naive broadphase implementation. Does N^2 tests. * * @class NaiveBroadphase * @constructor * @extends Broadphase */ function NaiveBroadphase(){ Broadphase.call(this, Broadphase.NAIVE); } NaiveBroadphase.prototype = new Broadphase(); /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ NaiveBroadphase.prototype.getCollisionPairs = function(world){ var bodies = world.bodies, result = this.result; result.length = 0; for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ var bi = bodies[i]; for(var j=0; j<i; j++){ var bj = bodies[j]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":9,"../math/vec2":30,"../shapes/Circle":35,"../shapes/Particle":39,"../shapes/Plane":40,"../shapes/Shape":42}],12:[function(require,module,exports){ var vec2 = require('../math/vec2') , sub = vec2.sub , add = vec2.add , dot = vec2.dot , Utils = require('../utils/Utils') , TupleDictionary = require('../utils/TupleDictionary') , Equation = require('../equations/Equation') , ContactEquation = require('../equations/ContactEquation') , FrictionEquation = require('../equations/FrictionEquation') , Circle = require('../shapes/Circle') , Convex = require('../shapes/Convex') , Shape = require('../shapes/Shape') , Body = require('../objects/Body') , Rectangle = require('../shapes/Rectangle'); module.exports = Narrowphase; // Temp things var yAxis = vec2.fromValues(0,1); var tmp1 = vec2.fromValues(0,0) , tmp2 = vec2.fromValues(0,0) , tmp3 = vec2.fromValues(0,0) , tmp4 = vec2.fromValues(0,0) , tmp5 = vec2.fromValues(0,0) , tmp6 = vec2.fromValues(0,0) , tmp7 = vec2.fromValues(0,0) , tmp8 = vec2.fromValues(0,0) , tmp9 = vec2.fromValues(0,0) , tmp10 = vec2.fromValues(0,0) , tmp11 = vec2.fromValues(0,0) , tmp12 = vec2.fromValues(0,0) , tmp13 = vec2.fromValues(0,0) , tmp14 = vec2.fromValues(0,0) , tmp15 = vec2.fromValues(0,0) , tmp16 = vec2.fromValues(0,0) , tmp17 = vec2.fromValues(0,0) , tmp18 = vec2.fromValues(0,0) , tmpArray = []; /** * Narrowphase. Creates contacts and friction given shapes and transforms. * @class Narrowphase * @constructor */ function Narrowphase(){ /** * @property contactEquations * @type {Array} */ this.contactEquations = []; /** * @property frictionEquations * @type {Array} */ this.frictionEquations = []; /** * Whether to make friction equations in the upcoming contacts. * @property enableFriction * @type {Boolean} */ this.enableFriction = true; /** * The friction slip force to use when creating friction equations. * @property slipForce * @type {Number} */ this.slipForce = 10.0; /** * The friction value to use in the upcoming friction equations. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; /** * Will be the .relativeVelocity in each produced FrictionEquation. * @property {Number} surfaceVelocity */ this.surfaceVelocity = 0; this.reuseObjects = true; this.reusableContactEquations = []; this.reusableFrictionEquations = []; /** * The restitution value to use in the next contact equations. * @property restitution * @type {Number} */ this.restitution = 0; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The stiffness value to use in the next friction equations. * @property frictionStiffness * @type {Number} */ this.frictionStiffness = Equation.DEFAULT_STIFFNESS; /** * The relaxation value to use in the next friction equations. * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = Equation.DEFAULT_RELAXATION; // Keep track of the colliding bodies last step this.collidingBodiesLastStep = new TupleDictionary(); } /** * Check if the bodies were in contact since the last reset(). * @method collidedLastStep * @param {Body} bi * @param {Body} bj * @return {Boolean} */ Narrowphase.prototype.collidedLastStep = function(bi,bj){ var id1 = bi.id|0, id2 = bj.id|0; return !!this.collidingBodiesLastStep.get(id1, id2); }; // "for in" loops aren't optimised in chrome... is there a better way to handle last-step collision memory? // Maybe do this: http://jsperf.com/reflection-vs-array-of-keys function clearObject(obj){ var l = obj.keys.length; while(l--){ delete obj[obj.keys[l]]; } obj.keys.length = 0; } /** * Throws away the old equations and gets ready to create new * @method reset * @param {World} world */ Narrowphase.prototype.reset = function(world){ this.collidingBodiesLastStep.reset(); for(var i=0; i!==this.contactEquations.length; i++){ var eq = this.contactEquations[i], id1 = eq.bodyA.id|0, id2 = eq.bodyB.id|0; this.collidingBodiesLastStep.set(id1, id2, true); } if(this.reuseObjects){ var ce = this.contactEquations, fe = this.frictionEquations, rfe = this.reusableFrictionEquations, rce = this.reusableContactEquations; Utils.appendArray(rce,ce); Utils.appendArray(rfe,fe); } // Reset this.contactEquations.length = this.frictionEquations.length = 0; }; /** * Creates a ContactEquation, either by reusing an existing object or creating a new one. * @method createContactEquation * @param {Body} bodyA * @param {Body} bodyB * @return {ContactEquation} */ Narrowphase.prototype.createContactEquation = function(bodyA,bodyB,shapeA,shapeB){ var c = this.reusableContactEquations.length ? this.reusableContactEquations.pop() : new ContactEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.restitution = this.restitution; c.firstImpact = !this.collidedLastStep(bodyA,bodyB); c.stiffness = this.stiffness; c.relaxation = this.relaxation; c.needsUpdate = true; c.enabled = true; return c; }; /** * Creates a FrictionEquation, either by reusing an existing object or creating a new one. * @method createFrictionEquation * @param {Body} bodyA * @param {Body} bodyB * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionEquation = function(bodyA,bodyB,shapeA,shapeB){ var c = this.reusableFrictionEquations.length ? this.reusableFrictionEquations.pop() : new FrictionEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.setSlipForce(this.slipForce); c.frictionCoefficient = this.frictionCoefficient; c.relativeVelocity = this.surfaceVelocity; c.enabled = true; c.needsUpdate = true; c.stiffness = this.frictionStiffness; c.relaxation = this.frictionRelaxation; return c; }; /** * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal. * @method createFrictionFromContact * @param {ContactEquation} contactEquation * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionFromContact = function(c){ var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB); vec2.copy(eq.contactPointA, c.contactPointA); vec2.copy(eq.contactPointB, c.contactPointB); vec2.rotate90cw(eq.t, c.normalA); eq.contactEquation = c; return eq; }; /** * Convex/line narrowphase * @method convexLine * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.CONVEX] = Narrowphase.prototype.convexLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; /** * Line/rectangle narrowphase * @method lineRectangle * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Rectangle} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.RECTANGLE] = Narrowphase.prototype.lineRectangle = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){ vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius); vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius); } var convexCapsule_tempRect = new Rectangle(1,1), convexCapsule_tempVec = vec2.create(); /** * Convex/capsule narrowphase * @method convexCapsule * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] = Narrowphase.prototype[Shape.CAPSULE | Shape.RECTANGLE] = Narrowphase.prototype.convexCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // Check the circles // Add offsets! var circlePos = convexCapsule_tempVec; vec2.set(circlePos, sj.length/2,0); vec2.rotate(circlePos,circlePos,aj); vec2.add(circlePos,circlePos,xj); var result1 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius); vec2.set(circlePos,-sj.length/2, 0); vec2.rotate(circlePos,circlePos,aj); vec2.add(circlePos,circlePos,xj); var result2 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius); if(justTest && (result1 || result2)) return true; // Check center rect var r = convexCapsule_tempRect; setConvexToCapsuleShapeMiddle(r,sj); var result = this.convexConvex(bi,si,xi,ai, bj,r,xj,aj, justTest); return result + result1 + result2; }; /** * Capsule/line narrowphase * @method lineCapsule * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] = Narrowphase.prototype.lineCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; var capsuleCapsule_tempVec1 = vec2.create(); var capsuleCapsule_tempVec2 = vec2.create(); var capsuleCapsule_tempRect1 = new Rectangle(1,1); /** * Capsule/capsule narrowphase * @method capsuleCapsule * @param {Body} bi * @param {Capsule} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] = Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // Check the circles // Add offsets! var circlePosi = capsuleCapsule_tempVec1, circlePosj = capsuleCapsule_tempVec2; var numContacts = 0; // Need 4 circle checks, between all for(var i=0; i<2; i++){ vec2.set(circlePosi,(i==0?-1:1)*si.length/2,0); vec2.rotate(circlePosi,circlePosi,ai); vec2.add(circlePosi,circlePosi,xi); for(var j=0; j<2; j++){ vec2.set(circlePosj,(j==0?-1:1)*sj.length/2, 0); vec2.rotate(circlePosj,circlePosj,aj); vec2.add(circlePosj,circlePosj,xj); var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius); if(justTest && result) return true; numContacts += result; } } // Check circles against the center rectangles var rect = capsuleCapsule_tempRect1; setConvexToCapsuleShapeMiddle(rect,si); var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest); if(justTest && result1) return true; numContacts += result1; setConvexToCapsuleShapeMiddle(rect,sj); var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest); if(justTest && result2) return true; numContacts += result2; return numContacts; }; /** * Line/line narrowphase * @method lineLine * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.LINE] = Narrowphase.prototype.lineLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; /** * Plane/line Narrowphase * @method planeLine * @param {Body} planeBody * @param {Plane} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle */ Narrowphase.prototype[Shape.PLANE | Shape.LINE] = Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle, lineBody, lineShape, lineOffset, lineAngle, justTest){ var worldVertex0 = tmp1, worldVertex1 = tmp2, worldVertex01 = tmp3, worldVertex11 = tmp4, worldEdge = tmp5, worldEdgeUnit = tmp6, dist = tmp7, worldNormal = tmp8, worldTangent = tmp9, verts = tmpArray numContacts = 0; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); vec2.rotate(worldNormal, yAxis, planeAngle); // Check line ends verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, planeOffset); var d = dot(dist,worldNormal); if(d < 0){ if(justTest) return true; var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape); numContacts++; vec2.copy(c.normalA, worldNormal); vec2.normalize(c.normalA,c.normalA); // distance vector along plane normal vec2.scale(dist, worldNormal, d); // Vector from plane center to contact sub(c.contactPointA, v, dist); sub(c.contactPointA, c.contactPointA, planeBody.position); // From line center to contact sub(c.contactPointB, v, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); // TODO : only need one friction equation if both points touch if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numContacts; }; Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] = Narrowphase.prototype.particleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius, 0); }; /** * Circle/line Narrowphase * @method circleLine * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations. * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules. * @param {Number} circleRadius If set, this value overrides the circle shape radius. */ Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] = Narrowphase.prototype.circleLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest, lineRadius, circleRadius){ var lineShape = sj, lineAngle = aj, lineBody = bj, lineOffset = xj, circleOffset = xi, circleBody = bi, circleShape = si, lineRadius = lineRadius || 0, circleRadius = typeof(circleRadius)!="undefined" ? circleRadius : circleShape.radius, orthoDist = tmp1, lineToCircleOrthoUnit = tmp2, projectedPoint = tmp3, centerDist = tmp4, worldTangent = tmp5, worldEdge = tmp6, worldEdgeUnit = tmp7, worldVertex0 = tmp8, worldVertex1 = tmp9, worldVertex01 = tmp10, worldVertex11 = tmp11, dist = tmp12, lineToCircle = tmp13, lineEndToLineRadius = tmp14, verts = tmpArray; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the plane spanned by the edge vs the circle sub(dist, circleOffset, worldVertex0); var d = dot(dist, worldTangent); // Distance from center of line to circle center sub(centerDist, worldVertex0, lineOffset); sub(lineToCircle, circleOffset, lineOffset); if(Math.abs(d) < circleRadius+lineRadius){ // Now project the circle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, circleOffset, orthoDist); // Add the missing line radius vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle)); vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit); vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius); add(projectedPoint,projectedPoint,lineToCircleOrthoUnit); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; var c = this.createContactEquation(circleBody,lineBody,si,sj); vec2.scale(c.normalA, orthoDist, -1); vec2.normalize(c.normalA, c.normalA); vec2.scale( c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, projectedPoint, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } // Add corner // @todo reuse array object verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, circleOffset); if(vec2.squaredLength(dist) < (circleRadius+lineRadius)*(circleRadius+lineRadius)){ if(justTest) return true; var c = this.createContactEquation(circleBody,lineBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, v, lineOffset); vec2.scale(lineEndToLineRadius, c.normalA, -lineRadius); add(c.contactPointB, c.contactPointB, lineEndToLineRadius); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } return 0; }; /** * Circle/capsule Narrowphase * @method circleCapsule * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] = Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius); }; /** * Circle/convex Narrowphase * @method circleConvex * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] = Narrowphase.prototype[Shape.CIRCLE | Shape.RECTANGLE] = Narrowphase.prototype.circleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, circleRadius){ var convexShape = sj, convexAngle = aj, convexBody = bj, convexOffset = xj, circleOffset = xi, circleBody = bi, circleShape = si, circleRadius = typeof(circleRadius)=="number" ? circleRadius : circleShape.radius; var worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldTangent = tmp5, centerDist = tmp6, convexToCircle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, candidate = tmp14, candidateDist = tmp15, minCandidate = tmp16, found = false, minCandidateDistance = Number.MAX_VALUE; var numReported = 0; // New algorithm: // 1. Check so center of circle is not inside the polygon. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. verts = convexShape.vertices; // Check all edges first for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldTangent, worldEdgeUnit); // Get point on circle, closest to the polygon vec2.scale(candidate,worldTangent,-circleShape.radius); add(candidate,candidate,circleOffset); if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){ vec2.sub(candidateDist,worldVertex0,candidate); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent)); /* // Check distance from the plane spanned by the edge vs the circle sub(dist, circleOffset, worldVertex0); var d = dot(dist, worldTangent); sub(centerDist, worldVertex0, convexOffset); sub(convexToCircle, circleOffset, convexOffset); if(d < circleRadius && dot(centerDist,convexToCircle) > 0){ // Now project the circle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, circleOffset, orthoDist); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){ closestEdgeDistance = d; closestEdge = i; vec2.copy(closestEdgeOrthoDist, orthoDist); vec2.copy(closestEdgeProjectedPoint, projectedPoint); } } } */ if(candidateDistance < minCandidateDistance){ vec2.copy(minCandidate,candidate); minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate); found = true; } } } if(found){ if(justTest) return true; var c = this.createContactEquation(circleBody,convexBody,si,sj); vec2.sub(c.normalA, minCandidate, circleOffset) vec2.normalize(c.normalA, c.normalA); vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return 1; } /* if(closestEdge != -1){ var c = this.createContactEquation(circleBody,convexBody); vec2.scale(c.normalA, closestEdgeOrthoDist, -1); vec2.normalize(c.normalA, c.normalA); vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return true; } */ // Check all vertices if(circleRadius > 0){ for(var i=0; i<verts.length; i++){ var localVertex = verts[i]; vec2.rotate(worldVertex, localVertex, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, circleOffset); if(vec2.squaredLength(dist) < circleRadius*circleRadius){ if(justTest) return true; var c = this.createContactEquation(circleBody,convexBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, worldVertex, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } } return 0; }; // Check if a point is in a polygon var pic_worldVertex0 = vec2.create(), pic_worldVertex1 = vec2.create(), pic_r0 = vec2.create(), pic_r1 = vec2.create(); function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){ var worldVertex0 = pic_worldVertex0, worldVertex1 = pic_worldVertex1, r0 = pic_r0, r1 = pic_r1, point = worldPoint, verts = convexShape.vertices, lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world // can we instead transform point to local of the convex??? vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(r0, worldVertex0, point); sub(r1, worldVertex1, point); var cross = vec2.crossLength(r0,r1); if(lastCross===null) lastCross = cross; // If we got a different sign of the distance vector, the point is out of the polygon if(cross*lastCross <= 0){ return false; } lastCross = cross; } return true; }; /** * Particle/convex Narrowphase * @method particleConvex * @param {Body} bi * @param {Particle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj * @todo use pointInConvex and code more similar to circleConvex */ Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] = Narrowphase.prototype[Shape.PARTICLE | Shape.RECTANGLE] = Narrowphase.prototype.particleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var convexShape = sj, convexAngle = aj, convexBody = bj, convexOffset = xj, particleOffset = xi, particleBody = bi, particleShape = si, worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldTangent = tmp5, centerDist = tmp6, convexToparticle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, r0 = tmp14, // vector from particle to vertex0 r1 = tmp15, localPoint = tmp16, candidateDist = tmp17, minEdgeNormal = tmp18, minCandidateDistance = Number.MAX_VALUE; var numReported = 0, found = false, verts = convexShape.vertices; // Check if the particle is in the polygon at all if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){ return 0; } if(justTest) return true; // Check edges first var lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); // Get world edge sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the infinite line (spanned by the edge) to the particle sub(dist, particleOffset, worldVertex0); var d = dot(dist, worldTangent); sub(centerDist, worldVertex0, convexOffset); sub(convexToparticle, particleOffset, convexOffset); /* if(d < 0 && dot(centerDist,convexToparticle) >= 0){ // Now project the particle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, particleOffset, orthoDist); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){ closestEdgeDistance = d; closestEdge = i; vec2.copy(closestEdgeOrthoDist, orthoDist); vec2.copy(closestEdgeProjectedPoint, projectedPoint); } } } */ vec2.sub(candidateDist,worldVertex0,particleOffset); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent)); if(candidateDistance < minCandidateDistance){ minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset); vec2.copy(minEdgeNormal,worldTangent); found = true; } } if(found){ var c = this.createContactEquation(particleBody,convexBody,si,sj); vec2.scale(c.normalA, minEdgeNormal, -1); vec2.normalize(c.normalA, c.normalA); // Particle has no extent to the contact point vec2.set(c.contactPointA, 0, 0); add(c.contactPointA, c.contactPointA, particleOffset); sub(c.contactPointA, c.contactPointA, particleBody.position); // From convex center to point sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return 1; } return 0; }; /** * Circle/circle Narrowphase * @method circleCircle * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Circle} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE] = Narrowphase.prototype.circleCircle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, radiusA, radiusB){ var bodyA = bi, shapeA = si, offsetA = xi, bodyB = bj, shapeB = sj, offsetB = xj, dist = tmp1, radiusA = radiusA || shapeA.radius, radiusB = radiusB || shapeB.radius; sub(dist,xi,xj); var r = radiusA + radiusB; if(vec2.squaredLength(dist) > r*r){ return 0; } if(justTest){ return true; } var c = this.createContactEquation(bodyA,bodyB,si,sj); sub(c.normalA, offsetB, offsetA); vec2.normalize(c.normalA,c.normalA); vec2.scale( c.contactPointA, c.normalA, radiusA); vec2.scale( c.contactPointB, c.normalA, -radiusB); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Plane/Convex Narrowphase * @method planeConvex * @param {Body} bi * @param {Plane} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = Narrowphase.prototype[Shape.PLANE | Shape.RECTANGLE] = Narrowphase.prototype.planeConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var convexBody = bj, convexOffset = xj, convexShape = sj, convexAngle = aj, planeBody = bi, planeShape = si, planeOffset = xi, planeAngle = ai; var worldVertex = tmp1, worldNormal = tmp2, dist = tmp3; var numReported = 0; vec2.rotate(worldNormal, yAxis, planeAngle); for(var i=0; i<convexShape.vertices.length; i++){ var v = convexShape.vertices[i]; vec2.rotate(worldVertex, v, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, planeOffset); if(dot(dist,worldNormal) <= Narrowphase.convexPrecision){ if(justTest){ return true; } // Found vertex numReported++; var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); sub(dist, worldVertex, planeOffset); vec2.copy(c.normalA, worldNormal); var d = dot(dist, c.normalA); vec2.scale(dist, c.normalA, d); // rj is from convex center to contact sub(c.contactPointB, worldVertex, convexBody.position); // ri is from plane center to contact sub( c.contactPointA, worldVertex, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numReported; }; /** * @method convexPlane * @deprecated Use .planeConvex() instead! */ Narrowphase.prototype.convexPlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ console.warn("Narrowphase.prototype.convexPlane is deprecated. Use planeConvex instead!"); return this.planeConvex( bj,sj,xj,aj, bi,si,xi,ai, justTest ); } /** * Narrowphase for particle vs plane * @method particlePlane * @param {Body} bi The particle body * @param {Particle} si Particle shape * @param {Array} xi World position for the particle * @param {Number} ai World angle for the particle * @param {Body} bj Plane body * @param {Plane} sj Plane shape * @param {Array} xj World position for the plane * @param {Number} aj World angle for the plane */ Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = Narrowphase.prototype.particlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var particleBody = bi, particleShape = si, particleOffset = xi, planeBody = bj, planeShape = sj, planeOffset = xj, planeAngle = aj; var dist = tmp1, worldNormal = tmp2; planeAngle = planeAngle || 0; sub(dist, particleOffset, planeOffset); vec2.rotate(worldNormal, yAxis, planeAngle); var d = dot(dist, worldNormal); if(d > 0) return 0; if(justTest) return true; var c = this.createContactEquation(planeBody,particleBody,sj,si); vec2.copy(c.normalA, worldNormal); vec2.scale( dist, c.normalA, d ); // dist is now the distance vector in the normal direction // ri is the particle position projected down onto the plane, from the plane center sub( c.contactPointA, particleOffset, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); // rj is from the body center to the particle center sub( c.contactPointB, particleOffset, particleBody.position ); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Circle/Particle Narrowphase * @method circleParticle * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Particle} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = Narrowphase.prototype.circleParticle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var circleBody = bi, circleShape = si, circleOffset = xi, particleBody = bj, particleShape = sj, particleOffset = xj, dist = tmp1; sub(dist, particleOffset, circleOffset); if(vec2.squaredLength(dist) > circleShape.radius*circleShape.radius) return 0; if(justTest) return true; var c = this.createContactEquation(circleBody,particleBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleShape.radius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); // Vector from particle center to contact point is zero sub(c.contactPointB, particleOffset, particleBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; var capsulePlane_tmpCircle = new Circle(1), capsulePlane_tmp1 = vec2.create(), capsulePlane_tmp2 = vec2.create(), capsulePlane_tmp3 = vec2.create(); Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = Narrowphase.prototype.planeCapsule = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var end1 = capsulePlane_tmp1, end2 = capsulePlane_tmp2, circle = capsulePlane_tmpCircle, dst = capsulePlane_tmp3; // Compute world end positions vec2.set(end1, -sj.length/2, 0); vec2.rotate(end1,end1,aj); add(end1,end1,xj); vec2.set(end2, sj.length/2, 0); vec2.rotate(end2,end2,aj); add(end2,end2,xj); circle.radius = sj.radius; // Do Narrowphase as two circles var numContacts1 = this.circlePlane(bj,circle,end1,0, bi,si,xi,ai, justTest), numContacts2 = this.circlePlane(bj,circle,end2,0, bi,si,xi,ai, justTest); if(justTest) return numContacts1 || numContacts2; else return numContacts1 + numContacts2; }; /** * @method capsulePlane * @deprecated Use .planeCapsule() instead! */ Narrowphase.prototype.capsulePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ console.warn("Narrowphase.prototype.capsulePlane() is deprecated. Use .planeCapsule() instead!"); return this.planeCapsule( bj,sj,xj,aj, bi,si,xi,ai, justTest ); } /** * Creates ContactEquations and FrictionEquations for a collision. * @method circlePlane * @param {Body} bi The first body that should be connected to the equations. * @param {Circle} si The circle shape participating in the collision. * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. * @param {Body} bj The second body that should be connected to the equations. * @param {Plane} sj The Plane shape that is participating * @param {Array} xj Extra offset for the plane shape. * @param {Number} aj Extra angle to apply to the plane */ Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] = Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var circleBody = bi, circleShape = si, circleOffset = xi, // Offset from body center, rotated! planeBody = bj, shapeB = sj, planeOffset = xj, planeAngle = aj; planeAngle = planeAngle || 0; // Vector from plane to circle var planeToCircle = tmp1, worldNormal = tmp2, temp = tmp3; sub(planeToCircle, circleOffset, planeOffset); // World plane normal vec2.rotate(worldNormal, yAxis, planeAngle); // Normal direction distance var d = dot(worldNormal, planeToCircle); if(d > circleShape.radius){ return 0; // No overlap. Abort. } if(justTest){ return true; } // Create contact var contact = this.createContactEquation(planeBody,circleBody,sj,si); // ni is the plane world normal vec2.copy(contact.normalA, worldNormal); // rj is the vector from circle center to the contact point vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); add(contact.contactPointB, contact.contactPointB, circleOffset); sub(contact.contactPointB, contact.contactPointB, circleBody.position); // ri is the distance from plane center to contact. vec2.scale(temp, contact.normalA, d); sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector add(contact.contactPointA, contact.contactPointA, planeOffset); sub(contact.contactPointA, contact.contactPointA, planeBody.position); this.contactEquations.push(contact); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(contact) ); } return 1; }; Narrowphase.convexPrecision = 1e-7; /** * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info. * @method convexConvex * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CONVEX] = Narrowphase.prototype[Shape.CONVEX | Shape.RECTANGLE] = Narrowphase.prototype[Shape.RECTANGLE] = Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){ var sepAxis = tmp1, worldPoint = tmp2, worldPoint0 = tmp3, worldPoint1 = tmp4, worldEdge = tmp5, projected = tmp6, penetrationVec = tmp7, dist = tmp8, worldNormal = tmp9, numContacts = 0, precision = precision || Narrowphase.convexPrecision; var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); if(!found){ return 0; } // Make sure the separating axis is directed from shape i to shape j sub(dist,xj,xi); if(dot(sepAxis,dist) > 0){ vec2.scale(sepAxis,sepAxis,-1); } // Find edges with normals closest to the separating axis var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); if(closestEdge1 === -1 || closestEdge2 === -1){ return 0; } // Loop over the shapes for(var k=0; k<2; k++){ var closestEdgeA = closestEdge1, closestEdgeB = closestEdge2, shapeA = si, shapeB = sj, offsetA = xi, offsetB = xj, angleA = ai, angleB = aj, bodyA = bi, bodyB = bj; if(k === 0){ // Swap! var tmp; tmp = closestEdgeA; closestEdgeA = closestEdgeB; closestEdgeB = tmp; tmp = shapeA; shapeA = shapeB; shapeB = tmp; tmp = offsetA; offsetA = offsetB; offsetB = tmp; tmp = angleA; angleA = angleB; angleB = tmp; tmp = bodyA; bodyA = bodyB; bodyB = tmp; } // Loop over 2 points in convex B for(var j=closestEdgeB; j<closestEdgeB+2; j++){ // Get world point var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length]; vec2.rotate(worldPoint, v, angleB); add(worldPoint, worldPoint, offsetB); var insideNumEdges = 0; // Loop over the 3 closest edges in convex A for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){ var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length], v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(worldNormal, worldEdge); // Normal points out of convex 1 vec2.normalize(worldNormal,worldNormal); sub(dist, worldPoint, worldPoint0); var d = dot(worldNormal,dist); if(d <= precision){ insideNumEdges++; } } if(insideNumEdges >= 3){ if(justTest){ return true; } // worldPoint was on the "inside" side of each of the 3 checked edges. // Project it to the center edge and use the projection direction as normal // Create contact var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); numContacts++; // Get center edge from body A var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(c.normalA, worldEdge); // Normal points out of convex A vec2.normalize(c.normalA,c.normalA); sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point var d = dot(c.normalA,dist); // Penetration vec2.scale(penetrationVec, c.normalA, d); // Vector penetration sub(c.contactPointA, worldPoint, offsetA); sub(c.contactPointA, c.contactPointA, penetrationVec); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); sub(c.contactPointB, worldPoint, offsetB); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); // Todo reduce to 1 friction equation if we have 2 contact points if(this.enableFriction) this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numContacts; }; // .projectConvex is called by other functions, need local tmp vectors var pcoa_tmp1 = vec2.fromValues(0,0); /** * Project a Convex onto a world-oriented axis * @method projectConvexOntoAxis * @static * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Array} worldAxis * @param {Array} result */ Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ var max=null, min=null, v, value, localAxis = pcoa_tmp1; // Convert the axis to local coords of the body vec2.rotate(localAxis, worldAxis, -convexAngle); // Get projected position of all vertices for(var i=0; i<convexShape.vertices.length; i++){ v = convexShape.vertices[i]; value = dot(v,localAxis); if(max === null || value > max) max = value; if(min === null || value < min) min = value; } if(min > max){ var t = min; min = max; max = t; } // Project the position of the body onto the axis - need to add this to the result var offset = dot(convexOffset, worldAxis); vec2.set( result, min + offset, max + offset); }; // .findSeparatingAxis is called by other functions, need local tmp vectors var fsa_tmp1 = vec2.fromValues(0,0) , fsa_tmp2 = vec2.fromValues(0,0) , fsa_tmp3 = vec2.fromValues(0,0) , fsa_tmp4 = vec2.fromValues(0,0) , fsa_tmp5 = vec2.fromValues(0,0) , fsa_tmp6 = vec2.fromValues(0,0) /** * Find a separating axis between the shapes, that maximizes the separating distance between them. * @method findSeparatingAxis * @static * @param {Convex} c1 * @param {Array} offset1 * @param {Number} angle1 * @param {Convex} c2 * @param {Array} offset2 * @param {Number} angle2 * @param {Array} sepAxis The resulting axis * @return {Boolean} Whether the axis could be found. */ Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){ var maxDist = null, overlap = false, found = false, edge = fsa_tmp1, worldPoint0 = fsa_tmp2, worldPoint1 = fsa_tmp3, normal = fsa_tmp4, span1 = fsa_tmp5, span2 = fsa_tmp6; for(var j=0; j!==2; j++){ var c = c1, angle = angle1; if(j===1){ c = c2; angle = angle2; } for(var i=0; i!==c.vertices.length; i++){ // Get the world edge vec2.rotate(worldPoint0, c.vertices[i], angle); vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); sub(edge, worldPoint1, worldPoint0); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); // Project hulls onto that normal Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); // Order by span position var a=span1, b=span2, swapped = false; if(span1[0] > span2[0]){ b=span1; a=span2; swapped = true; } // Get separating distance var dist = b[0] - a[1]; overlap = (dist <= Narrowphase.convexPrecision); if(maxDist===null || dist > maxDist){ vec2.copy(sepAxis, normal); maxDist = dist; found = overlap; } } } return found; }; // .getClosestEdge is called by other functions, need local tmp vectors var gce_tmp1 = vec2.fromValues(0,0) , gce_tmp2 = vec2.fromValues(0,0) , gce_tmp3 = vec2.fromValues(0,0) /** * Get the edge that has a normal closest to an axis. * @method getClosestEdge * @static * @param {Convex} c * @param {Number} angle * @param {Array} axis * @param {Boolean} flip * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. */ Narrowphase.getClosestEdge = function(c,angle,axis,flip){ var localAxis = gce_tmp1, edge = gce_tmp2, normal = gce_tmp3; // Convert the axis to local coords of the body vec2.rotate(localAxis, axis, -angle); if(flip){ vec2.scale(localAxis,localAxis,-1); } var closestEdge = -1, N = c.vertices.length; for(var i=0; i!==N; i++){ // Get the edge sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); var d = dot(normal,localAxis); if(closestEdge == -1 || d > maxDot){ closestEdge = i % N; maxDot = d; } } return closestEdge; }; var circleHeightfield_candidate = vec2.create(), circleHeightfield_dist = vec2.create(), circleHeightfield_v0 = vec2.create(), circleHeightfield_v1 = vec2.create(), circleHeightfield_minCandidate = vec2.create(), circleHeightfield_worldNormal = vec2.create(), circleHeightfield_minCandidateNormal = vec2.create(); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ var data = hfShape.data, radius = radius || circleShape.radius, w = hfShape.elementWidth, dist = circleHeightfield_dist, candidate = circleHeightfield_candidate, minCandidate = circleHeightfield_minCandidate, minCandidateNormal = circleHeightfield_minCandidateNormal, worldNormal = circleHeightfield_worldNormal, v0 = circleHeightfield_v0, v1 = circleHeightfield_v1; // Get the index of the points to test against var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); /*if(idxB < 0 || idxA >= data.length) return justTest ? false : 0;*/ if(idxA < 0) idxA = 0; if(idxB >= data.length) idxB = data.length-1; // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min) min = data[i]; if(data[i] > max) max = data[i]; } if(circlePos[1]-radius > max) return justTest ? false : 0; if(circlePos[1]+radius < min){ // Below the minimum point... We can just guess. // TODO } // 1. Check so center of circle is not inside the field. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. var found = false; // Check all edges first for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Get normal vec2.sub(worldNormal, v1, v0); vec2.rotate(worldNormal, worldNormal, Math.PI/2); vec2.normalize(worldNormal,worldNormal); // Get point on circle, closest to the edge vec2.scale(candidate,worldNormal,-radius); vec2.add(candidate,candidate,circlePos); // Distance from v0 to the candidate point vec2.sub(dist,candidate,v0); // Check if it is in the element "stick" var d = vec2.dot(dist,worldNormal); if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){ if(justTest){ return true; } found = true; // Store the candidate point, projected to the edge vec2.scale(dist,worldNormal,-d); vec2.add(minCandidate,candidate,dist); vec2.copy(minCandidateNormal,worldNormal); var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Normal is out of the heightfield vec2.copy(c.normalA, minCandidateNormal); // Vector from circle to heightfield vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); vec2.copy(c.contactPointA, minCandidate); vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(c) ); } } } // Check all vertices found = false; if(radius > 0){ for(var i=idxA; i<=idxB; i++){ // Get point vec2.set(v0, i*w, data[i]); vec2.add(v0,v0,hfPos); vec2.sub(dist, circlePos, v0); if(vec2.squaredLength(dist) < radius*radius){ if(justTest) return true; found = true; var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Construct normal - out of heightfield vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); sub(c.contactPointA, v0, hfPos); add(c.contactPointA, c.contactPointA, hfPos); sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } if(found){ return 1; } return 0; }; var convexHeightfield_v0 = vec2.create(), convexHeightfield_v1 = vec2.create(), convexHeightfield_tilePos = vec2.create(), convexHeightfield_tempConvexShape = new Convex([vec2.create(),vec2.create(),vec2.create(),vec2.create()]); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.RECTANGLE | Shape.HEIGHTFIELD] = Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, hfBody,hfShape,hfPos,hfAngle, justTest ){ var data = hfShape.data, w = hfShape.elementWidth, v0 = convexHeightfield_v0, v1 = convexHeightfield_v1, tilePos = convexHeightfield_tilePos, tileConvex = convexHeightfield_tempConvexShape; // Get the index of the points to test against var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); if(idxA < 0) idxA = 0; if(idxB >= data.length) idxB = data.length-1; // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min) min = data[i]; if(data[i] > max) max = data[i]; } if(convexBody.aabb.lowerBound[1] > max){ return justTest ? false : 0; } var found = false; var numContacts = 0; // Loop over all edges for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Construct a convex var tileHeight = 100; // todo vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.5); vec2.sub(tileConvex.vertices[0], v1, tilePos); vec2.sub(tileConvex.vertices[1], v0, tilePos); vec2.copy(tileConvex.vertices[2], tileConvex.vertices[1]); vec2.copy(tileConvex.vertices[3], tileConvex.vertices[0]); tileConvex.vertices[2][1] -= tileHeight; tileConvex.vertices[3][1] -= tileHeight; // Do convex collision numContacts += this.convexConvex( convexBody, convexShape, convexPos, convexAngle, hfBody, tileConvex, tilePos, 0, justTest); } return numContacts; }; },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Circle":35,"../shapes/Convex":36,"../shapes/Rectangle":41,"../shapes/Shape":42,"../utils/TupleDictionary":46,"../utils/Utils":47}],13:[function(require,module,exports){ var Utils = require('../utils/Utils') , Broadphase = require('../collision/Broadphase'); module.exports = SAPBroadphase; /** * Sweep and prune broadphase along one axis. * * @class SAPBroadphase * @constructor * @extends Broadphase */ function SAPBroadphase(){ Broadphase.call(this,Broadphase.SAP); /** * List of bodies currently in the broadphase. * @property axisList * @type {Array} */ this.axisList = []; /** * The world to search in. * @property world * @type {World} */ this.world = null; /** * The axis to sort along. * @property axisIndex * @type {Number} */ this.axisIndex = 0; var axisList = this.axisList; this._addBodyHandler = function(e){ axisList.push(e.body); }; this._removeBodyHandler = function(e){ // Remove from list var idx = axisList.indexOf(e.body); if(idx !== -1){ axisList.splice(idx,1); } }; } SAPBroadphase.prototype = new Broadphase(); /** * Change the world * @method setWorld * @param {World} world */ SAPBroadphase.prototype.setWorld = function(world){ // Clear the old axis array this.axisList.length = 0; // Add all bodies from the new world Utils.appendArray(this.axisList, world.bodies); // Remove old handlers, if any world .off("addBody",this._addBodyHandler) .off("removeBody",this._removeBodyHandler); // Add handlers to update the list of bodies. world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); this.world = world; }; /** * Sorts bodies along an axis. * @method sortAxisList * @param {Array} a * @param {number} axisIndex * @return {Array} */ SAPBroadphase.sortAxisList = function(a, axisIndex){ axisIndex = axisIndex|0; for(var i=1,l=a.length; i<l; i++) { var v = a[i]; for(var j=i - 1;j>=0;j--) { if(a[j].aabb.lowerBound[axisIndex] <= v.aabb.lowerBound[axisIndex]){ break; } a[j+1] = a[j]; } a[j+1] = v; } return a; }; /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ SAPBroadphase.prototype.getCollisionPairs = function(world){ var bodies = this.axisList, result = this.result, axisIndex = this.axisIndex; result.length = 0; // Update all AABBs if needed var l = bodies.length; while(l--){ var b = bodies[l]; if(b.aabbNeedsUpdate){ b.updateAABB(); } } // Sort the lists SAPBroadphase.sortAxisList(bodies, axisIndex); // Look through the X list for(var i=0, N=bodies.length|0; i!==N; i++){ var bi = bodies[i]; for(var j=i+1; j<N; j++){ var bj = bodies[j]; // Bounds overlap? var overlaps = (bj.aabb.lowerBound[axisIndex] <= bi.aabb.upperBound[axisIndex]); if(!overlaps){ break; } if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":9,"../utils/Utils":47}],14:[function(require,module,exports){ module.exports = Constraint; var Utils = require('../utils/Utils'); /** * Base constraint class. * * @class Constraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Number} type * @param {Object} [options] * @param {Object} [options.collideConnected=true] */ function Constraint(bodyA, bodyB, type, options){ this.type = type; options = Utils.defaults(options,{ collideConnected : true, wakeUpBodies : true, }); /** * Equations to be solved in this constraint * * @property equations * @type {Array} */ this.equations = []; /** * First body participating in the constraint. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint. * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * Set to true if you want the connected bodies to collide. * @property collideConnected * @type {Boolean} * @default true */ this.collideConnected = options.collideConnected; // Wake up bodies when connected if(options.wakeUpBodies){ if(bodyA){ bodyA.wakeUp(); } if(bodyB){ bodyB.wakeUp(); } } } /** * Updates the internal constraint parameters before solve. * @method update */ Constraint.prototype.update = function(){ throw new Error("method update() not implmemented in this Constraint subclass!"); }; Constraint.DISTANCE = 1; Constraint.GEAR = 2; Constraint.LOCK = 3; Constraint.PRISMATIC = 4; Constraint.REVOLUTE = 5; /** * Set stiffness for this constraint. * @method setStiffness * @param {Number} stiffness */ Constraint.prototype.setStiffness = function(stiffness){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.stiffness = stiffness; eq.needsUpdate = true; } }; /** * Set relaxation for this constraint. * @method setRelaxation * @param {Number} relaxation */ Constraint.prototype.setRelaxation = function(relaxation){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.relaxation = relaxation; eq.needsUpdate = true; } }; },{"../utils/Utils":47}],15:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') module.exports = DistanceConstraint; /** * Constraint that tries to keep the distance between two bodies constant. * * @class DistanceConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {number} distance The distance to keep between the bodies. * @param {object} [options] * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply. * @extends Constraint */ function DistanceConstraint(bodyA,bodyB,distance,options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options); /** * The distance to keep. * @property distance * @type {Number} */ this.distance = distance; /** * Local anchor in body A. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.create(); /** * Local anchor in body B. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.create(); var localAnchorA = this.localAnchorA; var localAnchorB = this.localAnchorB; var maxForce; if(typeof(options.maxForce)==="undefined" ){ maxForce = Number.MAX_VALUE; } else { maxForce = options.maxForce; } var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction this.equations = [ normal ]; // g = (xi - xj).dot(n) // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]' // ...and if we were to include offset points (TODO for now): // g = // (xj + rj - xi - ri).dot(n) - distance // // dg/dt = // (vj + wj x rj - vi - wi x ri).dot(n) = // { term 2 is near zero } = // [-n -ri x n n rj x n] * [vi wi vj wj]' = // G * W // // => G = [-n -rixn n rjxn] var r = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB var that = this; normal.computeGq = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, xi = bodyA.position, xj = bodyB.position; // Transform local anchors to world vec2.rotate(ri, localAnchorA, bodyA.angle); vec2.rotate(rj, localAnchorB, bodyB.angle); vec2.add(r, xi, rj); vec2.sub(r, r, ri); vec2.sub(r, r, xi); vec2.sub(r, bodyB.position, bodyA.position); return vec2.length(r) - that.distance; }; // Make the contact constraint bilateral this.setMaxForce(maxForce); } DistanceConstraint.prototype = new Constraint(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ var n = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB DistanceConstraint.prototype.update = function(){ var normal = this.equations[0], bodyA = this.bodyA, bodyB = this.bodyB, distance = this.distance, xi = bodyA.position, xj = bodyB.position, G = normal.G; // Transform local anchors to world vec2.rotate(ri, this.localAnchorA, bodyA.angle); vec2.rotate(rj, this.localAnchorB, bodyB.angle); // Caluclate cross products var rixn = vec2.crossLength(ri, n), rjxn = vec2.crossLength(rj, n); /* // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; */ vec2.sub(n, bodyB.position, bodyA.position); vec2.normalize(n,n); G[0] = -n[0]; G[1] = -n[1]; G[3] = n[0]; G[4] = n[1]; }; /** * Set the max force to be used * @method setMaxForce * @param {Number} f */ DistanceConstraint.prototype.setMaxForce = function(f){ var normal = this.equations[0]; normal.minForce = -f; normal.maxForce = f; }; /** * Get the max force * @method getMaxForce * @return {Number} */ DistanceConstraint.prototype.getMaxForce = function(f){ var normal = this.equations[0]; return normal.maxForce; }; },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],16:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , AngleLockEquation = require('../equations/AngleLockEquation') , vec2 = require('../math/vec2') module.exports = GearConstraint; /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class GearConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle=0] Relative angle between the bodies. * @param {Number} [options.ratio=1] Gear ratio. * @param {Number} [options.maxTorque] Maximum torque to apply. * @extends Constraint * @todo Ability to specify world points */ function GearConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); this.equations = [ new AngleLockEquation(bodyA,bodyB,options), ]; /** * The relative angle * @property angle * @type {Number} */ this.angle = typeof(options.angle) === "number" ? options.angle : 0; /** * The gear ratio. * @property ratio * @type {Number} */ this.ratio = typeof(options.ratio) === "number" ? options.ratio : 1; // Set max torque if(typeof(options.maxTorque) === "number"){ this.setMaxTorque(options.maxTorque); } } GearConstraint.prototype = new Constraint(); GearConstraint.prototype.update = function(){ var eq = this.equations[0]; if(eq.ratio !== this.ratio){ eq.setRatio(this.ratio); } eq.angle = this.angle; }; /** * Set the max torque for the constraint. * @method setMaxTorque * @param {Number} torque */ GearConstraint.prototype.setMaxTorque = function(torque){ this.equations[0].setMaxTorque(torque); }; /** * Get the max torque for the constraint. * @method getMaxTorque * @return {Number} */ GearConstraint.prototype.getMaxTorque = function(torque){ return this.equations[0].maxForce; }; },{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(require,module,exports){ var Constraint = require('./Constraint') , vec2 = require('../math/vec2') , Equation = require('../equations/Equation') module.exports = LockConstraint; /** * Locks the relative position between two bodies. * * @class LockConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. Default is the zero vector. * @param {number} [options.localAngleB=0] The angle of bodyB in bodyA's frame. * @param {number} [options.maxForce] * @extends Constraint */ function LockConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); var localOffsetB = options.localOffsetB || vec2.fromValues(0,0); localOffsetB = vec2.fromValues(localOffsetB[0],localOffsetB[1]); var localAngleB = options.localAngleB || 0; // Use 3 equations: // gx = (xj - xi - l) * xhat = 0 // gy = (xj - xi - l) * yhat = 0 // gr = (xi - xj + r) * that = 0 // // ...where: // l is the localOffsetB vector rotated to world in bodyA frame // r is the same vector but reversed and rotated from bodyB frame // xhat, yhat are world axis vectors // that is the tangent of r // // For the first two constraints, we get // G*W = (vj - vi - ldot ) * xhat // = (vj - vi - wi x l) * xhat // // Since (wi x l) * xhat = (l x xhat) * wi, we get // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] // // The last constraint gives // GW = (vi - vj + wj x r) * that // = [ that 0 -that (r x t) ] var x = new Equation(bodyA,bodyB,-maxForce,maxForce), y = new Equation(bodyA,bodyB,-maxForce,maxForce), rot = new Equation(bodyA,bodyB,-maxForce,maxForce); var l = vec2.create(), g = vec2.create(), that = this; x.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[0]; }; y.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[1]; }; var r = vec2.create(), t = vec2.create(); rot.computeGq = function(){ vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); vec2.scale(r,r,-1); vec2.sub(g,bodyA.position,bodyB.position); vec2.add(g,g,r); vec2.rotate(t,r,-Math.PI/2); vec2.normalize(t,t); return vec2.dot(g,t); }; /** * The offset of bodyB in bodyA's frame. * @property {Array} localOffsetB */ this.localOffsetB = localOffsetB; /** * The offset angle of bodyB in bodyA's frame. * @property {Number} localAngleB */ this.localAngleB = localAngleB; this.equations.push(x, y, rot); this.setMaxForce(maxForce); } LockConstraint.prototype = new Constraint(); /** * Set the maximum force to be applied. * @method setMaxForce * @param {Number} force */ LockConstraint.prototype.setMaxForce = function(force){ var eqs = this.equations; for(var i=0; i<this.equations.length; i++){ eqs[i].maxForce = force; eqs[i].minForce = -force; } }; /** * Get the max force. * @method getMaxForce * @return {Number} */ LockConstraint.prototype.getMaxForce = function(){ return this.equations[0].maxForce; }; var l = vec2.create(); var r = vec2.create(); var t = vec2.create(); var xAxis = vec2.fromValues(1,0); var yAxis = vec2.fromValues(0,1); LockConstraint.prototype.update = function(){ var x = this.equations[0], y = this.equations[1], rot = this.equations[2], bodyA = this.bodyA, bodyB = this.bodyB; vec2.rotate(l,this.localOffsetB,bodyA.angle); vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB); vec2.scale(r,r,-1); vec2.rotate(t,r,Math.PI/2); vec2.normalize(t,t); x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(l,xAxis); x.G[3] = 1; y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(l,yAxis); y.G[4] = 1; rot.G[0] = -t[0]; rot.G[1] = -t[1]; rot.G[3] = t[0]; rot.G[4] = t[1]; rot.G[5] = vec2.crossLength(r,t); }; },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(require,module,exports){ var Constraint = require('./Constraint') , ContactEquation = require('../equations/ContactEquation') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') , RotationalLockEquation = require('../equations/RotationalLockEquation') module.exports = PrismaticConstraint; /** * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. * * @class PrismaticConstraint * @constructor * @extends Constraint * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.maxForce] Max force to be applied by the constraint * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. * @param {Number} [options.upperLimit] * @param {Number} [options.lowerLimit] */ function PrismaticConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); // Get anchors var localAnchorA = vec2.fromValues(0,0), localAxisA = vec2.fromValues(1,0), localAnchorB = vec2.fromValues(0,0); if(options.localAnchorA) vec2.copy(localAnchorA, options.localAnchorA); if(options.localAxisA) vec2.copy(localAxisA, options.localAxisA); if(options.localAnchorB) vec2.copy(localAnchorB, options.localAnchorB); /** * @property localAnchorA * @type {Array} */ this.localAnchorA = localAnchorA; /** * @property localAnchorB * @type {Array} */ this.localAnchorB = localAnchorB; /** * @property localAxisA * @type {Array} */ this.localAxisA = localAxisA; /* The constraint violation for the common axis point is g = ( xj + rj - xi - ri ) * t := gg*t where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) Note the use of the chain rule. Now we identify the jacobian G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] The rotational part is just a rotation lock. */ var maxForce = this.maxForce = typeof(options.maxForce)!="undefined" ? options.maxForce : Number.MAX_VALUE; // Translational part var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); var ri = new vec2.create(), rj = new vec2.create(), gg = new vec2.create(), t = new vec2.create(); trans.computeGq = function(){ // g = ( xj + rj - xi - ri ) * t return vec2.dot(gg,t); }; trans.updateJacobian = function(){ var G = this.G, xi = bodyA.position, xj = bodyB.position; vec2.rotate(ri,localAnchorA,bodyA.angle); vec2.rotate(rj,localAnchorB,bodyB.angle); vec2.add(gg,xj,rj); vec2.sub(gg,gg,xi); vec2.sub(gg,gg,ri); vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); }; this.equations.push(trans); // Rotational part if(!options.disableRotationalLock){ var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); this.equations.push(rot); } /** * The position of anchor A relative to anchor B, along the constraint axis. * @property position * @type {Number} */ this.position = 0; this.velocity = 0; /** * Set to true to enable lower limit. * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; /** * Set to true to enable upper limit. * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; /** * Lower constraint limit. The constraint position is forced to be larger than this value. * @property lowerLimit * @type {Number} */ this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; /** * Upper constraint limit. The constraint position is forced to be smaller than this value. * @property upperLimit * @type {Number} */ this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; // Equations used for limits this.upperLimitEquation = new ContactEquation(bodyA,bodyB); this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); // Set max/min forces this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; /** * Equation used for the motor. * @property motorEquation * @type {Equation} */ this.motorEquation = new Equation(bodyA,bodyB); /** * The current motor state. Enable or disable the motor using .enableMotor * @property motorEnabled * @type {Boolean} */ this.motorEnabled = false; /** * Set the target speed for the motor. * @property motorSpeed * @type {Number} */ this.motorSpeed = 0; var that = this; var motorEquation = this.motorEquation; var old = motorEquation.computeGW; motorEquation.computeGq = function(){ return 0; }; motorEquation.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return this.transformedGmult(G,vi,wi,vj,wj) + that.motorSpeed; }; } PrismaticConstraint.prototype = new Constraint(); var worldAxisA = vec2.create(), worldAnchorA = vec2.create(), worldAnchorB = vec2.create(), orientedAnchorA = vec2.create(), orientedAnchorB = vec2.create(), tmp = vec2.create(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ PrismaticConstraint.prototype.update = function(){ var eqs = this.equations, trans = eqs[0], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation, bodyA = this.bodyA, bodyB = this.bodyB, localAxisA = this.localAxisA, localAnchorA = this.localAnchorA, localAnchorB = this.localAnchorB; trans.updateJacobian(); // Transform local things to world vec2.rotate(worldAxisA, localAxisA, bodyA.angle); vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); // Motor if(this.motorEnabled){ // G = [ a a x ri -a -a x rj ] var G = this.motorEquation.G; G[0] = worldAxisA[0]; G[1] = worldAxisA[1]; G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); G[3] = -worldAxisA[0]; G[4] = -worldAxisA[1]; G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); } /* Limits strategy: Add contact equation, with normal along the constraint axis. min/maxForce is set so the constraint is repulsive in the correct direction. Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. ^ | upperLimit x | ------ anchorB x<---| B | | | | ------ | ------ | | | | A |-->x anchorA ------ | x lowerLimit | axis */ if(this.upperLimitEnabled && relPosition > upperLimit){ // Update contact constraint normal, etc vec2.scale(upperLimitEquation.normalA, worldAxisA, -1); vec2.sub(upperLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(upperLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,upperLimit); vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp); if(eqs.indexOf(upperLimitEquation)==-1) eqs.push(upperLimitEquation); } else { var idx = eqs.indexOf(upperLimitEquation); if(idx != -1) eqs.splice(idx,1); } if(this.lowerLimitEnabled && relPosition < lowerLimit){ // Update contact constraint normal, etc vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,lowerLimit); vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); if(eqs.indexOf(lowerLimitEquation)==-1) eqs.push(lowerLimitEquation); } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx != -1) eqs.splice(idx,1); } }; /** * Enable the motor * @method enableMotor */ PrismaticConstraint.prototype.enableMotor = function(){ if(this.motorEnabled) return; this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ PrismaticConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled) return; var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , RotationalVelocityEquation = require('../equations/RotationalVelocityEquation') , RotationalLockEquation = require('../equations/RotationalLockEquation') , vec2 = require('../math/vec2') module.exports = RevoluteConstraint; var worldPivotA = vec2.create(), worldPivotB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1), g = vec2.create(); /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class RevoluteConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Array} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to. * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get sort of a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point. * @param {Array} pivotB See pivotA. * @param {Object} [options] * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. * @extends Constraint * @todo Ability to specify world points * @todo put pivot parameters in the options object? */ function RevoluteConstraint(bodyA, pivotA, bodyB, pivotB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; /** * @property {Array} pivotA */ this.pivotA = vec2.fromValues(pivotA[0],pivotA[1]); /** * @property {Array} pivotB */ this.pivotB = vec2.fromValues(pivotB[0],pivotB[1]); // Equations to be fed to the solver var eqs = this.equations = [ new Equation(bodyA,bodyB,-maxForce,maxForce), new Equation(bodyA,bodyB,-maxForce,maxForce), ]; var x = eqs[0]; var y = eqs[1]; var that = this; x.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,xAxis); }; y.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,yAxis); }; y.minForce = x.minForce = -maxForce; y.maxForce = x.maxForce = maxForce; this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); /** * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. * @property {Boolean} motorEnabled * @readOnly */ this.motorEnabled = false; /** * The constraint position. * @property angle * @type {Number} * @readOnly */ this.angle = 0; /** * Set to true to enable lower limit * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = false; /** * Set to true to enable upper limit * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = false; /** * The lower limit on the constraint angle. * @property lowerLimit * @type {Boolean} */ this.lowerLimit = 0; /** * The upper limit on the constraint angle. * @property upperLimit * @type {Boolean} */ this.upperLimit = 0; this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.upperLimitEquation.minForce = 0; this.lowerLimitEquation.maxForce = 0; } RevoluteConstraint.prototype = new Constraint(); RevoluteConstraint.prototype.update = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, pivotA = this.pivotA, pivotB = this.pivotB, eqs = this.equations, normal = eqs[0], tangent= eqs[1], x = eqs[0], y = eqs[1], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation; var relAngle = this.angle = bodyB.angle - bodyA.angle; if(this.upperLimitEnabled && relAngle > upperLimit){ upperLimitEquation.angle = upperLimit; if(eqs.indexOf(upperLimitEquation)==-1) eqs.push(upperLimitEquation); } else { var idx = eqs.indexOf(upperLimitEquation); if(idx != -1) eqs.splice(idx,1); } if(this.lowerLimitEnabled && relAngle < lowerLimit){ lowerLimitEquation.angle = lowerLimit; if(eqs.indexOf(lowerLimitEquation)==-1) eqs.push(lowerLimitEquation); } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx != -1) eqs.splice(idx,1); } /* The constraint violation is g = xj + rj - xi - ri ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: gdot = vj + wj x rj - vi - wi x ri We split this into x and y directions. (let x and y be unit vectors along the respective axes) gdot * x = ( vj + wj x rj - vi - wi x ri ) * x = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] = G*W ...and similar for y. We have then identified the jacobian entries for x and y directions: Gx = [ x (rj x x) -x -(ri x x)] Gy = [ y (rj x y) -y -(ri x y)] */ vec2.rotate(worldPivotA, pivotA, bodyA.angle); vec2.rotate(worldPivotB, pivotB, bodyB.angle); // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(worldPivotA,xAxis); x.G[3] = 1; x.G[4] = 0; x.G[5] = vec2.crossLength(worldPivotB,xAxis); y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(worldPivotA,yAxis); y.G[3] = 0; y.G[4] = 1; y.G[5] = vec2.crossLength(worldPivotB,yAxis); }; /** * Enable the rotational motor * @method enableMotor */ RevoluteConstraint.prototype.enableMotor = function(){ if(this.motorEnabled) return; this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ RevoluteConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled) return; var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; /** * Check if the motor is enabled. * @method motorIsEnabled * @return {Boolean} */ RevoluteConstraint.prototype.motorIsEnabled = function(){ return !!this.motorEnabled; }; /** * Set the speed of the rotational constraint motor * @method setMotorSpeed * @param {Number} speed */ RevoluteConstraint.prototype.setMotorSpeed = function(speed){ if(!this.motorEnabled){ return; } var i = this.equations.indexOf(this.motorEquation); this.equations[i].relativeVelocity = speed; }; /** * Get the speed of the rotational constraint motor * @method getMotorSpeed * @return {Number} The current speed, or false if the motor is not enabled. */ RevoluteConstraint.prototype.getMotorSpeed = function(){ if(!this.motorEnabled) return false; return this.motorEquation.relativeVelocity; }; },{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = AngleLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class AngleLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in body A. * @param {Number} [options.ratio] Gear ratio */ function AngleLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); this.angle = options.angle || 0; /** * The gear ratio. * @property {Number} ratio * @private * @see setRatio */ this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; this.setRatio(this.ratio); } AngleLockEquation.prototype = new Equation(); AngleLockEquation.prototype.constructor = AngleLockEquation; AngleLockEquation.prototype.computeGq = function(){ return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; }; /** * Set the gear ratio for this equation * @method setRatio * @param {Number} ratio */ AngleLockEquation.prototype.setRatio = function(ratio){ var G = this.G; G[2] = ratio; G[5] = -1; this.ratio = ratio; }; /** * Set the max force for the equation. * @method setMaxTorque * @param {Number} torque */ AngleLockEquation.prototype.setMaxTorque = function(torque){ this.maxForce = torque; this.minForce = -torque; }; },{"../math/vec2":30,"./Equation":22}],21:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = ContactEquation; /** * Non-penetration constraint equation. Tries to make the ri and rj vectors the same point. * * @class ContactEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function ContactEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); /** * Vector from body i center of mass to the contact point. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); this.penetrationVec = vec2.create(); /** * World-oriented vector from body A center of mass to the contact point. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * The normal vector, pointing out of body i * @property normalA * @type {Array} */ this.normalA = vec2.create(); /** * The restitution to use (0=no bounciness, 1=max bounciness). * @property restitution * @type {Number} */ this.restitution = 0; /** * This property is set to true if this is the first impact between the bodies (not persistant contact). * @property firstImpact * @type {Boolean} * @readOnly */ this.firstImpact = false; /** * The shape in body i that triggered this contact. * @property shapeA * @type {Shape} */ this.shapeA = null; /** * The shape in body j that triggered this contact. * @property shapeB * @type {Shape} */ this.shapeB = null; } ContactEquation.prototype = new Equation(); ContactEquation.prototype.constructor = ContactEquation; ContactEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, xi = bi.position, xj = bj.position; var penetrationVec = this.penetrationVec, n = this.normalA, G = this.G; // Caluclate cross products var rixn = vec2.crossLength(ri,n), rjxn = vec2.crossLength(rj,n); // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector vec2.add(penetrationVec,xj,rj); vec2.sub(penetrationVec,penetrationVec,xi); vec2.sub(penetrationVec,penetrationVec,ri); // Compute iteration var GW, Gq; if(this.firstImpact && this.restitution !== 0){ Gq = 0; GW = (1/b)*(1+this.restitution) * this.computeGW(); } else { Gq = vec2.dot(n,penetrationVec); GW = this.computeGW(); } var GiMf = this.computeGiMf(); var B = - Gq * a - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"./Equation":22}],22:[function(require,module,exports){ module.exports = Equation; var vec2 = require('../math/vec2'), Utils = require('../utils/Utils'), Body = require('../objects/Body'); /** * Base class for constraint equations. * @class Equation * @constructor * @param {Body} bodyA First body participating in the equation * @param {Body} bodyB Second body participating in the equation * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE */ function Equation(bodyA, bodyB, minForce, maxForce){ /** * Minimum force to apply when solving. * @property minForce * @type {Number} */ this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; /** * Max force to apply when solving. * @property maxForce * @type {Number} */ this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; /** * First body participating in the constraint * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. * @property stiffness * @type {Number} */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. * @property relaxation * @type {Number} */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). * @property G * @type {Array} */ this.G = new Utils.ARRAY_TYPE(6); for(var i=0; i<6; i++){ this.G[i]=0; } // Constraint frames for body i and j /* this.xi = vec2.create(); this.xj = vec2.create(); this.ai = 0; this.aj = 0; */ this.offset = 0; this.a = 0; this.b = 0; this.epsilon = 0; this.timeStep = 1/60; /** * Indicates if stiffness or relaxation was changed. * @property {Boolean} needsUpdate */ this.needsUpdate = true; /** * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. * @property multiplier * @type {Number} */ this.multiplier = 0; /** * Relative velocity. * @property {Number} relativeVelocity */ this.relativeVelocity = 0; /** * Whether this equation is enabled or not. If true, it will be added to the solver. * @property {Boolean} enabled */ this.enabled = true; } Equation.prototype.constructor = Equation; /** * The default stiffness when creating a new Equation. * @static * @property {Number} DEFAULT_STIFFNESS * @default 1e6 */ Equation.DEFAULT_STIFFNESS = 1e6; /** * The default relaxation when creating a new Equation. * @static * @property {Number} DEFAULT_RELAXATION * @default 4 */ Equation.DEFAULT_RELAXATION = 4; /** * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>. * @method update */ Equation.prototype.update = function(){ var k = this.stiffness, d = this.relaxation, h = this.timeStep; this.a = 4.0 / (h * (1 + 4 * d)); this.b = (4.0 * d) / (1 + 4 * d); this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); this.needsUpdate = false; }; function Gmult(G,vi,wi,vj,wj){ return G[0] * vi[0] + G[1] * vi[1] + G[2] * wi + G[3] * vj[0] + G[4] * vj[1] + G[5] * wj; } /** * Computes the RHS of the SPOOK equation * @method computeB * @return {Number} */ Equation.prototype.computeB = function(a,b,h){ var GW = this.computeGW(); var Gq = this.computeGq(); var GiMf = this.computeGiMf(); return - Gq * a - GW * b - GiMf*h; }; /** * Computes G*q, where q are the generalized body coordinates * @method computeGq * @return {Number} */ var qi = vec2.create(), qj = vec2.create(); Equation.prototype.computeGq = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, xi = bi.position, xj = bj.position, ai = bi.angle, aj = bj.angle; return Gmult(G, qi, ai, qj, aj) + this.offset; }; /** * Computes G*W, where W are the body velocities * @method computeGW * @return {Number} */ Equation.prototype.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return Gmult(G,vi,wi,vj,wj) + this.relativeVelocity; }; /** * Computes G*Wlambda, where W are the body velocities * @method computeGWlambda * @return {Number} */ Equation.prototype.computeGWlambda = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.vlambda, vj = bj.vlambda, wi = bi.wlambda, wj = bj.wlambda; return Gmult(G,vi,wi,vj,wj); }; /** * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. * @method computeGiMf * @return {Number} */ var iMfi = vec2.create(), iMfj = vec2.create(); Equation.prototype.computeGiMf = function(){ var bi = this.bodyA, bj = this.bodyB, fi = bi.force, ti = bi.angularForce, fj = bj.force, tj = bj.angularForce, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), G = this.G; vec2.scale(iMfi, fi,invMassi); vec2.scale(iMfj, fj,invMassj); return Gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); }; function getBodyInvMass(body){ if(body.sleepState === Body.SLEEPING){ return 0; } else { return body.invMass; } } function getBodyInvInertia(body){ if(body.sleepState === Body.SLEEPING){ return 0; } else { return body.invInertia; } } /** * Computes G*inv(M)*G' * @method computeGiMGt * @return {Number} */ Equation.prototype.computeGiMGt = function(){ var bi = this.bodyA, bj = this.bodyB, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), G = this.G; return G[0] * G[0] * invMassi + G[1] * G[1] * invMassi + G[2] * G[2] * invIi + G[3] * G[3] * invMassj + G[4] * G[4] * invMassj + G[5] * G[5] * invIj; }; var addToWlambda_temp = vec2.create(), addToWlambda_Gi = vec2.create(), addToWlambda_Gj = vec2.create(), addToWlambda_ri = vec2.create(), addToWlambda_rj = vec2.create(), addToWlambda_Mdiag = vec2.create(); /** * Add constraint velocity to the bodies. * @method addToWlambda * @param {Number} deltalambda */ Equation.prototype.addToWlambda = function(deltalambda){ var bi = this.bodyA, bj = this.bodyB, temp = addToWlambda_temp, Gi = addToWlambda_Gi, Gj = addToWlambda_Gj, ri = addToWlambda_ri, rj = addToWlambda_rj, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), Mdiag = addToWlambda_Mdiag, G = this.G; Gi[0] = G[0]; Gi[1] = G[1]; Gj[0] = G[3]; Gj[1] = G[4]; // Add to linear velocity // v_lambda += inv(M) * delta_lamba * G vec2.scale(temp, Gi, invMassi*deltalambda); vec2.add( bi.vlambda, bi.vlambda, temp); // This impulse is in the offset frame // Also add contribution to angular //bi.wlambda -= vec2.crossLength(temp,ri); bi.wlambda += invIi * G[2] * deltalambda; vec2.scale(temp, Gj, invMassj*deltalambda); vec2.add( bj.vlambda, bj.vlambda, temp); //bj.wlambda -= vec2.crossLength(temp,rj); bj.wlambda += invIj * G[5] * deltalambda; }; /** * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps * @method computeInvC * @param {Number} eps * @return {Number} */ Equation.prototype.computeInvC = function(eps){ return 1.0 / (this.computeGiMGt() + eps); }; },{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":47}],23:[function(require,module,exports){ var vec2 = require('../math/vec2') , Equation = require('./Equation') , Utils = require('../utils/Utils'); module.exports = FrictionEquation; /** * Constrains the slipping in a contact along a tangent * * @class FrictionEquation * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Number} slipForce * @extends Equation */ function FrictionEquation(bodyA, bodyB, slipForce){ Equation.call(this, bodyA, bodyB, -slipForce, slipForce); /** * Relative vector from center of body A to the contact point, world oriented. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); /** * Relative vector from center of body B to the contact point, world oriented. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * Tangent vector that the friction force will act along. World oriented. * @property t * @type {Array} */ this.t = vec2.create(); /** * A ContactEquation connected to this friction. The contact equation can be used to rescale the max force for the friction. * @property contactEquation * @type {ContactEquation} */ this.contactEquation = null; /** * The shape in body i that triggered this friction. * @property shapeA * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeA... */ this.shapeA = null; /** * The shape in body j that triggered this friction. * @property shapeB * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeB... */ this.shapeB = null; /** * The friction coefficient to use. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; } FrictionEquation.prototype = new Equation(); FrictionEquation.prototype.constructor = FrictionEquation; /** * Set the slipping condition for the constraint. The friction force cannot be * larger than this value. * @method setSlipForce * @param {Number} slipForce */ FrictionEquation.prototype.setSlipForce = function(slipForce){ this.maxForce = slipForce; this.minForce = -slipForce; }; /** * Get the max force for the constraint. * @method getSlipForce * @return {Number} */ FrictionEquation.prototype.getSlipForce = function(){ return this.maxForce; }; FrictionEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, t = this.t, G = this.G; // G = [-t -rixt t rjxt] // And remember, this is a pure velocity constraint, g is always zero! G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); var GW = this.computeGW(), GiMf = this.computeGiMf(); var B = /* - g * a */ - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"../utils/Utils":47,"./Equation":22}],24:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class RotationalLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in body i. */ function RotationalLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); this.angle = options.angle || 0; var G = this.G; G[2] = 1; G[5] = -1; } RotationalLockEquation.prototype = new Equation(); RotationalLockEquation.prototype.constructor = RotationalLockEquation; var worldVectorA = vec2.create(), worldVectorB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1); RotationalLockEquation.prototype.computeGq = function(){ vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); return vec2.dot(worldVectorA,worldVectorB); }; },{"../math/vec2":30,"./Equation":22}],25:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalVelocityEquation; /** * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). * * @class RotationalVelocityEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function RotationalVelocityEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); this.relativeVelocity = 1; this.ratio = 1; } RotationalVelocityEquation.prototype = new Equation(); RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; RotationalVelocityEquation.prototype.computeB = function(a,b,h){ var G = this.G; G[2] = -1; G[5] = this.ratio; var GiMf = this.computeGiMf(); var GW = this.computeGW(); var B = - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"./Equation":22}],26:[function(require,module,exports){ /** * Base class for objects that dispatches events. * @class EventEmitter * @constructor */ var EventEmitter = function () {} module.exports = EventEmitter; EventEmitter.prototype = { constructor: EventEmitter, /** * Add an event listener * @method on * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ on: function ( type, listener, context ) { listener.context = context || this; if ( this._listeners === undefined ) this._listeners = {}; var listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } return this; }, /** * Check if an event listener is added * @method has * @param {String} type * @param {Function} listener * @return {Boolean} */ has: function ( type, listener ) { if ( this._listeners === undefined ) return false; var listeners = this._listeners; if(listener){ if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { return true; } } else { if ( listeners[ type ] !== undefined ) { return true; } } return false; }, /** * Remove an event listener * @method off * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ off: function ( type, listener ) { if ( this._listeners === undefined ) return this; var listeners = this._listeners; var index = listeners[ type ].indexOf( listener ); if ( index !== - 1 ) { listeners[ type ].splice( index, 1 ); } return this; }, /** * Emit an event. * @method emit * @param {Object} event * @param {String} event.type * @return {EventEmitter} The self object, for chainability. */ emit: function ( event ) { if ( this._listeners === undefined ) return this; var listeners = this._listeners; var listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { var listener = listenerArray[ i ]; listener.call( listener.context, event ); } } return this; } }; },{}],27:[function(require,module,exports){ var Material = require('./Material'); var Equation = require('../equations/Equation'); module.exports = ContactMaterial; /** * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. * @class ContactMaterial * @constructor * @param {Material} materialA * @param {Material} materialB * @param {Object} [options] * @param {Number} [options.friction=0.3] Friction coefficient. * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". * @param {Number} [options.stiffness] ContactEquation stiffness. * @param {Number} [options.relaxation] ContactEquation relaxation. * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. * @param {Number} [options.surfaceVelocity=0] Surface velocity. * @author schteppe */ function ContactMaterial(materialA, materialB, options){ options = options || {}; if(!(materialA instanceof Material) || !(materialB instanceof Material)) throw new Error("First two arguments must be Material instances."); /** * The contact material identifier * @property id * @type {Number} */ this.id = ContactMaterial.idCounter++; /** * First material participating in the contact material * @property materialA * @type {Material} */ this.materialA = materialA; /** * Second material participating in the contact material * @property materialB * @type {Material} */ this.materialB = materialB; /** * Friction to use in the contact of these two materials * @property friction * @type {Number} */ this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; /** * Restitution to use in the contact of these two materials * @property restitution * @type {Number} */ this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0; /** * Stiffness of the resulting ContactEquation that this ContactMaterial generate * @property stiffness * @type {Number} */ this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting ContactEquation that this ContactMaterial generate * @property relaxation * @type {Number} */ this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; /** * Stiffness of the resulting FrictionEquation that this ContactMaterial generate * @property frictionStiffness * @type {Number} */ this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting FrictionEquation that this ContactMaterial generate * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; /** * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. * @property {Number} surfaceVelocity */ this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; } ContactMaterial.idCounter = 0; },{"../equations/Equation":22,"./Material":28}],28:[function(require,module,exports){ module.exports = Material; /** * Defines a physics material. * @class Material * @constructor * @param string name * @author schteppe */ function Material(){ /** * The material identifier * @property id * @type {Number} */ this.id = Material.idCounter++; }; Material.idCounter = 0; },{}],29:[function(require,module,exports){ /* PolyK library url: http://polyk.ivank.net Released under MIT licence. Copyright (c) 2012 Ivan Kuckir Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var PolyK = {}; /* Is Polygon self-intersecting? O(n^2) */ /* PolyK.IsSimple = function(p) { var n = p.length>>1; if(n<4) return true; var a1 = new PolyK._P(), a2 = new PolyK._P(); var b1 = new PolyK._P(), b2 = new PolyK._P(); var c = new PolyK._P(); for(var i=0; i<n; i++) { a1.x = p[2*i ]; a1.y = p[2*i+1]; if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; } else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; } for(var j=0; j<n; j++) { if(Math.abs(i-j) < 2) continue; if(j==n-1 && i==0) continue; if(i==n-1 && j==0) continue; b1.x = p[2*j ]; b1.y = p[2*j+1]; if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; } else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; } if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false; } } return true; } PolyK.IsConvex = function(p) { if(p.length<6) return true; var l = p.length - 4; for(var i=0; i<l; i+=2) if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false; if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false; if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false; return true; } */ PolyK.GetArea = function(p) { if(p.length <6) return 0; var l = p.length - 2; var sum = 0; for(var i=0; i<l; i+=2) sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]); sum += (p[0]-p[l]) * (p[l+1]+p[1]); return - sum * 0.5; } /* PolyK.GetAABB = function(p) { var minx = Infinity; var miny = Infinity; var maxx = -minx; var maxy = -miny; for(var i=0; i<p.length; i+=2) { minx = Math.min(minx, p[i ]); maxx = Math.max(maxx, p[i ]); miny = Math.min(miny, p[i+1]); maxy = Math.max(maxy, p[i+1]); } return {x:minx, y:miny, width:maxx-minx, height:maxy-miny}; } */ PolyK.Triangulate = function(p) { var n = p.length>>1; if(n<3) return []; var tgs = []; var avl = []; for(var i=0; i<n; i++) avl.push(i); var i = 0; var al = n; while(al > 3) { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; var ax = p[2*i0], ay = p[2*i0+1]; var bx = p[2*i1], by = p[2*i1+1]; var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; if(PolyK._convex(ax, ay, bx, by, cx, cy)) { earFound = true; for(var j=0; j<al; j++) { var vi = avl[j]; if(vi==i0 || vi==i1 || vi==i2) continue; if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;} } } if(earFound) { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i= 0; } else if(i++ > 3*al) break; // no convex angles :( } tgs.push(avl[0], avl[1], avl[2]); return tgs; } /* PolyK.ContainsPoint = function(p, px, py) { var n = p.length>>1; var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; var depth = 0; for(var i=0; i<n; i++) { ax = bx; ay = by; bx = p[2*i ] - px; by = p[2*i+1] - py; if(ay< 0 && by< 0) continue; // both "up" or both "donw" if(ay>=0 && by>=0) continue; // both "up" or both "donw" if(ax< 0 && bx< 0) continue; var lx = ax + (bx-ax)*(-ay)/(by-ay); if(lx>0) depth++; } return (depth & 1) == 1; } PolyK.Slice = function(p, ax, ay, bx, by) { if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; var a = new PolyK._P(ax, ay); var b = new PolyK._P(bx, by); var iscs = []; // intersections var ps = []; // points for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1])); for(var i=0; i<ps.length; i++) { var isc = new PolyK._P(0,0); isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc); if(isc) { isc.flag = true; iscs.push(isc); ps.splice(i+1,0,isc); i++; } } if(iscs.length == 0) return [p.slice(0)]; var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); } iscs.sort(comp); var pgs = []; var dir = 0; while(iscs.length > 0) { var n = ps.length; var i0 = iscs[0]; var i1 = iscs[1]; var ind0 = ps.indexOf(i0); var ind1 = ps.indexOf(i1); var solved = false; if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; else { i0 = iscs[1]; i1 = iscs[0]; ind0 = ps.indexOf(i0); ind1 = ps.indexOf(i1); if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; } if(solved) { dir--; var pgn = PolyK._getPoints(ps, ind0, ind1); pgs.push(pgn); ps = PolyK._getPoints(ps, ind1, ind0); i0.flag = i1.flag = false; iscs.splice(0,2); if(iscs.length == 0) pgs.push(ps); } else { dir++; iscs.reverse(); } if(dir>1) break; } var result = []; for(var i=0; i<pgs.length; i++) { var pg = pgs[i]; var npg = []; for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y); result.push(npg); } return result; } PolyK.Raycast = function(p, x, y, dx, dy, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], a2 = tp[1], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; a2.x = x+dx; a2.y = y+dy; if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc); return (isc.dist != Infinity) ? isc : null; } PolyK.ClosestEdge = function(p, x, y, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; PolyK._pointLineDist(a1, b1, b2, i>>1, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; PolyK._pointLineDist(a1, b1, b2, l>>1, isc); var idst = 1/isc.dist; isc.norm.x = (x-isc.point.x)*idst; isc.norm.y = (y-isc.point.y)*idst; return isc; } PolyK._pointLineDist = function(p, a, b, edge, isc) { var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; var A = x - x1; var B = y - y1; var C = x2 - x1; var D = y2 - y1; var dot = A * C + B * D; var len_sq = C * C + D * D; var param = dot / len_sq; var xx, yy; if (param < 0 || (x1 == x2 && y1 == y2)) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } var dx = x - xx; var dy = y - yy; var dst = Math.sqrt(dx * dx + dy * dy); if(dst<isc.dist) { isc.dist = dst; isc.edge = edge; isc.point.x = xx; isc.point.y = yy; } } PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc) { var nrl = PolyK._P.dist(a1, c); if(nrl<isc.dist) { var ibl = 1/PolyK._P.dist(b1, b2); var nx = -(b2.y-b1.y)*ibl; var ny = (b2.x-b1.x)*ibl; var ddot = 2*(dx*nx+dy*ny); isc.dist = nrl; isc.norm.x = nx; isc.norm.y = ny; isc.refl.x = -ddot*nx+dx; isc.refl.y = -ddot*ny+dy; isc.edge = edge; } } PolyK._getPoints = function(ps, ind0, ind1) { var n = ps.length; var nps = []; if(ind1<ind0) ind1 += n; for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]); return nps; } PolyK._firstWithFlag = function(ps, ind) { var n = ps.length; while(true) { ind = (ind+1)%n; if(ps[ind].flag) return ind; } } */ PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy) { var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; var v1y = by-ay; var v2x = px-ax; var v2y = py-ay; var dot00 = v0x*v0x+v0y*v0y; var dot01 = v0x*v1x+v0y*v1y; var dot02 = v0x*v2x+v0y*v2y; var dot11 = v1x*v1x+v1y*v1y; var dot12 = v1x*v2x+v1y*v2y; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1); } /* PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; var iDen = 1/Den; I.x = ( A*dbx - dax*B ) * iDen; I.y = ( A*dby - day*B ) * iDen; if(!PolyK._InRect(I, b1, b2)) return null; if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null; if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null; return I; } PolyK._GetLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; I.x = ( A*dbx - dax*B ) / Den; I.y = ( A*dby - day*B ) / Den; if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I; return null; } PolyK._InRect = function(a, b, c) { if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) return true; return false; } */ PolyK._convex = function(ax, ay, bx, by, cx, cy) { return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; } /* PolyK._P = function(x,y) { this.x = x; this.y = y; this.flag = false; } PolyK._P.prototype.toString = function() { return "Point ["+this.x+", "+this.y+"]"; } PolyK._P.dist = function(a,b) { var dx = b.x-a.x; var dy = b.y-a.y; return Math.sqrt(dx*dx + dy*dy); } PolyK._tp = []; for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); */ module.exports = PolyK; },{}],30:[function(require,module,exports){ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net for full doc. * @class vec2 */ var vec2 = require('../../build/vec2').vec2; /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Float32Array} a * @param {Float32Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Float32Array} out * @param {Float32Array} vec * @param {Number} zcomp * @return {Number} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Float32Array} out * @param {Number} zcomp * @param {Float32Array} vec * @return {Number} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Number} angle */ vec2.rotate = function(out,a,angle){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Number} angle */ vec2.rotate90cw = function(out, a) { out[0] = a[1]; out[1] = -a[0]; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ vec2.copy(out, worldPoint); vec2.sub(out, out, framePosition); vec2.rotate(out, out, -frameAngle); }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ vec2.copy(out, localPoint); vec2.rotate(out, out, frameAngle); vec2.add(out, out, framePosition); }; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Float32Array} b * @param {Float32Array} c * @return {Float32Array} The out object */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; // Export everything module.exports = vec2; },{"../../build/vec2":1}],31:[function(require,module,exports){ var vec2 = require('../math/vec2') , decomp = require('poly-decomp') , Convex = require('../shapes/Convex') , AABB = require('../collision/AABB') , EventEmitter = require('../events/EventEmitter') module.exports = Body; /** * A rigid body. Has got a center of mass, position, velocity and a number of * shapes that are used for collisions. * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] A number >= 0. If zero, the .motionState will be set to Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] */ function Body(options){ options = options || {}; EventEmitter.call(this); /** * The body identifyer * @property id * @type {Number} */ this.id = ++Body._idCounter; /** * The world that this body is added to. This property is set to NULL if the body is not added to any world. * @property world * @type {World} */ this.world = null; /** * The shapes of the body. The local transform of the shape in .shapes[i] is * defined by .shapeOffsets[i] and .shapeAngles[i]. * * @property shapes * @type {Array} */ this.shapes = []; /** * The local shape offsets, relative to the body center of mass. This is an * array of Array. * @property shapeOffsets * @type {Array} */ this.shapeOffsets = []; /** * The body-local shape angle transforms. This is an array of numbers (angles). * @property shapeAngles * @type {Array} */ this.shapeAngles = []; /** * The mass of the body. * @property mass * @type {number} */ this.mass = options.mass || 0; /** * The inverse mass of the body. * @property invMass * @type {number} */ this.invMass = 0; /** * The inertia of the body around the Z axis. * @property inertia * @type {number} */ this.inertia = 0; /** * The inverse inertia of the body. * @property invInertia * @type {number} */ this.invInertia = 0; /** * Set to true if you want to fix the rotation of the body. * @property fixedRotation * @type {Boolean} */ this.fixedRotation = !!options.fixedRotation || false; /** * The position of the body * @property position * @type {Array} */ this.position = vec2.fromValues(0,0); if(options.position){ vec2.copy(this.position, options.position); } /** * The interpolated position of the body. * @property interpolatedPosition * @type {Array} */ this.interpolatedPosition = vec2.fromValues(0,0); /** * The interpolated angle of the body. * @property interpolatedAngle * @type {Number} */ this.interpolatedAngle = 0; /** * The previous position of the body. * @property previousPosition * @type {Array} */ this.previousPosition = vec2.fromValues(0,0); /** * The previous angle of the body. * @property previousAngle * @type {Number} */ this.previousAngle = 0; /** * The velocity of the body * @property velocity * @type {Array} */ this.velocity = vec2.fromValues(0,0); if(options.velocity){ vec2.copy(this.velocity, options.velocity); } /** * Constraint velocity that was added to the body during the last step. * @property vlambda * @type {Array} */ this.vlambda = vec2.fromValues(0,0); /** * Angular constraint velocity that was added to the body during last step. * @property wlambda * @type {Array} */ this.wlambda = 0; /** * The angle of the body, in radians. * @property angle * @type {number} * @example * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. * // If you need a value between 0 and 2*pi, use the following function to normalize it. * function normalizeAngle(angle){ * angle = angle % (2*Math.PI); * if(angle < 0){ * angle += (2*Math.PI); * } * return angle; * } */ this.angle = options.angle || 0; /** * The angular velocity of the body, in radians per second. * @property angularVelocity * @type {number} */ this.angularVelocity = options.angularVelocity || 0; /** * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. * @property force * @type {Array} * * @example * // This produces a forcefield of 1 Newton in the positive x direction. * for(var i=0; i<numSteps; i++){ * body.force[0] = 1; * world.step(1/60); * } * * @example * // This will apply a rotational force on the body * for(var i=0; i<numSteps; i++){ * body.angularForce = -3; * world.step(1/60); * } */ this.force = vec2.create(); if(options.force) vec2.copy(this.force, options.force); /** * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}. * @property angularForce * @type {number} */ this.angularForce = options.angularForce || 0; /** * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1. * @property damping * @type {Number} * @default 0.1 */ this.damping = typeof(options.damping)=="number" ? options.damping : 0.1; /** * The angular force acting on the body. Should be a value between 0 and 1. * @property angularDamping * @type {Number} * @default 0.1 */ this.angularDamping = typeof(options.angularDamping)=="number" ? options.angularDamping : 0.1; /** * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}. * * * Static bodies do not move, and they do not respond to forces or collision. * * Dynamic bodies body can move and respond to collisions and forces. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * * @property motionState * @type {number} * * @example * // This body will move and interact with other bodies * var dynamicBody = new Body({ * mass : 1 // If mass is nonzero, the body becomes dynamic automatically * }); * dynamicBody.motionState == Body.DYNAMIC // true * * @example * // This body will not move at all * var staticBody = new Body({ * mass : 0 // Will make the body static * }); * staticBody.motionState == Body.STATIC // true * * @example * // This body will only move if you change its velocity * var kinematicBody = new Body(); * kinematicBody.motionState = Body.KINEMATIC; */ this.motionState = this.mass === 0 ? Body.STATIC : Body.DYNAMIC; /** * Bounding circle radius. * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Bounding box of this body. * @property aabb * @type {AABB} */ this.aabb = new AABB(); /** * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}. * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * // Force update the AABB * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ this.aabbNeedsUpdate = true; /** * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen. * @property allowSleep * @type {Boolean} * @default true */ this.allowSleep = true; this.wantsToSleep = false; /** * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}. * * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY). * * @property sleepState * @type {Number} * @default Body.AWAKE */ this.sleepState = Body.AWAKE; /** * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ this.sleepSpeedLimit = 0.2; /** * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. * @property sleepTimeLimit * @type {Number} * @default 1 */ this.sleepTimeLimit = 1; /** * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1. * @property {Number} gravityScale * @default 1 */ this.gravityScale = 1; /** * The last time when the body went to SLEEPY state. * @property {Number} timeLastSleepy * @private */ this.timeLastSleepy = 0; this.concavePath = null; this.lastDampingScale = 1; this.lastAngularDampingScale = 1; this.lastDampingTimeStep = -1; this._wakeUpAfterNarrowphase = false; this.updateMassProperties(); } Body.prototype = new EventEmitter(); Body._idCounter = 0; /** * Set the total density of the body * @method setDensity */ Body.prototype.setDensity = function(density) { var totalArea = this.getArea(); this.mass = totalArea * density; this.updateMassProperties(); }; /** * Get the total area of all shapes in the body * @method getArea * @return {Number} */ Body.prototype.getArea = function() { var totalArea = 0; for(var i=0; i<this.shapes.length; i++){ totalArea += this.shapes[i].area; } return totalArea; }; var shapeAABB = new AABB(), tmp = vec2.create(); /** * Updates the AABB of the Body * @method updateAABB */ Body.prototype.updateAABB = function() { var shapes = this.shapes, shapeOffsets = this.shapeOffsets, shapeAngles = this.shapeAngles, N = shapes.length; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = tmp, angle = shapeAngles[i] + this.angle; // Get shape world offset vec2.rotate(offset,shapeOffsets[i],this.angle); vec2.add(offset,offset,this.position); // Get shape AABB shape.computeAABB(shapeAABB,offset,angle); if(i===0) this.aabb.copy(shapeAABB); else this.aabb.extend(shapeAABB); } this.aabbNeedsUpdate = false; }; /** * Update the bounding radius of the body. Should be done if any of the shapes * are changed. * @method updateBoundingRadius */ Body.prototype.updateBoundingRadius = function(){ var shapes = this.shapes, shapeOffsets = this.shapeOffsets, N = shapes.length, radius = 0; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = vec2.length(shapeOffsets[i]), r = shape.boundingRadius; if(offset + r > radius){ radius = offset + r; } } this.boundingRadius = radius; }; /** * Add a shape to the body. You can pass a local transform when adding a shape, * so that the shape gets an offset and angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method addShape * @param {Shape} shape * @param {Array} [offset] Local body offset of the shape. * @param {Number} [angle] Local body angle. * * @example * var body = new Body(), * shape = new Circle(); * * // Add the shape to the body, positioned in the center * body.addShape(shape); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. * body.addShape(shape,[1,0]); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. * body.addShape(shape,[0,1],Math.PI/2); */ Body.prototype.addShape = function(shape,offset,angle){ angle = angle || 0.0; // Copy the offset vector if(offset){ offset = vec2.fromValues(offset[0],offset[1]); } else { offset = vec2.fromValues(0,0); } this.shapes .push(shape); this.shapeOffsets.push(offset); this.shapeAngles .push(angle); this.updateMassProperties(); this.updateBoundingRadius(); this.aabbNeedsUpdate = true; }; /** * Remove a shape * @method removeShape * @param {Shape} shape * @return {Boolean} True if the shape was found and removed, else false. */ Body.prototype.removeShape = function(shape){ var idx = this.shapes.indexOf(shape); if(idx !== -1){ this.shapes.splice(idx,1); this.shapeOffsets.splice(idx,1); this.shapeAngles.splice(idx,1); this.aabbNeedsUpdate = true; return true; } else { return false; } }; /** * Updates .inertia, .invMass, .invInertia for this Body. Should be called when * changing the structure or mass of the Body. * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ Body.prototype.updateMassProperties = function(){ if(this.motionState === Body.STATIC || this.motionState === Body.KINEMATIC){ this.mass = Number.MAX_VALUE; this.invMass = 0; this.inertia = Number.MAX_VALUE; this.invInertia = 0; } else { var shapes = this.shapes, N = shapes.length, m = this.mass / N, I = 0; if(!this.fixedRotation){ for(var i=0; i<N; i++){ var shape = shapes[i], r2 = vec2.squaredLength(this.shapeOffsets[i]), Icm = shape.computeMomentOfInertia(m); I += Icm + m*r2; } this.inertia = I; this.invInertia = I>0 ? 1/I : 0; } else { this.inertia = Number.MAX_VALUE; this.invInertia = 0; } // Inverse mass properties are easy this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0; } }; var Body_applyForce_r = vec2.create(); /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * @method applyForce * @param {Array} force The force to add. * @param {Array} worldPoint A world point to apply the force on. */ Body.prototype.applyForce = function(force,worldPoint){ // Compute point position relative to the body center var r = Body_applyForce_r; vec2.sub(r,worldPoint,this.position); // Add linear force vec2.add(this.force,this.force,force); // Compute produced rotational force var rotForce = vec2.crossLength(r,force); // Add rotational force this.angularForce += rotForce; }; /** * Transform a world point to local body frame. * @method toLocalFrame * @param {Array} out The vector to store the result in * @param {Array} worldPoint The input world vector */ Body.prototype.toLocalFrame = function(out, worldPoint){ vec2.toLocalFrame(out, worldPoint, this.position, this.angle); }; /** * Transform a local point to world frame. * @method toWorldFrame * @param {Array} out The vector to store the result in * @param {Array} localPoint The input local vector */ Body.prototype.toWorldFrame = function(out, localPoint){ vec2.toGlobalFrame(out, localPoint, this.position, this.angle); }; /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. * @method fromPolygon * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. * @param {Object} [options] * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @return {Boolean} True on success, else false. */ Body.prototype.fromPolygon = function(path,options){ options = options || {}; // Remove all shapes for(var i=this.shapes.length; i>=0; --i) this.removeShape(this.shapes[i]); var p = new decomp.Polygon(); p.vertices = path; // Make it counter-clockwise p.makeCCW(); if(typeof(options.removeCollinearPoints)=="number"){ p.removeCollinearPoints(options.removeCollinearPoints); } // Check if any line segment intersects the path itself if(typeof(options.skipSimpleCheck) == "undefined"){ if(!p.isSimple()) return false; } // Save this path for later this.concavePath = p.vertices.slice(0); for(var i=0; i<this.concavePath.length; i++){ var v = [0,0]; vec2.copy(v,this.concavePath[i]); this.concavePath[i] = v; } // Slow or fast decomp? var convexes; if(options.optimalDecomp) convexes = p.decomp(); else convexes = p.quickDecomp(); var cm = vec2.create(); // Add convexes for(var i=0; i!==convexes.length; i++){ // Create convex var c = new Convex(convexes[i].vertices); // Move all vertices so its center of mass is in the local center of the convex for(var j=0; j!==c.vertices.length; j++){ var v = c.vertices[j]; vec2.sub(v,v,c.centerOfMass); } vec2.scale(cm,c.centerOfMass,1); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); // Add the shape this.addShape(c,cm); } this.adjustCenterOfMass(); this.aabbNeedsUpdate = true; return true; }; var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0), adjustCenterOfMass_tmp2 = vec2.fromValues(0,0), adjustCenterOfMass_tmp3 = vec2.fromValues(0,0), adjustCenterOfMass_tmp4 = vec2.fromValues(0,0); /** * Moves the shape offsets so their center of mass becomes the body center of mass. * @method adjustCenterOfMass */ Body.prototype.adjustCenterOfMass = function(){ var offset_times_area = adjustCenterOfMass_tmp2, sum = adjustCenterOfMass_tmp3, cm = adjustCenterOfMass_tmp4, totalArea = 0; vec2.set(sum,0,0); for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; vec2.scale(offset_times_area,offset,s.area); vec2.add(sum,sum,offset_times_area); totalArea += s.area; } vec2.scale(cm,sum,1/totalArea); // Now move all shapes for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; // Offset may be undefined. Fix that. if(!offset){ offset = this.shapeOffsets[i] = vec2.create(); } vec2.sub(offset,offset,cm); } // Move the body position too vec2.add(this.position,this.position,cm); // And concave path for(var i=0; this.concavePath && i<this.concavePath.length; i++){ vec2.sub(this.concavePath[i], this.concavePath[i], cm); } this.updateMassProperties(); this.updateBoundingRadius(); }; /** * Sets the force on the body to zero. * @method setZeroForce */ Body.prototype.setZeroForce = function(){ vec2.set(this.force,0.0,0.0); this.angularForce = 0.0; }; Body.prototype.resetConstraintVelocity = function(){ var b = this, vlambda = b.vlambda; vec2.set(vlambda,0,0); b.wlambda = 0; }; Body.prototype.addConstraintVelocity = function(){ var b = this, v = b.velocity; vec2.add( v, v, b.vlambda); b.angularVelocity += b.wlambda; }; /** * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details. * @method applyDamping * @param {number} dt Current time step */ Body.prototype.applyDamping = function(dt){ if(this.motionState === Body.DYNAMIC){ // Only for dynamic bodies // Since Math.pow generates garbage we check if we can reuse the scaling coefficient from last step if(dt !== this.lastDampingTimeStep){ this.lastDampingScale = Math.pow(1.0 - this.damping,dt); this.lastAngularDampingScale = Math.pow(1.0 - this.angularDamping,dt); this.lastDampingTimeStep = dt; } var v = this.velocity; vec2.scale(v,v,this.lastDampingScale); this.angularVelocity *= this.lastAngularDampingScale; } }; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ Body.prototype.wakeUp = function(){ var s = this.sleepState; this.sleepState = Body.AWAKE; this.idleTime = 0; if(s !== Body.AWAKE){ this.emit(Body.wakeUpEvent); } }; /** * Force body sleep * @method sleep */ Body.prototype.sleep = function(){ this.sleepState = Body.SLEEPING; this.angularVelocity = 0; this.angularForce = 0; vec2.set(this.velocity,0,0); vec2.set(this.force,0,0); this.emit(Body.sleepEvent); }; //var velo2 = vec2.create(); /** * @method sleepTick * @param float time The world time in seconds * @brief Called every timestep to update internal sleep timer and change sleep state if needed. */ Body.prototype.sleepTick = function(time, dontSleep, dt){ if(!this.allowSleep || this.motionState === Body.SLEEPING){ return; } this.wantsToSleep = false; var sleepState = this.sleepState, speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); // Add to idle time if(speedSquared >= speedLimitSquared){ this.idleTime = 0; this.sleepState = Body.AWAKE; } else { this.idleTime += dt; this.sleepState = Body.SLEEPY; } if(this.idleTime > this.sleepTimeLimit){ if(!dontSleep){ this.sleep(); } else { this.wantsToSleep = true; } } /* if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ this.sleepState = Body.SLEEPY; // Sleepy this.timeLastSleepy = time; this.emit(Body.sleepyEvent); } else if(sleepState===Body.SLEEPY && speedSquared >= speedLimitSquared){ this.wakeUp(); // Wake up } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ this.wantsToSleep = true; if(!dontSleep){ this.sleep(); } } */ }; Body.prototype.getVelocityFromPosition = function(store, timeStep){ store = store || vec2.create(); vec2.sub(store, this.position, this.previousPosition); vec2.scale(store, store, 1/timeStep); return store; }; Body.prototype.getAngularVelocityFromPosition = function(timeStep){ return (this.angle - this.previousAngle) / timeStep; }; /** * @event sleepy */ Body.sleepyEvent = { type: "sleepy" }; /** * @event sleep */ Body.sleepEvent = { type: "sleep" }; /** * @event wakeup */ Body.wakeUpEvent = { type: "wakeup" }; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Body.KINEMATIC = 4; /** * @property AWAKE * @type {Number} * @static */ Body.AWAKE = 0; /** * @property SLEEPY * @type {Number} * @static */ Body.SLEEPY = 1; /** * @property SLEEPING * @type {Number} * @static */ Body.SLEEPING = 2; },{"../collision/AABB":8,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":36,"poly-decomp":6}],32:[function(require,module,exports){ var vec2 = require('../math/vec2'); var Utils = require('../utils/Utils'); module.exports = Spring; /** * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the solver. * * @class Spring * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {number} [options.restLength=1] A number > 0. Default: 1 * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. * @param {number} [options.damping=1] A number >= 0. Default: 1 * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. * @param {Array} [options.localAnchorB] * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. * @param {Array} [options.worldAnchorB] */ function Spring(bodyA,bodyB,options){ options = Utils.defaults(options,{ restLength: 1, stiffness: 100, damping: 1, localAnchorA: [0,0], localAnchorB: [0,0], }); /** * Rest length of the spring. * @property restLength * @type {number} */ this.restLength = options.restLength; /** * Stiffness of the spring. * @property stiffness * @type {number} */ this.stiffness = options.stiffness; /** * Damping of the spring. * @property damping * @type {number} */ this.damping = options.damping; /** * First connected body. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second connected body. * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * Anchor for bodyA in local bodyA coordinates. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.create(); vec2.copy(this.localAnchorA, options.localAnchorA); /** * Anchor for bodyB in local bodyB coordinates. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.create(); vec2.copy(this.localAnchorB, options.localAnchorB); if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } } /** * Set the anchor point on body A, using world coordinates. * @method setWorldAnchorA * @param {Array} worldAnchorA */ Spring.prototype.setWorldAnchorA = function(worldAnchorA){ this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); }; /** * Set the anchor point on body B, using world coordinates. * @method setWorldAnchorB * @param {Array} worldAnchorB */ Spring.prototype.setWorldAnchorB = function(worldAnchorB){ this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); }; /** * Get the anchor point on body A, in world coordinates. * @method getWorldAnchorA * @param {Array} result The vector to store the result in. */ Spring.prototype.getWorldAnchorA = function(result){ this.bodyA.toWorldFrame(result, this.localAnchorA); }; /** * Get the anchor point on body B, in world coordinates. * @method getWorldAnchorB * @param {Array} result The vector to store the result in. */ Spring.prototype.getWorldAnchorB = function(result){ this.bodyB.toWorldFrame(result, this.localAnchorB); }; var applyForce_r = vec2.create(), applyForce_r_unit = vec2.create(), applyForce_u = vec2.create(), applyForce_f = vec2.create(), applyForce_worldAnchorA = vec2.create(), applyForce_worldAnchorB = vec2.create(), applyForce_ri = vec2.create(), applyForce_rj = vec2.create(), applyForce_tmp = vec2.create(); /** * Apply the spring force to the connected bodies. * @method applyForce */ Spring.prototype.applyForce = function(){ var k = this.stiffness, d = this.damping, l = this.restLength, bodyA = this.bodyA, bodyB = this.bodyB, r = applyForce_r, r_unit = applyForce_r_unit, u = applyForce_u, f = applyForce_f, tmp = applyForce_tmp; var worldAnchorA = applyForce_worldAnchorA, worldAnchorB = applyForce_worldAnchorB, ri = applyForce_ri, rj = applyForce_rj; // Get world anchors this.getWorldAnchorA(worldAnchorA); this.getWorldAnchorB(worldAnchorB); // Get offset points vec2.sub(ri, worldAnchorA, bodyA.position); vec2.sub(rj, worldAnchorB, bodyB.position); // Compute distance vector between world anchor points vec2.sub(r, worldAnchorB, worldAnchorA); var rlen = vec2.len(r); vec2.normalize(r_unit,r); //console.log(rlen) //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) // Compute relative velocity of the anchor points, u vec2.sub(u, bodyB.velocity, bodyA.velocity); vec2.crossZV(tmp, bodyB.angularVelocity, rj); vec2.add(u, u, tmp); vec2.crossZV(tmp, bodyA.angularVelocity, ri); vec2.sub(u, u, tmp); // F = - k * ( x - L ) - D * ( u ) vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); // Add forces to bodies vec2.sub( bodyA.force, bodyA.force, f); vec2.add( bodyB.force, bodyB.force, f); // Angular force var ri_x_f = vec2.crossLength(ri, f); var rj_x_f = vec2.crossLength(rj, f); bodyA.angularForce -= ri_x_f; bodyB.angularForce += rj_x_f; }; },{"../math/vec2":30,"../utils/Utils":47}],33:[function(require,module,exports){ // Export p2 classes module.exports = { AABB : require('./collision/AABB'), AngleLockEquation : require('./equations/AngleLockEquation'), Body : require('./objects/Body'), Broadphase : require('./collision/Broadphase'), Capsule : require('./shapes/Capsule'), Circle : require('./shapes/Circle'), Constraint : require('./constraints/Constraint'), ContactEquation : require('./equations/ContactEquation'), ContactMaterial : require('./material/ContactMaterial'), Convex : require('./shapes/Convex'), DistanceConstraint : require('./constraints/DistanceConstraint'), Equation : require('./equations/Equation'), EventEmitter : require('./events/EventEmitter'), FrictionEquation : require('./equations/FrictionEquation'), GearConstraint : require('./constraints/GearConstraint'), GridBroadphase : require('./collision/GridBroadphase'), GSSolver : require('./solver/GSSolver'), Heightfield : require('./shapes/Heightfield'), Line : require('./shapes/Line'), LockConstraint : require('./constraints/LockConstraint'), Material : require('./material/Material'), Narrowphase : require('./collision/Narrowphase'), NaiveBroadphase : require('./collision/NaiveBroadphase'), Particle : require('./shapes/Particle'), Plane : require('./shapes/Plane'), RevoluteConstraint : require('./constraints/RevoluteConstraint'), PrismaticConstraint : require('./constraints/PrismaticConstraint'), Rectangle : require('./shapes/Rectangle'), RotationalVelocityEquation : require('./equations/RotationalVelocityEquation'), SAPBroadphase : require('./collision/SAPBroadphase'), Shape : require('./shapes/Shape'), Solver : require('./solver/Solver'), Spring : require('./objects/Spring'), Utils : require('./utils/Utils'), World : require('./world/World'), vec2 : require('./math/vec2'), version : require('../package.json').version, }; },{"../package.json":7,"./collision/AABB":8,"./collision/Broadphase":9,"./collision/GridBroadphase":10,"./collision/NaiveBroadphase":11,"./collision/Narrowphase":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/Spring":32,"./shapes/Capsule":34,"./shapes/Circle":35,"./shapes/Convex":36,"./shapes/Heightfield":37,"./shapes/Line":38,"./shapes/Particle":39,"./shapes/Plane":40,"./shapes/Rectangle":41,"./shapes/Shape":42,"./solver/GSSolver":43,"./solver/Solver":44,"./utils/Utils":47,"./world/World":51}],34:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Capsule; /** * Capsule shape class. * @class Capsule * @constructor * @extends Shape * @param {Number} [length] The distance between the end points * @param {Number} [radius] Radius of the capsule */ function Capsule(length, radius){ /** * The distance between the end points. * @property {Number} length */ this.length = length || 1; /** * The radius of the capsule. * @property {Number} radius */ this.radius = radius || 1; Shape.call(this,Shape.CAPSULE); } Capsule.prototype = new Shape(); /** * Compute the mass moment of inertia of the Capsule. * @method conputeMomentOfInertia * @param {Number} mass * @return {Number} * @todo */ Capsule.prototype.computeMomentOfInertia = function(mass){ // Approximate with rectangle var r = this.radius, w = this.length + r, // 2*r is too much, 0 is too little h = r*2; return mass * (h*h + w*w) / 12; }; /** * @method updateBoundingRadius */ Capsule.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius + this.length/2; }; /** * @method updateArea */ Capsule.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; }; var r = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Capsule.prototype.computeAABB = function(out, position, angle){ var radius = this.radius; // Compute center position of one of the the circles, world oriented, but with local offset vec2.set(r,this.length,0); vec2.rotate(r,r,angle); // Get bounds vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius), Math.max(r[1]+radius, -r[1]+radius)); vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius), Math.min(r[1]-radius, -r[1]-radius)); // Add offset vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; },{"../math/vec2":30,"./Shape":42}],35:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Circle; /** * Circle shape class. * @class Circle * @extends Shape * @constructor * @param {number} [radius=1] The radius of this circle */ function Circle(radius){ /** * The radius of the circle. * @property radius * @type {number} */ this.radius = radius || 1; Shape.call(this,Shape.CIRCLE); }; Circle.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Circle.prototype.computeMomentOfInertia = function(mass){ var r = this.radius; return mass * r * r / 2; }; /** * @method updateBoundingRadius * @return {Number} */ Circle.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius; }; /** * @method updateArea * @return {Number} */ Circle.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Circle.prototype.computeAABB = function(out, position, angle){ var r = this.radius; vec2.set(out.upperBound, r, r); vec2.set(out.lowerBound, -r, -r); if(position){ vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); } }; },{"../math/vec2":30,"./Shape":42}],36:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , polyk = require('../math/polyk') , decomp = require('poly-decomp') module.exports = Convex; /** * Convex shape class. * @class Convex * @constructor * @extends Shape * @param {Array} vertices An array of Float32Array vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. */ function Convex(vertices){ /** * Vertices defined in the local frame. * @property vertices * @type {Array} */ this.vertices = []; // Copy the verts for(var i=0; i<vertices.length; i++){ var v = vec2.create(); vec2.copy(v,vertices[i]); this.vertices.push(v); } /** * The center of mass of the Convex * @property centerOfMass * @type {Float32Array} */ this.centerOfMass = vec2.fromValues(0,0); /** * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. * @property triangles * @type {Array} */ this.triangles = []; if(this.vertices.length){ this.updateTriangles(); this.updateCenterOfMass(); } /** * The bounding radius of the convex * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; Shape.call(this,Shape.CONVEX); this.updateBoundingRadius(); this.updateArea(); if(this.area < 0) throw new Error("Convex vertices must be given in conter-clockwise winding."); }; Convex.prototype = new Shape(); /** * Update the .triangles property * @method updateTriangles */ Convex.prototype.updateTriangles = function(){ this.triangles.length = 0; // Rewrite on polyk notation, array of numbers var polykVerts = []; for(var i=0; i<this.vertices.length; i++){ var v = this.vertices[i]; polykVerts.push(v[0],v[1]); } // Triangulate var triangles = polyk.Triangulate(polykVerts); // Loop over all triangles, add their inertia contributions to I for(var i=0; i<triangles.length; i+=3){ var id1 = triangles[i], id2 = triangles[i+1], id3 = triangles[i+2]; // Add to triangles this.triangles.push([id1,id2,id3]); } }; var updateCenterOfMass_centroid = vec2.create(), updateCenterOfMass_centroid_times_mass = vec2.create(), updateCenterOfMass_a = vec2.create(), updateCenterOfMass_b = vec2.create(), updateCenterOfMass_c = vec2.create(), updateCenterOfMass_ac = vec2.create(), updateCenterOfMass_ca = vec2.create(), updateCenterOfMass_cb = vec2.create(), updateCenterOfMass_n = vec2.create(); /** * Update the .centerOfMass property. * @method updateCenterOfMass */ Convex.prototype.updateCenterOfMass = function(){ var triangles = this.triangles, verts = this.vertices, cm = this.centerOfMass, centroid = updateCenterOfMass_centroid, n = updateCenterOfMass_n, a = updateCenterOfMass_a, b = updateCenterOfMass_b, c = updateCenterOfMass_c, ac = updateCenterOfMass_ac, ca = updateCenterOfMass_ca, cb = updateCenterOfMass_cb, centroid_times_mass = updateCenterOfMass_centroid_times_mass; vec2.set(cm,0,0); var totalArea = 0; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; vec2.centroid(centroid,a,b,c); // Get mass for the triangle (density=1 in this case) // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors var m = Convex.triangleArea(a,b,c) totalArea += m; // Add to center of mass vec2.scale(centroid_times_mass, centroid, m); vec2.add(cm, cm, centroid_times_mass); } vec2.scale(cm,cm,1/totalArea); }; /** * Compute the mass moment of inertia of the Convex. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/ */ Convex.prototype.computeMomentOfInertia = function(mass){ var denom = 0.0, numer = 0.0, N = this.vertices.length; for(var j = N-1, i = 0; i < N; j = i, i ++){ var p0 = this.vertices[j]; var p1 = this.vertices[i]; var a = Math.abs(vec2.crossLength(p0,p1)); var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0); denom += a * b; numer += a; } return (mass / 6.0) * (denom / numer); }; /** * Updates the .boundingRadius property * @method updateBoundingRadius */ Convex.prototype.updateBoundingRadius = function(){ var verts = this.vertices, r2 = 0; for(var i=0; i!==verts.length; i++){ var l2 = vec2.squaredLength(verts[i]); if(l2 > r2) r2 = l2; } this.boundingRadius = Math.sqrt(r2); }; /** * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. * @static * @method triangleArea * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Convex.triangleArea = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; } /** * Update the .area * @method updateArea */ Convex.prototype.updateArea = function(){ this.updateTriangles(); this.area = 0; var triangles = this.triangles, verts = this.vertices; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; // Get mass for the triangle (density=1 in this case) var m = Convex.triangleArea(a,b,c); this.area += m; } }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Convex.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices,position,angle); }; },{"../math/polyk":29,"../math/vec2":30,"./Shape":42,"poly-decomp":6}],37:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = Heightfield; /** * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". * @class Heightfield * @extends Shape * @constructor * @param {Array} data * @param {Number} maxValue * @param {Number} elementWidth * @todo Should take maxValue as an option and also be able to compute it itself if not given. * @todo Should be possible to use along all axes, not just y */ function Heightfield(data, options){ options = Utils.defaults(options, { maxValue : null, minValue : null, elementWidth : 0.1 }); if(options.minValue === null || options.maxValue === null){ options.maxValue = data[0]; options.minValue = data[0]; for(var i=0; i !== data.length; i++){ var v = data[i]; if(v > options.maxValue){ options.maxValue = v; } if(v < options.minValue){ options.minValue = v; } } } /** * An array of numbers, or height values, that are spread out along the x axis. * @property {array} data */ this.data = data; /** * Max value of the data * @property {number} maxValue */ this.maxValue = options.maxValue; /** * Max value of the data * @property {number} minValue */ this.minValue = options.minValue; /** * The width of each element * @property {number} elementWidth */ this.elementWidth = options.elementWidth; Shape.call(this,Shape.HEIGHTFIELD); } Heightfield.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Heightfield.prototype.computeMomentOfInertia = function(mass){ return Number.MAX_VALUE; }; Heightfield.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; Heightfield.prototype.updateArea = function(){ var data = this.data, area = 0; for(var i=0; i<data.length-1; i++){ area += (data[i]+data[i+1]) / 2 * this.elementWidth; } this.area = area; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Heightfield.prototype.computeAABB = function(out, position, angle){ // Use the max data rectangle out.upperBound[0] = this.elementWidth * this.data.length + position[0]; out.upperBound[1] = this.maxValue + position[1]; out.lowerBound[0] = position[0]; out.lowerBound[1] = -Number.MAX_VALUE; // Infinity }; },{"../math/vec2":30,"../utils/Utils":47,"./Shape":42}],38:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Line; /** * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * @class Line * @param {Number} length The total length of the line * @extends Shape * @constructor */ function Line(length){ /** * Length of this line * @property length * @type {Number} */ this.length = length || 1; Shape.call(this,Shape.LINE); } Line.prototype = new Shape(); Line.prototype.computeMomentOfInertia = function(mass){ return mass * Math.pow(this.length,2) / 12; }; Line.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.length/2; }; var points = [vec2.create(),vec2.create()]; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Line.prototype.computeAABB = function(out, position, angle){ var l = this.length; vec2.set(points[0], -l/2, 0); vec2.set(points[1], l/2, 0); out.setFromPoints(points,position,angle); }; },{"../math/vec2":30,"./Shape":42}],39:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Particle; /** * Particle shape class. * @class Particle * @constructor * @extends Shape */ function Particle(){ Shape.call(this,Shape.PARTICLE); }; Particle.prototype = new Shape(); Particle.prototype.computeMomentOfInertia = function(mass){ return 0; // Can't rotate a particle }; Particle.prototype.updateBoundingRadius = function(){ this.boundingRadius = 0; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Particle.prototype.computeAABB = function(out, position, angle){ var l = this.length; vec2.copy(out.lowerBound, position); vec2.copy(out.upperBound, position); }; },{"../math/vec2":30,"./Shape":42}],40:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils') module.exports = Plane; /** * Plane shape class. The plane is facing in the Y direction. * @class Plane * @extends Shape * @constructor */ function Plane(){ Shape.call(this,Shape.PLANE); }; Plane.prototype = new Shape(); /** * Compute moment of inertia * @method computeMomentOfInertia */ Plane.prototype.computeMomentOfInertia = function(mass){ return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here }; /** * Update the bounding radius * @method updateBoundingRadius */ Plane.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Plane.prototype.computeAABB = function(out, position, angle){ var a = 0, set = vec2.set; if(typeof(angle) == "number") a = angle % (2*Math.PI); if(a == 0){ // y goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, 0); } else if(a == Math.PI / 2){ // x goes from 0 to inf set(out.lowerBound, 0, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a == Math.PI){ // y goes from 0 to inf set(out.lowerBound, -Number.MAX_VALUE, 0); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a == 3*Math.PI/2){ // x goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, 0, Number.MAX_VALUE); } else { // Set max bounds set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; Plane.prototype.updateArea = function(){ this.area = Number.MAX_VALUE; }; },{"../math/vec2":30,"../utils/Utils":47,"./Shape":42}],41:[function(require,module,exports){ var vec2 = require('../math/vec2') , Shape = require('./Shape') , Convex = require('./Convex'); module.exports = Rectangle; /** * Rectangle shape class. * @class Rectangle * @constructor * @param {Number} width Width * @param {Number} height Height * @extends Convex */ function Rectangle(width, height){ width = width || 1; height = height || 1; var verts = [ vec2.fromValues(-width/2, -height/2), vec2.fromValues( width/2, -height/2), vec2.fromValues( width/2, height/2), vec2.fromValues(-width/2, height/2)]; /** * Total width of the rectangle * @property width * @type {Number} */ this.width = width; /** * Total height of the rectangle * @property height * @type {Number} */ this.height = height; Convex.call(this,verts); this.type = Shape.RECTANGLE; } Rectangle.prototype = new Convex([]); /** * Compute moment of inertia * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Rectangle.prototype.computeMomentOfInertia = function(mass){ var w = this.width, h = this.height; return mass * (h*h + w*w) / 12; }; /** * Update the bounding radius * @method updateBoundingRadius */ Rectangle.prototype.updateBoundingRadius = function(){ var w = this.width, h = this.height; this.boundingRadius = Math.sqrt(w*w + h*h) / 2; }; var corner1 = vec2.create(), corner2 = vec2.create(), corner3 = vec2.create(), corner4 = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Rectangle.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices,position,angle); }; Rectangle.prototype.updateArea = function(){ this.area = this.width * this.height; }; },{"../math/vec2":30,"./Convex":36,"./Shape":42}],42:[function(require,module,exports){ module.exports = Shape; /** * Base class for shapes. * @class Shape * @constructor * @param {Number} type */ function Shape(type){ /** * The type of the shape. One of: * * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} * * {{#crossLink "Shape/RECTANGLE:property"}}Shape.RECTANGLE{{/crossLink}} * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} * * @property {number} type */ this.type = type; /** * Shape object identifier. * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = 1; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = 1; if(type) this.updateBoundingRadius(); /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = false; this.updateArea(); }; Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} RECTANGLE */ Shape.RECTANGLE = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; /** * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ Shape.prototype.computeMomentOfInertia = function(mass){ throw new Error("Shape.computeMomentOfInertia is not implemented in this Shape..."); }; /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ Shape.prototype.updateBoundingRadius = function(){ throw new Error("Shape.updateBoundingRadius is not implemented in this Shape..."); }; /** * Update the .area property of the shape. * @method updateArea */ Shape.prototype.updateArea = function(){ // To be implemented in all subclasses }; /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Shape.prototype.computeAABB = function(out, position, angle){ // To be implemented in each subclass }; },{}],43:[function(require,module,exports){ var vec2 = require('../math/vec2') , Solver = require('./Solver') , Utils = require('../utils/Utils') , FrictionEquation = require('../equations/FrictionEquation'); module.exports = GSSolver; /** * Iterative Gauss-Seidel constraint equation solver. * * @class GSSolver * @constructor * @extends Solver * @param {Object} [options] * @param {Number} [options.iterations=10] * @param {Number} [options.tolerance=0] */ function GSSolver(options){ Solver.call(this,options,Solver.GS); options = options || {}; /** * The number of iterations to do when solving. More gives better results, but is more expensive. * @property iterations * @type {Number} */ this.iterations = options.iterations || 10; /** * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. * @property tolerance * @type {Number} */ this.tolerance = options.tolerance || 1e-10; this.arrayStep = 30; this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); /** * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. * @property useZeroRHS * @type {Boolean} */ this.useZeroRHS = false; /** * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example. * The solver will use less iterations if the solution is below the .tolerance. * @property frictionIterations * @type {Number} */ this.frictionIterations = 0; /** * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. * @property {Number} usedIterations */ this.usedIterations = 0; } GSSolver.prototype = new Solver(); function setArrayZero(array){ var l = array.length; while(l--){ array[l] = +0.0; } } /** * Solve the system of equations * @method solve * @param {Number} h Time step * @param {World} world World to solve */ GSSolver.prototype.solve = function(h, world){ this.sortEquations(); var iter = 0, maxIter = this.iterations, maxFrictionIter = this.frictionIterations, equations = this.equations, Neq = equations.length, tolSquared = Math.pow(this.tolerance*Neq, 2), bodies = world.bodies, Nbodies = world.bodies.length, add = vec2.add, set = vec2.set, useZeroRHS = this.useZeroRHS, lambda = this.lambda; this.usedIterations = 0; // Things that does not change during iteration can be computed once if(lambda.length < Neq){ lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); } setArrayZero(lambda); var invCs = this.invCs, Bs = this.Bs, lambda = this.lambda; for(var i=0; i!==equations.length; i++){ var c = equations[i]; if(c.timeStep !== h || c.needsUpdate){ c.timeStep = h; c.update(); } Bs[i] = c.computeB(c.a,c.b,h); invCs[i] = c.computeInvC(c.epsilon); } var q, B, c, deltalambdaTot,i,j; if(Neq !== 0){ // Reset vlambda for(i=0; i!==Nbodies; i++){ bodies[i].resetConstraintVelocity(); } if(maxFrictionIter){ // Iterate over contact equations to get normal forces for(iter=0; iter!==maxFrictionIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; if(c instanceof FrictionEquation){ //continue; } var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } GSSolver.updateMultipliers(equations, lambda, 1/h); // Set computed friction force for(j=0; j!==Neq; j++){ var eq = equations[j]; if(eq instanceof FrictionEquation){ var f = eq.contactEquation.multiplier * eq.frictionCoefficient; eq.maxForce = f; eq.minForce = -f; } } } // Iterate over all equations for(iter=0; iter!==maxIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } // Add result to velocity for(i=0; i!==Nbodies; i++){ bodies[i].addConstraintVelocity(); } GSSolver.updateMultipliers(equations, lambda, 1/h); } }; // Sets the .multiplier property of each equation GSSolver.updateMultipliers = function(equations, lambda, invDt){ // Set the .multiplier property of each equation var l = equations.length; while(l--){ equations[l].multiplier = lambda[l] * invDt; } }; GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ // Compute iteration var B = Bs[j], invC = invCs[j], lambdaj = lambda[j], GWlambda = eq.computeGWlambda(); var maxForce = eq.maxForce, minForce = eq.minForce; if(useZeroRHS){ B = 0; } var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); // Clamp if we are not within the min/max interval var lambdaj_plus_deltalambda = lambdaj + deltalambda; if(lambdaj_plus_deltalambda < minForce*dt){ deltalambda = minForce*dt - lambdaj; } else if(lambdaj_plus_deltalambda > maxForce*dt){ deltalambda = maxForce*dt - lambdaj; } lambda[j] += deltalambda; eq.addToWlambda(deltalambda); return deltalambda; }; },{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":47,"./Solver":44}],44:[function(require,module,exports){ var Utils = require('../utils/Utils') , EventEmitter = require('../events/EventEmitter') module.exports = Solver; /** * Base class for constraint solvers. * @class Solver * @constructor * @extends EventEmitter */ function Solver(options,type){ options = options || {}; EventEmitter.call(this); this.type = type; /** * Current equations in the solver. * * @property equations * @type {Array} */ this.equations = []; /** * Function that is used to sort all equations before each solve. * @property equationSortFunction * @type {function|boolean} */ this.equationSortFunction = options.equationSortFunction || false; } Solver.prototype = new EventEmitter(); /** * Method to be implemented in each subclass * @method solve * @param {Number} dt * @param {World} world */ Solver.prototype.solve = function(dt,world){ throw new Error("Solver.solve should be implemented by subclasses!"); }; var mockWorld = {bodies:[]}; /** * Solves all constraints in an island. * @method solveIsland * @param {Number} dt * @param {Island} island */ Solver.prototype.solveIsland = function(dt,island){ this.removeAllEquations(); if(island.equations.length){ // Add equations to solver this.addEquations(island.equations); mockWorld.bodies.length = 0; island.getBodies(mockWorld.bodies); // Solve if(mockWorld.bodies.length){ this.solve(dt,mockWorld); } } }; /** * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. * @method sortEquations */ Solver.prototype.sortEquations = function(){ if(this.equationSortFunction){ this.equations.sort(this.equationSortFunction); } }; /** * Add an equation to be solved. * * @method addEquation * @param {Equation} eq */ Solver.prototype.addEquation = function(eq){ if(eq.enabled){ this.equations.push(eq); } }; /** * Add equations. Same as .addEquation, but this time the argument is an array of Equations * * @method addEquations * @param {Array} eqs */ Solver.prototype.addEquations = function(eqs){ //Utils.appendArray(this.equations,eqs); for(var i=0, N=eqs.length; i!==N; i++){ var eq = eqs[i]; if(eq.enabled){ this.equations.push(eq); } } }; /** * Remove an equation. * * @method removeEquation * @param {Equation} eq */ Solver.prototype.removeEquation = function(eq){ var i = this.equations.indexOf(eq); if(i !== -1){ this.equations.splice(i,1); } }; /** * Remove all currently added equations. * * @method removeAllEquations */ Solver.prototype.removeAllEquations = function(){ this.equations.length=0; }; Solver.GS = 1; Solver.ISLAND = 2; },{"../events/EventEmitter":26,"../utils/Utils":47}],45:[function(require,module,exports){ var TupleDictionary = require('./TupleDictionary'); var Utils = require('./Utils'); module.exports = OverlapKeeper; /** * Keeps track of overlaps in the current state and the last step state. * @class OverlapKeeper * @constructor */ function OverlapKeeper() { this.overlappingLastState = new TupleDictionary(); this.overlappingCurrentState = new TupleDictionary(); this.recordPool = []; this.tmpDict = new TupleDictionary(); this.tmpArray1 = []; } /** * @method tick */ OverlapKeeper.prototype.tick = function() { var last = this.overlappingLastState; var current = this.overlappingCurrentState; // Save old objects into pool var l = current.keys.length; while(l--){ var key = current.keys[l]; this.recordPool.push(current.getByKey(key)); } // Clear last object last.reset(); // Transfer from new object to old last.copy(current); // Clear current object current.reset(); }; /** * @method setOverlapping */ OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { var last = this.overlappingLastState; var current = this.overlappingCurrentState; // Store current contact state if(!current.get(shapeA.id, shapeB.id)){ var data; if(this.recordPool.length){ data = this.recordPool.pop(); } else { data = new OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB); } current.set(shapeA.id, shapeB.id, data); } }; OverlapKeeper.prototype.getNewOverlaps = function(result){ return this.getDiff(this.overlappingLastState, this.overlappingCurrentState, result); }; OverlapKeeper.prototype.getEndOverlaps = function(result){ return this.getDiff(this.overlappingCurrentState, this.overlappingLastState, result); }; OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){ var result = result || []; var last = dictA; var current = dictB; result.length = 0; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if(!data){ throw new Error('Key '+key+' had no data!'); } var lastData = last.data[key]; if(!lastData){ // Not overlapping in last state, but in current. result.push(data); } } return result; }; OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ var idA = shapeA.id|0, idB = shapeB.id|0; return !!!this.overlappingLastState.get(idA, idB) && !!this.overlappingCurrentState.get(idA, idB); }; OverlapKeeper.prototype.getNewBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getNewOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getEndBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getEndOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){ result = result || []; var accumulator = this.tmpDict; var l = overlaps.length; while(l--){ var data = overlaps[l]; // Since we use body id's for the accumulator, these will be a subset of the original one accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); } l = accumulator.keys.length; while(l--){ var data = accumulator.keys[l]; result.push(data.bodyA, data.bodyB); } accumulator.reset(); return result; }; /** * Overlap data container for the OverlapKeeper * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB [description] */ function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ /** * @property {Shape} shapeA */ this.shapeA = shapeA; /** * @property {Shape} shapeB */ this.shapeB = shapeB; /** * @property {Body} bodyA */ this.bodyA = bodyA; /** * @property {Body} bodyB */ this.bodyB = bodyB; } OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); }; },{"./TupleDictionary":46,"./Utils":47}],46:[function(require,module,exports){ var Utils = require('./Utils'); module.exports = TupleDictionary; /** * @class TupleDictionary * @constructor */ function TupleDictionary() { /** * The data storage * @property data * @type {Array} */ this.data = []; /** * Keys that are currently used. * @type {Array} */ this.keys = []; } /** * Generate a key given two integers * @param {number} i * @param {number} j * @return {string} */ TupleDictionary.prototype.getKey = function(id1, id2) { id1 = id1|0; id2 = id2|0; if ( (id1|0) === (id2|0) ){ return -1; } // valid for values < 2^16 return ((id1|0) > (id2|0) ? (id1 << 16) | (id2 & 0xFFFF) : (id2 << 16) | (id1 & 0xFFFF))|0 ; }; /** * @method getByKey * @param {Number} key * @return {Object} */ TupleDictionary.prototype.getByKey = function(key) { key = key|0; return this.data[key]; }; /** * @method get * @param {Number} i * @param {Number} j * @return {Number} */ TupleDictionary.prototype.get = function(i, j) { i = i|0; j = j|0; var key = this.getKey(i, j)|0; return this.data[key]; }; /** * @method set * @param {Number} i * @param {Number} j * @param {Number} value */ TupleDictionary.prototype.set = function(i, j, value) { if(!value){ throw new Error("No data!"); } i = i|0; j = j|0; var key = this.getKey(i, j)|0; // Check if key already exists if(!this.get(i, j)){ this.keys.push(key); } this.data[key] = value; return key; }; /** * @method reset */ TupleDictionary.prototype.reset = function() { var data = this.data, keys = this.keys; var l = keys.length|0; while(l--){ var key = keys[l]|0; data[key] = undefined; } keys.length = 0; }; /** * @method copy */ TupleDictionary.prototype.copy = function(dict) { this.reset(); Utils.appendArray(this.keys, dict.keys); var l = dict.keys.length|0; while(l--){ var key = dict.keys[l]|0; this.data[key] = dict.data[key]; } }; },{"./Utils":47}],47:[function(require,module,exports){ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){}; /** * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * The array type to use for internal numeric computations. * @type {Array} * @static * @property ARRAY_TYPE */ Utils.ARRAY_TYPE = window.Float32Array || Array; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.defaults = function(options, defaults){ options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; },{}],48:[function(require,module,exports){ var Body = require('../objects/Body'); module.exports = Island; /** * An island of bodies connected with equations. * @class Island * @constructor */ function Island(){ /** * Current equations in this island. * @property equations * @type {Array} */ this.equations = []; /** * Current bodies in this island. * @property bodies * @type {Array} */ this.bodies = []; } /** * Clean this island from bodies and equations. * @method reset */ Island.prototype.reset = function(){ this.equations.length = this.bodies.length = 0; }; var bodyIds = []; /** * Get all unique bodies in this island. * @method getBodies * @return {Array} An array of Body */ Island.prototype.getBodies = function(result){ var bodies = result || [], eqs = this.equations; bodyIds.length = 0; for(var i=0; i!==eqs.length; i++){ var eq = eqs[i]; if(bodyIds.indexOf(eq.bodyA.id)===-1){ bodies.push(eq.bodyA); bodyIds.push(eq.bodyA.id); } if(bodyIds.indexOf(eq.bodyB.id)===-1){ bodies.push(eq.bodyB); bodyIds.push(eq.bodyB.id); } } return bodies; }; /** * Check if the entire island wants to sleep. * @method wantsToSleep * @return {Boolean} */ Island.prototype.wantsToSleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; if(b.motionState === Body.DYNAMIC && !b.wantsToSleep){ return false; } } return true; }; /** * Make all bodies in the island sleep. * @method sleep */ Island.prototype.sleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; b.sleep(); } return true; }; },{"../objects/Body":31}],49:[function(require,module,exports){ var vec2 = require('../math/vec2') , Island = require('./Island') , IslandNode = require('./IslandNode') , Body = require('../objects/Body') module.exports = IslandManager; /** * Splits the system of bodies and equations into independent islands * * @class IslandManager * @constructor * @param {Object} [options] * @extends Solver */ function IslandManager(options){ // Pooling of node objects saves some GC load this._nodePool = []; this._islandPool = []; /** * The equations to split. Manually fill this array before running .split(). * @property {Array} equations */ this.equations = []; /** * The resulting {{#crossLink "Island"}}{{/crossLink}}s. * @property {Array} islands */ this.islands = []; /** * The resulting graph nodes. * @property {Array} nodes */ this.nodes = []; /** * The node queue, used when traversing the graph of nodes. * @private * @property {Array} queue */ this.queue = []; } /** * Get an unvisited node from a list of nodes. * @static * @method getUnvisitedNode * @param {Array} nodes * @return {IslandNode|boolean} The node if found, else false. */ IslandManager.getUnvisitedNode = function(nodes){ var Nnodes = nodes.length; for(var i=0; i!==Nnodes; i++){ var node = nodes[i]; if(!node.visited && node.body.motionState === Body.DYNAMIC){ return node; } } return false; }; /** * Visit a node. * @method visit * @param {IslandNode} node * @param {Array} bds * @param {Array} eqs */ IslandManager.prototype.visit = function (node,bds,eqs){ bds.push(node.body); var Neqs = node.equations.length; for(var i=0; i!==Neqs; i++){ var eq = node.equations[i]; if(eqs.indexOf(eq) === -1){ // Already added? eqs.push(eq); } } }; /** * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays. * @method bfs * @param {IslandNode} root The node to start from * @param {Array} bds An array to append resulting Bodies to. * @param {Array} eqs An array to append resulting Equations to. */ IslandManager.prototype.bfs = function(root,bds,eqs){ // Reset the visit queue var queue = this.queue; queue.length = 0; // Add root node to queue queue.push(root); root.visited = true; this.visit(root,bds,eqs); // Process all queued nodes while(queue.length) { // Get next node in the queue var node = queue.pop(); // Visit unvisited neighboring nodes var child; while((child = IslandManager.getUnvisitedNode(node.neighbors))) { child.visited = true; this.visit(child,bds,eqs); // Only visit the children of this node if it's dynamic if(child.body.motionState === Body.DYNAMIC){ queue.push(child); } } } }; /** * Split the world into independent islands. The result is stored in .islands. * @method split * @param {World} world * @return {Array} The generated islands */ IslandManager.prototype.split = function(world){ var bodies = world.bodies, nodes = this.nodes, equations = this.equations; // Move old nodes to the node pool while(nodes.length){ this._nodePool.push(nodes.pop()); } // Create needed nodes, reuse if possible for(var i=0; i!==bodies.length; i++){ if(this._nodePool.length){ var node = this._nodePool.pop(); node.reset(); node.body = bodies[i]; nodes.push(node); } else { nodes.push(new IslandNode(bodies[i])); } } // Add connectivity data. Each equation connects 2 bodies. for(var k=0; k!==equations.length; k++){ var eq=equations[k], i=bodies.indexOf(eq.bodyA), j=bodies.indexOf(eq.bodyB), ni=nodes[i], nj=nodes[j]; ni.neighbors.push(nj); nj.neighbors.push(ni); ni.equations.push(eq); nj.equations.push(eq); } // Move old islands to the island pool var islands = this.islands; while(islands.length){ var island = islands.pop(); island.reset(); this._islandPool.push(island); } // Get islands var child; while((child = IslandManager.getUnvisitedNode(nodes))){ // Create new island var island = this._islandPool.length ? this._islandPool.pop() : new Island(); // Get all equations and bodies in this island this.bfs(child, island.bodies, island.equations); islands.push(island); } return islands; }; },{"../math/vec2":30,"../objects/Body":31,"./Island":48,"./IslandNode":50}],50:[function(require,module,exports){ module.exports = IslandNode; /** * Holds a body and keeps track of some additional properties needed for graph traversal. * @class IslandNode * @constructor * @param {Body} body */ function IslandNode(body){ /** * The body that is contained in this node. * @property {Body} */ this.body = body; /** * Neighboring IslandNodes * @property {Array} neighbors */ this.neighbors = []; /** * Equations connected to this node. * @property {Array} equations */ this.equations = []; /** * If this node was visiting during the graph traversal. * @property visited * @type {Boolean} */ this.visited = false; } /** * Clean this node from bodies and equations. * @method reset */ IslandNode.prototype.reset = function(){ this.equations.length = 0; this.neighbors.length = 0; this.visited = false; this.body = null; }; },{}],51:[function(require,module,exports){ var GSSolver = require('../solver/GSSolver') , Solver = require('../solver/Solver') , NaiveBroadphase = require('../collision/NaiveBroadphase') , vec2 = require('../math/vec2') , Circle = require('../shapes/Circle') , Rectangle = require('../shapes/Rectangle') , Convex = require('../shapes/Convex') , Line = require('../shapes/Line') , Plane = require('../shapes/Plane') , Capsule = require('../shapes/Capsule') , Particle = require('../shapes/Particle') , EventEmitter = require('../events/EventEmitter') , Body = require('../objects/Body') , Shape = require('../shapes/Shape') , Spring = require('../objects/Spring') , Material = require('../material/Material') , ContactMaterial = require('../material/ContactMaterial') , DistanceConstraint = require('../constraints/DistanceConstraint') , Constraint = require('../constraints/Constraint') , LockConstraint = require('../constraints/LockConstraint') , RevoluteConstraint = require('../constraints/RevoluteConstraint') , PrismaticConstraint = require('../constraints/PrismaticConstraint') , GearConstraint = require('../constraints/GearConstraint') , pkg = require('../../package.json') , Broadphase = require('../collision/Broadphase') , SAPBroadphase = require('../collision/SAPBroadphase') , Narrowphase = require('../collision/Narrowphase') , Utils = require('../utils/Utils') , OverlapKeeper = require('../utils/OverlapKeeper') , IslandManager = require('./IslandManager') module.exports = World; if(typeof performance === 'undefined'){ performance = {}; } if(!performance.now){ var nowOffset = Date.now(); if (performance.timing && performance.timing.navigationStart){ nowOffset = performance.timing.navigationStart; } performance.now = function(){ return Date.now() - nowOffset; }; } /** * The dynamics world, where all bodies and constraints lives. * * @class World * @constructor * @param {Object} [options] * @param {Solver} [options.solver] Defaults to GSSolver. * @param {Array} [options.gravity] Defaults to [0,-9.78] * @param {Broadphase} [options.broadphase] Defaults to NaiveBroadphase * @param {Boolean} [options.islandSplit=false] * @param {Boolean} [options.doProfiling=false] * @extends EventEmitter */ function World(options){ EventEmitter.apply(this); options = options || {}; /** * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}. * * @property springs * @type {Array} */ this.springs = []; /** * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}. * @property {Array} bodies */ this.bodies = []; /** * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}. * @private * @property {Array} disabledBodyCollisionPairs */ this.disabledBodyCollisionPairs = []; /** * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}. * @property {Solver} solver */ this.solver = options.solver || new GSSolver(); /** * The narrowphase to use to generate contacts. * * @property narrowphase * @type {Narrowphase} */ this.narrowphase = new Narrowphase(this); /** * The island manager of this world. * @property {IslandManager} islandManager */ this.islandManager = new IslandManager(); /** * Gravity in the world. This is applied on all bodies in the beginning of each step(). * * @property gravity * @type {Array} */ this.gravity = vec2.fromValues(0, -9.78); if(options.gravity){ vec2.copy(this.gravity, options.gravity); } /** * Gravity to use when approximating the friction max force (mu*mass*gravity). * @property {Number} frictionGravity */ this.frictionGravity = vec2.length(this.gravity) || 10; /** * Set to true if you want .frictionGravity to be automatically set to the length of .gravity. * @property {Boolean} useWorldGravityAsFrictionGravity */ this.useWorldGravityAsFrictionGravity = true; /** * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games. * @property {Boolean} useFrictionGravityOnZeroGravity */ this.useFrictionGravityOnZeroGravity = true; /** * Whether to do timing measurements during the step() or not. * * @property doPofiling * @type {Boolean} */ this.doProfiling = options.doProfiling || false; /** * How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true. * * @property lastStepTime * @type {Number} */ this.lastStepTime = 0.0; /** * The broadphase algorithm to use. * * @property broadphase * @type {Broadphase} */ this.broadphase = options.broadphase || new NaiveBroadphase(); this.broadphase.setWorld(this); /** * User-added constraints. * * @property constraints * @type {Array} */ this.constraints = []; /** * Dummy default material in the world, used in .defaultContactMaterial * @property {Material} defaultMaterial */ this.defaultMaterial = new Material(); /** * The default contact material to use, if no contact material was set for the colliding materials. * @property {ContactMaterial} defaultContactMaterial */ this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial); /** * For keeping track of what time step size we used last step * @property lastTimeStep * @type {Number} */ this.lastTimeStep = 1/60; /** * Enable to automatically apply spring forces each step. * @property applySpringForces * @type {Boolean} */ this.applySpringForces = true; /** * Enable to automatically apply body damping each step. * @property applyDamping * @type {Boolean} */ this.applyDamping = true; /** * Enable to automatically apply gravity each step. * @property applyGravity * @type {Boolean} */ this.applyGravity = true; /** * Enable/disable constraint solving in each step. * @property solveConstraints * @type {Boolean} */ this.solveConstraints = true; /** * The ContactMaterials added to the World. * @property contactMaterials * @type {Array} */ this.contactMaterials = []; /** * World time. * @property time * @type {Number} */ this.time = 0.0; /** * Is true during the step(). * @property {Boolean} stepping */ this.stepping = false; /** * Bodies that are scheduled to be removed at the end of the step. * @property {Array} bodiesToBeRemoved * @private */ this.bodiesToBeRemoved = []; this.fixedStepTime = 0.0; /** * Whether to enable island splitting. Island splitting can be an advantage for many things, including solver performance. See {{#crossLink "IslandManager"}}{{/crossLink}}. * @property {Boolean} islandSplit */ this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : false; /** * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. * @property emitImpactEvent * @type {Boolean} */ this.emitImpactEvent = true; // Id counters this._constraintIdCounter = 0; this._bodyIdCounter = 0; /** * Fired after the step(). * @event postStep */ this.postStepEvent = { type : "postStep", }; /** * Fired when a body is added to the world. * @event addBody * @param {Body} body */ this.addBodyEvent = { type : "addBody", body : null }; /** * Fired when a body is removed from the world. * @event removeBody * @param {Body} body */ this.removeBodyEvent = { type : "removeBody", body : null }; /** * Fired when a spring is added to the world. * @event addSpring * @param {Spring} spring */ this.addSpringEvent = { type : "addSpring", spring : null, }; /** * Fired when a first contact is created between two bodies. This event is fired after the step has been done. * @event impact * @param {Body} bodyA * @param {Body} bodyB */ this.impactEvent = { type: "impact", bodyA : null, bodyB : null, shapeA : null, shapeB : null, contactEquation : null, }; /** * Fired after the Broadphase has collected collision pairs in the world. * Inside the event handler, you can modify the pairs array as you like, to * prevent collisions between objects that you don't want. * @event postBroadphase * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase. */ this.postBroadphaseEvent = { type:"postBroadphase", pairs:null, }; /** * Enable / disable automatic body sleeping. Sleeping can improve performance. You might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}. * @property allowSleep * @type {Boolean} */ this.enableBodySleeping = false; /** * Enable or disable island sleeping. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work. * @property {Boolean} enableIslandSleeping */ this.enableIslandSleeping = false; /** * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step. * @event beginContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.beginContactEvent = { type:"beginContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, contactEquations : [], }; /** * Fired when two shapes stop overlapping, after the narrowphase (during step). * @event endContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.endContactEvent = { type:"endContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, }; /** * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver. * @event preSolve * @param {Array} contactEquations An array of contacts to be solved. * @param {Array} frictionEquations An array of friction equations to be solved. */ this.preSolveEvent = { type:"preSolve", contactEquations:null, frictionEquations:null, }; // For keeping track of overlapping shapes this.overlappingShapesLastState = { keys:[] }; this.overlappingShapesCurrentState = { keys:[] }; this.overlapKeeper = new OverlapKeeper(); } World.prototype = new Object(EventEmitter.prototype); /** * Add a constraint to the simulation. * * @method addConstraint * @param {Constraint} c */ World.prototype.addConstraint = function(c){ this.constraints.push(c); }; /** * Add a ContactMaterial to the simulation. * @method addContactMaterial * @param {ContactMaterial} contactMaterial */ World.prototype.addContactMaterial = function(contactMaterial){ this.contactMaterials.push(contactMaterial); }; /** * Removes a contact material * * @method removeContactMaterial * @param {ContactMaterial} cm */ World.prototype.removeContactMaterial = function(cm){ var idx = this.contactMaterials.indexOf(cm); if(idx!==-1){ Utils.splice(this.contactMaterials,idx,1); } }; /** * Get a contact material given two materials * @method getContactMaterial * @param {Material} materialA * @param {Material} materialB * @return {ContactMaterial} The matching ContactMaterial, or false on fail. * @todo Use faster hash map to lookup from material id's */ World.prototype.getContactMaterial = function(materialA,materialB){ var cmats = this.contactMaterials; for(var i=0, N=cmats.length; i!==N; i++){ var cm = cmats[i]; if( (cm.materialA === materialA) && (cm.materialB === materialB) || (cm.materialA === materialB) && (cm.materialB === materialA) ){ return cm; } } return false; }; /** * Removes a constraint * * @method removeConstraint * @param {Constraint} c */ World.prototype.removeConstraint = function(c){ var idx = this.constraints.indexOf(c); if(idx!==-1){ Utils.splice(this.constraints,idx,1); } }; var step_r = vec2.create(), step_runit = vec2.create(), step_u = vec2.create(), step_f = vec2.create(), step_fhMinv = vec2.create(), step_velodt = vec2.create(), step_mg = vec2.create(), xiw = vec2.fromValues(0,0), xjw = vec2.fromValues(0,0), zero = vec2.fromValues(0,0), interpvelo = vec2.fromValues(0,0); /** * Step the physics world forward in time. * * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. * * @method step * @param {Number} dt The fixed time step size to use. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call. * * @example * // fixed timestepping without interpolation * var world = new World(); * world.step(0.01); * * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World */ World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){ maxSubSteps = maxSubSteps || 10; timeSinceLastCalled = timeSinceLastCalled || 0; if(timeSinceLastCalled === 0){ // Fixed, simple stepping this.internalStep(dt); // Increment time this.time += dt; } else { // Compute the number of fixed steps we should have taken since the last step var internalSteps = Math.floor( (this.time+timeSinceLastCalled) / dt) - Math.floor(this.time / dt); internalSteps = Math.min(internalSteps,maxSubSteps); // Do some fixed steps to catch up for(var i=0; i!==internalSteps; i++){ this.internalStep(dt); } // Increment internal clock this.time += timeSinceLastCalled; // Compute "Left over" time step var h = this.time % dt; var h_div_dt = h/dt; for(var j=0; j!==this.bodies.length; j++){ var b = this.bodies[j]; if(b.motionState !== Body.STATIC && b.sleepState !== Body.SLEEPING){ // Interpolate vec2.sub(interpvelo, b.position, b.previousPosition); vec2.scale(interpvelo, interpvelo, h_div_dt); vec2.add(b.interpolatedPosition, b.position, interpvelo); b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt; } else { // For static bodies, just copy. Who else will do it? vec2.copy(b.interpolatedPosition, b.position); b.interpolatedAngle = b.angle; } } } }; var endOverlaps = []; /** * Make a fixed step. * @method internalStep * @param {number} dt * @private */ World.prototype.internalStep = function(dt){ this.stepping = true; var that = this, doProfiling = this.doProfiling, Nsprings = this.springs.length, springs = this.springs, bodies = this.bodies, g = this.gravity, solver = this.solver, Nbodies = this.bodies.length, broadphase = this.broadphase, np = this.narrowphase, constraints = this.constraints, t0, t1, fhMinv = step_fhMinv, velodt = step_velodt, mg = step_mg, scale = vec2.scale, add = vec2.add, rotate = vec2.rotate, islandManager = this.islandManager; this.lastTimeStep = dt; if(doProfiling){ t0 = performance.now(); } // Update approximate friction gravity. if(this.useWorldGravityAsFrictionGravity){ var gravityLen = vec2.length(this.gravity); if(gravityLen === 0 && this.useFrictionGravityOnZeroGravity){ // Leave friction gravity as it is. } else { // Nonzero gravity. Use it. this.frictionGravity = gravityLen; } } // Add gravity to bodies if(this.applyGravity){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i], fi = b.force; if(b.motionState !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ continue; } vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g add(fi,fi,mg); } } // Add spring forces if(this.applySpringForces){ for(var i=0; i!==Nsprings; i++){ var s = springs[i]; s.applyForce(); } } if(this.applyDamping){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i]; if(b.motionState === Body.DYNAMIC){ b.applyDamping(dt); } } } // Broadphase var result = broadphase.getCollisionPairs(this); // Remove ignored collision pairs var ignoredPairs = this.disabledBodyCollisionPairs; for(var i=ignoredPairs.length-2; i>=0; i-=2){ for(var j=result.length-2; j>=0; j-=2){ if( (ignoredPairs[i] === result[j] && ignoredPairs[i+1] === result[j+1]) || (ignoredPairs[i+1] === result[j] && ignoredPairs[i] === result[j+1])){ result.splice(j,2); } } } // Remove constrained pairs with collideConnected == false var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ var c = constraints[i]; if(!c.collideConnected){ for(var j=result.length-2; j>=0; j-=2){ if( (c.bodyA === result[j] && c.bodyB === result[j+1]) || (c.bodyB === result[j] && c.bodyA === result[j+1])){ result.splice(j,2); } } } } // postBroadphase event this.postBroadphaseEvent.pairs = result; this.emit(this.postBroadphaseEvent); // Narrowphase np.reset(this); for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ var bi = result[i], bj = result[i+1]; // Loop over all shapes of body i for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ var si = bi.shapes[k], xi = bi.shapeOffsets[k], ai = bi.shapeAngles[k]; // All shapes of body j for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ var sj = bj.shapes[l], xj = bj.shapeOffsets[l], aj = bj.shapeAngles[l]; var cm = this.defaultContactMaterial; if(si.material && sj.material){ var tmp = this.getContactMaterial(si.material,sj.material); if(tmp){ cm = tmp; } } this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity); } } } // Wake up bodies for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body._wakeUpAfterNarrowphase){ body.wakeUp(); body._wakeUpAfterNarrowphase = false; } } // Emit end overlap events if(this.has('endContact')){ this.overlapKeeper.getEndOverlaps(endOverlaps); var e = this.endContactEvent; var l = endOverlaps.length; while(l--){ var data = endOverlaps[l]; e.shapeA = data.shapeA; e.shapeB = data.shapeB; e.bodyA = data.bodyA; e.bodyB = data.bodyA; this.emit(e); } } this.overlapKeeper.tick(); var preSolveEvent = this.preSolveEvent; preSolveEvent.contactEquations = np.contactEquations; preSolveEvent.frictionEquations = np.frictionEquations; this.emit(preSolveEvent); // update constraint equations var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ constraints[i].update(); } if(np.contactEquations.length || np.frictionEquations.length || constraints.length){ if(this.islandSplit){ // Split into islands islandManager.equations.length = 0; Utils.appendArray(islandManager.equations, np.contactEquations); Utils.appendArray(islandManager.equations, np.frictionEquations); for(i=0; i!==Nconstraints; i++){ Utils.appendArray(islandManager.equations, constraints[i].equations); } islandManager.split(this); for(var i=0; i!==islandManager.islands.length; i++){ var island = islandManager.islands[i]; if(island.equations.length){ solver.solveIsland(dt,island); } } } else { // Add contact equations to solver solver.addEquations(np.contactEquations); solver.addEquations(np.frictionEquations); // Add user-defined constraint equations for(i=0; i!==Nconstraints; i++){ solver.addEquations(constraints[i].equations); } if(this.solveConstraints){ solver.solve(dt,this); } solver.removeAllEquations(); } } // Step forward for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body.sleepState !== Body.SLEEPING && body.motionState !== Body.STATIC){ World.integrateBody(body,dt); } } // Reset force for(var i=0; i!==Nbodies; i++){ bodies[i].setZeroForce(); } if(doProfiling){ t1 = performance.now(); that.lastStepTime = t1-t0; } // Emit impact event if(this.emitImpactEvent && this.has('impact')){ var ev = this.impactEvent; for(var i=0; i!==np.contactEquations.length; i++){ var eq = np.contactEquations[i]; if(eq.firstImpact){ ev.bodyA = eq.bodyA; ev.bodyB = eq.bodyB; ev.shapeA = eq.shapeA; ev.shapeB = eq.shapeB; ev.contactEquation = eq; this.emit(ev); } } } // Sleeping update if(this.enableBodySleeping){ for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, false, dt); } } else if(this.enableIslandSleeping && this.islandSplit){ // Tell all bodies to sleep tick but dont sleep yet for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, true, dt); } // Sleep islands for(var i=0; i<this.islandManager.islands.length; i++){ var island = this.islandManager.islands[i]; if(island.wantsToSleep()){ island.sleep(); } } } this.stepping = false; // Remove bodies that are scheduled for removal if(this.bodiesToBeRemoved.length){ for(var i=0; i!==this.bodiesToBeRemoved.length; i++){ this.removeBody(this.bodiesToBeRemoved[i]); } this.bodiesToBeRemoved.length = 0; } this.emit(this.postStepEvent); }; var ib_fhMinv = vec2.create(); var ib_velodt = vec2.create(); /** * Move a body forward in time. * @static * @method integrateBody * @param {Body} body * @param {Number} dt * @todo Move to Body.prototype? */ World.integrateBody = function(body,dt){ var minv = body.invMass, f = body.force, pos = body.position, velo = body.velocity; // Save old position vec2.copy(body.previousPosition, body.position); body.previousAngle = body.angle; // Angular step if(!body.fixedRotation){ body.angularVelocity += body.angularForce * body.invInertia * dt; body.angle += body.angularVelocity * dt; } // Linear step vec2.scale(ib_fhMinv,f,dt*minv); vec2.add(velo,ib_fhMinv,velo); vec2.scale(ib_velodt,velo,dt); vec2.add(pos,pos,ib_velodt); body.aabbNeedsUpdate = true; }; /** * Runs narrowphase for the shape pair i and j. * @method runNarrowphase * @param {Narrowphase} np * @param {Body} bi * @param {Shape} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Shape} sj * @param {Array} xj * @param {Number} aj * @param {Number} mu */ World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){ // Check collision groups and masks if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){ return; } // Get world position and angle of each shape vec2.rotate(xiw, xi, bi.angle); vec2.rotate(xjw, xj, bj.angle); vec2.add(xiw, xiw, bi.position); vec2.add(xjw, xjw, bj.position); var aiw = ai + bi.angle; var ajw = aj + bj.angle; np.enableFriction = cm.friction > 0; np.frictionCoefficient = cm.friction; var reducedMass; if(bi.motionState === Body.STATIC || bi.motionState === Body.KINEMATIC){ reducedMass = bj.mass; } else if(bj.motionState === Body.STATIC || bj.motionState === Body.KINEMATIC){ reducedMass = bi.mass; } else { reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass); } np.slipForce = cm.friction*glen*reducedMass; np.restitution = cm.restitution; np.surfaceVelocity = cm.surfaceVelocity; np.frictionStiffness = cm.frictionStiffness; np.frictionRelaxation = cm.frictionRelaxation; np.stiffness = cm.stiffness; np.relaxation = cm.relaxation; var resolver = np[si.type | sj.type], numContacts = 0; if (resolver) { var sensor = si.sensor || sj.sensor; var numFrictionBefore = np.frictionEquations.length; if (si.type < sj.type) { numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); } else { numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); } var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; if(numContacts){ if( bi.allowSleep && bi.motionState === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.motionState !== Body.STATIC ){ var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); if(speedSquaredB >= speedLimitSquaredB*2){ bi._wakeUpAfterNarrowphase = true; } } if( bj.allowSleep && bj.motionState === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.motionState !== Body.STATIC ){ var speedSquaredA = vec2.squaredLength(bi.velocity) + Math.pow(bi.angularVelocity,2); var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2); if(speedSquaredA >= speedLimitSquaredA*2){ bj._wakeUpAfterNarrowphase = true; } } this.overlapKeeper.setOverlapping(bi, si, bj, sj); if(this.has('beginContact') && this.overlapKeeper.isNewOverlap(si, sj)){ // Report new shape overlap var e = this.beginContactEvent; e.shapeA = si; e.shapeB = sj; e.bodyA = bi; e.bodyB = bj; // Reset contact equations e.contactEquations.length = 0; if(typeof(numContacts)==="number"){ for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++){ e.contactEquations.push(np.contactEquations[i]); } } this.emit(e); } // divide the max friction force by the number of contacts if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1? for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){ var f = np.frictionEquations[i]; f.setSlipForce(f.getSlipForce() / numFrictionEquations); } } } } }; /** * Add a spring to the simulation * * @method addSpring * @param {Spring} s */ World.prototype.addSpring = function(s){ this.springs.push(s); this.addSpringEvent.spring = s; this.emit(this.addSpringEvent); }; /** * Remove a spring * * @method removeSpring * @param {Spring} s */ World.prototype.removeSpring = function(s){ var idx = this.springs.indexOf(s); if(idx===-1){ Utils.splice(this.springs,idx,1); } }; /** * Add a body to the simulation * * @method addBody * @param {Body} body * * @example * var world = new World(), * body = new Body(); * world.addBody(body); * @todo What if this is done during step? */ World.prototype.addBody = function(body){ if(this.bodies.indexOf(body) === -1){ this.bodies.push(body); body.world = this; this.addBodyEvent.body = body; this.emit(this.addBodyEvent); } }; /** * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step. * * @method removeBody * @param {Body} body */ World.prototype.removeBody = function(body){ if(this.stepping){ this.bodiesToBeRemoved.push(body); } else { body.world = null; var idx = this.bodies.indexOf(body); if(idx!==-1){ Utils.splice(this.bodies,idx,1); this.removeBodyEvent.body = body; body.resetConstraintVelocity(); this.emit(this.removeBodyEvent); } } }; /** * Get a body by its id. * @method getBodyById * @return {Body|Boolean} The body, or false if it was not found. */ World.prototype.getBodyById = function(id){ var bodies = this.bodies; for(var i=0; i<bodies.length; i++){ var b = bodies[i]; if(b.id === id){ return b; } } return false; }; /** * Disable collision between two bodies * @method disableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.disableBodyCollision = function(bodyA,bodyB){ this.disabledBodyCollisionPairs.push(bodyA,bodyB); }; /** * Enable collisions between the given two bodies * @method enableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.enableBodyCollision = function(bodyA,bodyB){ var pairs = this.disabledBodyCollisionPairs; for(var i=0; i<pairs.length; i+=2){ if((pairs[i] === bodyA && pairs[i+1] === bodyB) || (pairs[i+1] === bodyA && pairs[i] === bodyB)){ pairs.splice(i,2); return; } } }; function v2a(v){ if(!v) return v; return [v[0],v[1]]; } function extend(a,b){ for(var key in b) a[key] = b[key]; } function contactMaterialToJSON(cm){ return { id : cm.id, materialA : cm.materialA.id, materialB : cm.materialB.id, friction : cm.friction, restitution : cm.restitution, stiffness : cm.stiffness, relaxation : cm.relaxation, frictionStiffness : cm.frictionStiffness, frictionRelaxation : cm.frictionRelaxation, }; } /** * Convert the world to a JSON-serializable Object. * * @method toJSON * @return {Object} * @deprecated Should use Serializer instead. */ World.prototype.toJSON = function(){ var world = this; var json = { p2 : pkg.version, bodies : [], springs : [], solver : {}, gravity : v2a(world.gravity), broadphase : {}, distanceConstraints : [], revoluteConstraints : [], prismaticConstraints : [], lockConstraints : [], gearConstraints : [], contactMaterials : [], materials : [], defaultContactMaterial : contactMaterialToJSON(world.defaultContactMaterial), islandSplit : world.islandSplit, enableIslandSleeping : world.enableIslandSleeping, enableBodySleeping : world.enableBodySleeping, }; // Solver var js = json.solver, s = world.solver; if(s.type === Solver.GS){ js.type = "GSSolver"; js.iterations = s.iterations; } // Broadphase var jb = json.broadphase, wb = world.broadphase; if(wb.type === Broadphase.NAIVE){ jb.type = "NaiveBroadphase"; } else if(wb.type === Broadphase.SAP) { jb.type = "SAPBroadphase"; //jb.axisIndex = wb.axisIndex; } else { console.error("Broadphase not supported: "+wb.type); } // Serialize springs for(var i=0; i!==world.springs.length; i++){ var s = world.springs[i]; json.springs.push({ bodyA : world.bodies.indexOf(s.bodyA), bodyB : world.bodies.indexOf(s.bodyB), stiffness : s.stiffness, damping : s.damping, restLength : s.restLength, localAnchorA : v2a(s.localAnchorA), localAnchorB : v2a(s.localAnchorB), }); } // Serialize constraints for(var i=0; i<world.constraints.length; i++){ var c = world.constraints[i]; var jc = { bodyA : world.bodies.indexOf(c.bodyA), bodyB : world.bodies.indexOf(c.bodyB), collideConnected : c.collideConnected }; switch(c.type){ case Constraint.DISTANCE: extend(jc,{ distance : c.distance, maxForce : c.getMaxForce(), }); json.distanceConstraints.push(jc); break; case Constraint.REVOLUTE: extend(jc,{ pivotA : v2a(c.pivotA), pivotB : v2a(c.pivotB), maxForce : c.maxForce, motorSpeed : c.getMotorSpeed() || 0, motorEnabled : !!c.getMotorSpeed(), lowerLimit : c.lowerLimit, lowerLimitEnabled : c.lowerLimitEnabled, upperLimit : c.upperLimit, upperLimitEnabled : c.upperLimitEnabled, }); json.revoluteConstraints.push(jc); break; case Constraint.PRISMATIC: extend(jc,{ localAxisA : v2a(c.localAxisA), localAnchorA : v2a(c.localAnchorA), localAnchorB : v2a(c.localAnchorB), maxForce : c.maxForce, upperLimitEnabled : c.upperLimitEnabled, lowerLimitEnabled : c.lowerLimitEnabled, upperLimit : c.upperLimit, lowerLimit : c.lowerLimit, motorEnabled : c.motorEnabled, motorSpeed : c.motorSpeed, }); json.prismaticConstraints.push(jc); break; case Constraint.LOCK: extend(jc,{ localOffsetB : v2a(c.localOffsetB), localAngleB : c.localAngleB, maxForce : c.getMaxForce(), }); json.lockConstraints.push(jc); break; case Constraint.GEAR: extend(jc,{ angle : c.angle, ratio : c.ratio, maxForce : c.maxForce || 1e6, // correct? }); json.gearConstraints.push(jc); break; default: console.error("Constraint not supported yet: ",c.type); break; } } // Serialize bodies for(var i=0; i!==world.bodies.length; i++){ var b = world.bodies[i], ss = b.shapes, jsonBody = { id : b.id, mass : b.mass, angle : b.angle, position : v2a(b.position), velocity : v2a(b.velocity), angularVelocity : b.angularVelocity, force : v2a(b.force), motionState : b.motionState, fixedRotation : b.fixedRotation, circleShapes : [], planeShapes : [], particleShapes : [], lineShapes : [], rectangleShapes : [], convexShapes : [], capsuleShapes : [], }; if(b.concavePath){ jsonBody.concavePath = b.concavePath; } for(var j=0; j<ss.length; j++){ var s = ss[j], jsonShape = {}; jsonShape.offset = v2a(b.shapeOffsets[j]); jsonShape.angle = b.shapeAngles[j]; jsonShape.collisionGroup = s.collisionGroup; jsonShape.collisionMask = s.collisionMask; jsonShape.material = s.material ? s.material.id : null; // Check type switch(s.type){ case Shape.CIRCLE: extend(jsonShape,{ radius : s.radius, }); jsonBody.circleShapes.push(jsonShape); break; case Shape.PLANE: jsonBody.planeShapes.push(jsonShape); break; case Shape.PARTICLE: jsonBody.particleShapes.push(jsonShape); break; case Shape.LINE: jsonShape.length = s.length; jsonBody.lineShapes.push(jsonShape); break; case Shape.RECTANGLE: extend(jsonShape,{ width : s.width, height : s.height }); jsonBody.rectangleShapes.push(jsonShape); break; case Shape.CONVEX: var verts = []; for(var k=0; k<s.vertices.length; k++){ verts.push(v2a(s.vertices[k])); } extend(jsonShape,{ vertices : verts }); jsonBody.convexShapes.push(jsonShape); break; case Shape.CAPSULE: extend(jsonShape,{ length : s.length, radius : s.radius }); jsonBody.capsuleShapes.push(jsonShape); break; default: console.error("Shape type not supported yet!"); break; } } json.bodies.push(jsonBody); } // Serialize contactmaterials for(var i=0; i<world.contactMaterials.length; i++){ var cm = world.contactMaterials[i]; json.contactMaterials.push(contactMaterialToJSON(cm)); } // Serialize materials var mats = {}; // Get unique materials first for(var i=0; i<world.contactMaterials.length; i++){ var cm = world.contactMaterials[i]; mats[cm.materialA.id+''] = cm.materialA; mats[cm.materialB.id+''] = cm.materialB; } for(var matId in mats){ var m = mats[parseInt(matId)]; json.materials.push({ id : m.id, }); } return json; }; /** * Load a scene from a serialized state in JSON format. * * @method fromJSON * @param {Object} json * @return {Boolean} True on success, else false. */ World.prototype.fromJSON = function(json){ this.clear(); if(!json.p2){ return false; } var w = this; // Set gravity vec2.copy(w.gravity, json.gravity); w.islandSplit = json.islandSplit; w.enableIslandSleeping = json.enableIslandSleeping; w.enableBodySleeping = json.enableBodySleeping; // Set solver switch(json.solver.type){ case "GSSolver": var js = json.solver, s = new GSSolver(); w.solver = s; s.iterations = js.iterations; break; default: throw new Error("Solver type not recognized: "+json.solver.type); } // Broadphase switch(json.broadphase.type){ case "NaiveBroadphase": w.broadphase = new NaiveBroadphase(); break; case "SAPBroadphase": w.broadphase = new SAPBroadphase(); break; } w.broadphase.setWorld(w); var bodies = w.bodies; // Load materials var id2material = {}; for(var i=0; i!==json.materials.length; i++){ var jm = json.materials[i]; var m = new Material(); id2material[jm.id+""] = m; m.id = jm.id; } // Load default material w.defaultMaterial.id = json.defaultContactMaterial.materialA; // Load bodies for(var i=0; i!==json.bodies.length; i++){ var jb = json.bodies[i]; // Create body var b = new Body({ mass : jb.mass, position : jb.position, angle : jb.angle, velocity : jb.velocity, angularVelocity : jb.angularVelocity, force : jb.force, fixedRotation : jb.fixedRotation, }); b.id = jb.id; b.motionState = jb.motionState; // Circle for(var j=0; j<jb.circleShapes.length; j++){ var s = jb.circleShapes[j]; addShape(b, new Circle(s.radius), s); } // Plane for(var j=0; j<jb.planeShapes.length; j++){ var s = jb.planeShapes[j]; addShape(b, new Plane(), s); } // Particle for(var j=0; j<jb.particleShapes.length; j++){ var s = jb.particleShapes[j]; addShape(b, new Particle(), s); } // Line for(var j=0; j<jb.lineShapes.length; j++){ var s = jb.lineShapes[j]; addShape(b, new Line(s.length), s); } // Rectangle for(var j=0; j<jb.rectangleShapes.length; j++){ var s = jb.rectangleShapes[j]; addShape(b, new Rectangle(s.width,s.height), s); } // Convex for(var j=0; j<jb.convexShapes.length; j++){ var s = jb.convexShapes[j]; addShape(b, new Convex(s.vertices), s); } // Capsule for(var j=0; j<jb.capsuleShapes.length; j++){ var s = jb.capsuleShapes[j]; addShape(b, new Capsule(s.length, s.radius), s); } function addShape(body, shape, shapeJSON){ shape.collisionMask = shapeJSON.collisionMask; shape.collisionGroup = shapeJSON.collisionGroup; if(shapeJSON.material){ shape.material = id2material[shapeJSON.material+""]; } body.addShape(shape, shapeJSON.offset, shapeJSON.angle); } if(jb.concavePath){ b.concavePath = jb.concavePath; } w.addBody(b); } // Load springs for(var i=0; i<json.springs.length; i++){ var js = json.springs[i]; var bodyA = bodies[js.bodyA], bodyB = bodies[js.bodyB]; if(!bodyA){ this.error = "instance.springs["+i+"] references instance.body["+js.bodyA+"], which does not exist."; return false; } if(!bodyB){ this.error = "instance.springs["+i+"] references instance.body["+js.bodyB+"], which does not exist."; return false; } var s = new Spring(bodyA, bodyB, { stiffness : js.stiffness, damping : js.damping, restLength : js.restLength, localAnchorA : js.localAnchorA, localAnchorB : js.localAnchorB, }); w.addSpring(s); } // Load contact materials for(var i=0; i<json.contactMaterials.length; i++){ var jm = json.contactMaterials[i], matA = id2material[jm.materialA+""], matB = id2material[jm.materialB+""]; if(!matA){ this.error = "Reference to material id "+jm.materialA+": material not found"; return false; } if(!matB){ this.error = "Reference to material id "+jm.materialB+": material not found"; return false; } var cm = new ContactMaterial(matA, matB, { friction : jm.friction, restitution : jm.restitution, stiffness : jm.stiffness, relaxation : jm.relaxation, frictionStiffness : jm.frictionStiffness, frictionRelaxation : jm.frictionRelaxation, }); cm.id = jm.id; w.addContactMaterial(cm); } // Load default contact material var jm = json.defaultContactMaterial, matA = w.defaultMaterial, matB = w.defaultMaterial; var cm = new ContactMaterial(matA, matB, { friction : jm.friction, restitution : jm.restitution, stiffness : jm.stiffness, relaxation : jm.relaxation, frictionStiffness : jm.frictionStiffness, frictionRelaxation : jm.frictionRelaxation, }); cm.id = jm.id; w.defaultContactMaterial = cm; // DistanceConstraint for(var i=0; i<json.distanceConstraints.length; i++){ var c = json.distanceConstraints[i]; w.addConstraint(new DistanceConstraint( bodies[c.bodyA], bodies[c.bodyB], c.distance, { maxForce:c.maxForce, collideConnected:c.collideConnected })); } // RevoluteConstraint for(var i=0; i<json.revoluteConstraints.length; i++){ var c = json.revoluteConstraints[i]; var revolute = new RevoluteConstraint(bodies[c.bodyA], c.pivotA, bodies[c.bodyB], c.pivotB, { maxForce: c.maxForce, collideConnected: c.collideConnected }); if(c.motorEnabled){ revolute.enableMotor(); } revolute.setMotorSpeed(c.motorSpeed); revolute.lowerLimit = c.lowerLimit; revolute.upperLimit = c.upperLimit; revolute.lowerLimitEnabled = c.lowerLimitEnabled; revolute.upperLimitEnabled = c.upperLimitEnabled; w.addConstraint(revolute); } // PrismaticConstraint for(var i=0; i<json.prismaticConstraints.length; i++){ var c = json.prismaticConstraints[i], p = new PrismaticConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, localAxisA : c.localAxisA, localAnchorA : c.localAnchorA, localAnchorB : c.localAnchorB, collideConnected: c.collideConnected }); p.motorSpeed = c.motorSpeed; w.addConstraint(p); } // LockConstraint for(var i=0; i<json.lockConstraints.length; i++){ var c = json.lockConstraints[i]; w.addConstraint(new LockConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, localOffsetB : c.localOffsetB, localAngleB : c.localAngleB, collideConnected: c.collideConnected })); } // GearConstraint for(var i=0; i<json.gearConstraints.length; i++){ var c = json.gearConstraints[i]; w.addConstraint(new GearConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, angle : c.angle, ratio : c.ratio, collideConnected: c.collideConnected })); } return true; }; /** * Resets the World, removes all bodies, constraints and springs. * * @method clear */ World.prototype.clear = function(){ this.time = 0; this.fixedStepTime = 0; // Remove all solver equations if(this.solver && this.solver.equations.length){ this.solver.removeAllEquations(); } // Remove all constraints var cs = this.constraints; for(var i=cs.length-1; i>=0; i--){ this.removeConstraint(cs[i]); } // Remove all bodies var bodies = this.bodies; for(var i=bodies.length-1; i>=0; i--){ this.removeBody(bodies[i]); } // Remove all springs var springs = this.springs; for(var i=springs.length-1; i>=0; i--){ this.removeSpring(springs[i]); } // Remove all contact materials var cms = this.contactMaterials; for(var i=cms.length-1; i>=0; i--){ this.removeContactMaterial(cms[i]); } World.apply(this); }; /** * Get a copy of this World instance * @method clone * @return {World} */ World.prototype.clone = function(){ var world = new World(); world.fromJSON(this.toJSON()); return world; }; var hitTest_tmp1 = vec2.create(), hitTest_zero = vec2.fromValues(0,0), hitTest_tmp2 = vec2.fromValues(0,0); /** * Test if a world point overlaps bodies * @method hitTest * @param {Array} worldPoint Point to use for intersection tests * @param {Array} bodies A list of objects to check for intersection * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @return {Array} Array of bodies that overlap the point */ World.prototype.hitTest = function(worldPoint,bodies,precision){ precision = precision || 0; // Create a dummy particle body with a particle shape to test against the bodies var pb = new Body({ position:worldPoint }), ps = new Particle(), px = worldPoint, pa = 0, x = hitTest_tmp1, zero = hitTest_zero, tmp = hitTest_tmp2; pb.addShape(ps); var n = this.narrowphase, result = []; // Check bodies for(var i=0, N=bodies.length; i!==N; i++){ var b = bodies[i]; for(var j=0, NS=b.shapes.length; j!==NS; j++){ var s = b.shapes[j], offset = b.shapeOffsets[j] || zero, angle = b.shapeAngles[j] || 0.0; // Get shape world position + angle vec2.rotate(x, offset, b.angle); vec2.add(x, x, b.position); var a = angle + b.angle; if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) || (s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision) ){ result.push(b); } } } return result; }; /** * Sets the Equation parameters for all constraints and contact materials. * @method setGlobalEquationParameters * @param {object} [parameters] * @param {Number} [parameters.relaxation] * @param {Number} [parameters.stiffness] */ World.prototype.setGlobalEquationParameters = function(parameters){ parameters = parameters || {}; // Set for all constraints for(var i=0; i !== this.constraints.length; i++){ var c = this.constraints[i]; for(var j=0; j !== c.equations.length; j++){ var eq = c.equations[j]; if(typeof(parameters.stiffness) !== "undefined"){ eq.stiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ eq.relaxation = parameters.relaxation; } eq.needsUpdate = true; } } // Set for all contact materials for(var i=0; i !== this.contactMaterials.length; i++){ var c = this.contactMaterials[i]; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } } // Set for default contact material var c = this.defaultContactMaterial; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } }; /** * Set the stiffness for all equations and contact materials. * @method setGlobalStiffness * @param {Number} stiffness */ World.prototype.setGlobalStiffness = function(stiffness){ this.setGlobalEquationParameters({ stiffness: stiffness }); }; /** * Set the relaxation for all equations and contact materials. * @method setGlobalRelaxation * @param {Number} relaxation */ World.prototype.setGlobalRelaxation = function(relaxation){ this.setGlobalEquationParameters({ relaxation: relaxation }); }; },{"../../package.json":7,"../collision/Broadphase":9,"../collision/NaiveBroadphase":11,"../collision/Narrowphase":12,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/Spring":32,"../shapes/Capsule":34,"../shapes/Circle":35,"../shapes/Convex":36,"../shapes/Line":38,"../shapes/Particle":39,"../shapes/Plane":40,"../shapes/Rectangle":41,"../shapes/Shape":42,"../solver/GSSolver":43,"../solver/Solver":44,"../utils/OverlapKeeper":45,"../utils/Utils":47,"./IslandManager":49}]},{},[33]) (33) }); ;; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ // Add an extra properties to p2 that we need p2.Body.prototype.parent = null; p2.Spring.prototype.parent = null; /** * @class Phaser.Physics.P2 * @classdesc Physics World Constructor * @constructor * @param {Phaser.Game} game - Reference to the current game instance. * @param {object} [config] - Physics configuration object passed in from the game constructor. */ Phaser.Physics.P2 = function (game, config) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; if (typeof config === 'undefined' || !config.hasOwnProperty('gravity') || !config.hasOwnProperty('broadphase')) { config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; } /** * @property {p2.World} world - The p2 World in which the simulation is run. * @protected */ this.world = new p2.World(config); /** * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. * @default */ this.frameRate = 1 / 60; /** * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. * @default */ this.useElapsedTime = false; /** * @property {boolean} paused - The paused state of the P2 World. * @default */ this.paused = false; /** * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials. * @protected */ this.materials = []; /** * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. */ this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); /** * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. */ this.walls = { left: null, right: null, top: null, bottom: null }; /** * @property {Phaser.Signal} onBodyAdded - Dispatched when a new Body is added to the World. */ this.onBodyAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onBodyRemoved - Dispatched when a Body is removed from the World. */ this.onBodyRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringAdded - Dispatched when a new Spring is added to the World. */ this.onSpringAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringRemoved - Dispatched when a Spring is removed from the World. */ this.onSpringRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintAdded - Dispatched when a new Constraint is added to the World. */ this.onConstraintAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintRemoved - Dispatched when a Constraint is removed from the World. */ this.onConstraintRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialAdded - Dispatched when a new ContactMaterial is added to the World. */ this.onContactMaterialAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialRemoved - Dispatched when a ContactMaterial is removed from the World. */ this.onContactMaterialRemoved = new Phaser.Signal(); /** * @property {function} postBroadphaseCallback - A postBroadphase callback. */ this.postBroadphaseCallback = null; /** * @property {object} callbackContext - The context under which the callbacks are fired. */ this.callbackContext = null; /** * @property {Phaser.Signal} onBeginContact - Dispatched when a first contact is created between two bodies. This event is fired before the step has been done. */ this.onBeginContact = new Phaser.Signal(); /** * @property {Phaser.Signal} onEndContact - Dispatched when final contact occurs between two bodies. This event is fired before the step has been done. */ this.onEndContact = new Phaser.Signal(); // Pixel to meter function overrides if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) { this.mpx = config.mpx; this.mpxi = config.mpxi; this.pxm = config.pxm; this.pxmi = config.pxmi; } // Hook into the World events this.world.on("beginContact", this.beginContactHandler, this); this.world.on("endContact", this.endContactHandler, this); /** * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. */ this.collisionGroups = []; /** * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. */ this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); /** * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. */ this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); /** * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. */ this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); /** * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. */ this.boundsCollidesWith = []; /** * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. * @private */ this._toRemove = []; /** * @property {number} _collisionGroupID - Internal var. * @private */ this._collisionGroupID = 2; // By default we want everything colliding with everything this.setBoundsToWorld(true, true, true, true, false); }; Phaser.Physics.P2.prototype = { /** * This will add a P2 Physics body into the removal list for the next step. * * @method Phaser.Physics.P2#removeBodyNextStep * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. */ removeBodyNextStep: function (body) { this._toRemove.push(body); }, /** * Called at the start of the core update loop. Purges flagged bodies from the world. * * @method Phaser.Physics.P2#preUpdate */ preUpdate: function () { var i = this._toRemove.length; while (i--) { this.removeBody(this._toRemove[i]); } this._toRemove.length = 0; }, /** * This will create a P2 Physics body on the given game object or array of game objects. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. * * @method Phaser.Physics.P2#enable * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. * @param {boolean} [debug=false] - Create a debug object to go with this body? * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. */ enable: function (object, debug, children) { if (typeof debug === 'undefined') { debug = false; } if (typeof children === 'undefined') { children = true; } var i = 1; if (Array.isArray(object)) { i = object.length; while (i--) { if (object[i] instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object[i].children, debug, children); } else { this.enableBody(object[i], debug); if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) { this.enable(object[i], debug, true); } } } } else { if (object instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object.children, debug, children); } else { this.enableBody(object, debug); if (children && object.hasOwnProperty('children') && object.children.length > 0) { this.enable(object.children, debug, true); } } } }, /** * Creates a P2 Physics body on the given game object. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. * * @method Phaser.Physics.P2#enableBody * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. * @param {boolean} debug - Create a debug object to go with this body? */ enableBody: function (object, debug) { if (object.hasOwnProperty('body') && object.body === null) { object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1); object.body.debug = debug; object.anchor.set(0.5); } }, /** * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. * * @method Phaser.Physics.P2#setImpactEvents * @param {boolean} state - Set to true to enable impact events, or false to disable. */ setImpactEvents: function (state) { if (state) { this.world.on("impact", this.impactHandler, this); } else { this.world.off("impact", this.impactHandler, this); } }, /** * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. * Returning `true` from the callback will ensure they are checked in the narrowphase. * * @method Phaser.Physics.P2#setPostBroadphaseCallback * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. * @param {object} context - The context under which the callback will be fired. */ setPostBroadphaseCallback: function (callback, context) { this.postBroadphaseCallback = callback; this.callbackContext = context; if (callback !== null) { this.world.on("postBroadphase", this.postBroadphaseHandler, this); } else { this.world.off("postBroadphase", this.postBroadphaseHandler, this); } }, /** * Internal handler for the postBroadphase event. * * @method Phaser.Physics.P2#postBroadphaseHandler * @private * @param {object} event - The event data. */ postBroadphaseHandler: function (event) { if (this.postBroadphaseCallback) { var i = event.pairs.length; while (i -= 2) { if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent)) { event.pairs.splice(i, 2); } } } }, /** * Handles a p2 impact event. * * @method Phaser.Physics.P2#impactHandler * @private * @param {object} event - The event data. */ impactHandler: function (event) { if (event.bodyA.parent && event.bodyB.parent) { // Body vs. Body callbacks var a = event.bodyA.parent; var b = event.bodyB.parent; if (a._bodyCallbacks[event.bodyB.id]) { a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB); } if (b._bodyCallbacks[event.bodyA.id]) { b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA); } // Body vs. Group callbacks if (a._groupCallbacks[event.shapeB.collisionGroup]) { a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB); } if (b._groupCallbacks[event.shapeA.collisionGroup]) { b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA); } } }, /** * Handles a p2 begin contact event. * * @method Phaser.Physics.P2#beginContactHandler * @param {object} event - The event data. */ beginContactHandler: function (event) { this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations); if (event.bodyA.parent) { event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB, event.contactEquations); } if (event.bodyB.parent) { event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA, event.contactEquations); } }, /** * Handles a p2 end contact event. * * @method Phaser.Physics.P2#endContactHandler * @param {object} event - The event data. */ endContactHandler: function (event) { this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); if (event.bodyA.parent) { event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB); } if (event.bodyB.parent) { event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA); } }, /** * Sets the bounds of the Physics world to match the Game.World dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics#setBoundsToWorld * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) { this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup); }, /** * Sets the given material against the 4 bounds of this World. * * @method Phaser.Physics#setWorldMaterial * @param {Phaser.Physics.P2.Material} material - The material to set. * @param {boolean} [left=true] - If true will set the material on the left bounds wall. * @param {boolean} [right=true] - If true will set the material on the right bounds wall. * @param {boolean} [top=true] - If true will set the material on the top bounds wall. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. */ setWorldMaterial: function (material, left, right, top, bottom) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (left && this.walls.left) { this.walls.left.shapes[0].material = material; } if (right && this.walls.right) { this.walls.right.shapes[0].material = material; } if (top && this.walls.top) { this.walls.top.shapes[0].material = material; } if (bottom && this.walls.bottom) { this.walls.bottom.shapes[0].material = material; } }, /** * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. * If you start to use your own collision groups then your objects will no longer collide with the bounds. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. * * @method Phaser.Physics.P2#updateBoundsCollisionGroup * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ updateBoundsCollisionGroup: function (setCollisionGroup) { var mask = this.everythingCollisionGroup.mask; if (typeof setCollisionGroup === 'undefined') { mask = this.boundsCollisionGroup.mask; } if (this.walls.left) { this.walls.left.shapes[0].collisionGroup = mask; } if (this.walls.right) { this.walls.right.shapes[0].collisionGroup = mask; } if (this.walls.top) { this.walls.top.shapes[0].collisionGroup = mask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionGroup = mask; } }, /** * Sets the bounds of the Physics world to match the given world pixel dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics.P2#setBounds * @param {number} x - The x coordinate of the top-left corner of the bounds. * @param {number} y - The y coordinate of the top-left corner of the bounds. * @param {number} width - The width of the bounds. * @param {number} height - The height of the bounds. * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (typeof setCollisionGroup === 'undefined') { setCollisionGroup = true; } if (this.walls.left) { this.world.removeBody(this.walls.left); } if (this.walls.right) { this.world.removeBody(this.walls.right); } if (this.walls.top) { this.world.removeBody(this.walls.top); } if (this.walls.bottom) { this.world.removeBody(this.walls.bottom); } if (left) { this.walls.left = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: 1.5707963267948966 }); this.walls.left.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.left.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.left); } if (right) { this.walls.right = new p2.Body({ mass: 0, position: [ this.pxmi(x + width), this.pxmi(y) ], angle: -1.5707963267948966 }); this.walls.right.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.right.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.right); } if (top) { this.walls.top = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: -3.141592653589793 }); this.walls.top.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.top.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.top); } if (bottom) { this.walls.bottom = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y + height) ] }); this.walls.bottom.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.bottom.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.bottom); } }, /** * Pauses the P2 World independent of the game pause state. * * @method Phaser.Physics.P2#pause */ pause: function() { this.paused = true; }, /** * Resumes a paused P2 World. * * @method Phaser.Physics.P2#resume */ resume: function() { this.paused = false; }, /** * Internal P2 update loop. * * @method Phaser.Physics.P2#update */ update: function () { // Do nothing when the pysics engine was paused before if (this.paused) { return; } if (this.useElapsedTime) { this.world.step(this.game.time.physicsElapsed); } else { this.world.step(this.frameRate); } }, /** * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. * * @method Phaser.Physics.P2#clear */ clear: function () { this.world.clear(); this.world.off("beginContact", this.beginContactHandler, this); this.world.off("endContact", this.endContactHandler, this); this.postBroadphaseCallback = null; this.callbackContext = null; this.impactCallback = null; this.collisionGroups = []; this._toRemove = []; this._collisionGroupID = 2; this.boundsCollidesWith = []; }, /** * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. * * @method Phaser.Physics.P2#destroy */ destroy: function () { this.clear(); this.game = null; }, /** * Add a body to the world. * * @method Phaser.Physics.P2#addBody * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. * @return {boolean} True if the Body was added successfully, otherwise false. */ addBody: function (body) { if (body.data.world) { return false; } else { this.world.addBody(body.data); this.onBodyAdded.dispatch(body); return true; } }, /** * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. * * @method Phaser.Physics.P2#removeBody * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. * @return {Phaser.Physics.P2.Body} The Body that was removed. */ removeBody: function (body) { if (body.data.world == this.world) { this.world.removeBody(body.data); this.onBodyRemoved.dispatch(body); } return body; }, /** * Adds a Spring to the world. * * @method Phaser.Physics.P2#addSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to add to the World. * @return {Phaser.Physics.P2.Spring} The Spring that was added. */ addSpring: function (spring) { this.world.addSpring(spring); this.onSpringAdded.dispatch(spring); return spring; }, /** * Removes a Spring from the world. * * @method Phaser.Physics.P2#removeSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. * @return {Phaser.Physics.P2.Spring} The Spring that was removed. */ removeSpring: function (spring) { this.world.removeSpring(spring); this.onSpringRemoved.dispatch(spring); return spring; }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createDistanceConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint */ createDistanceConstraint: function (bodyA, bodyB, distance, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, maxForce)); } }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createGearConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. * @return {Phaser.Physics.P2.GearConstraint} The constraint */ createGearConstraint: function (bodyA, bodyB, angle, ratio) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio)); } }, /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @method Phaser.Physics.P2#createRevoluteConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint */ createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce)); } }, /** * Locks the relative position between two bodies. * * @method Phaser.Physics.P2#createLockConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.LockConstraint} The constraint */ createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce)); } }, /** * Constraint that only allows bodies to move along a line, relative to each other. * See http://www.iforce2d.net/b2dtut/joints-prismatic * * @method Phaser.Physics.P2#createPrismaticConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint */ createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce)); } }, /** * Adds a Constraint to the world. * * @method Phaser.Physics.P2#addConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. */ addConstraint: function (constraint) { this.world.addConstraint(constraint); this.onConstraintAdded.dispatch(constraint); return constraint; }, /** * Removes a Constraint from the world. * * @method Phaser.Physics.P2#removeConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. */ removeConstraint: function (constraint) { this.world.removeConstraint(constraint); this.onConstraintRemoved.dispatch(constraint); return constraint; }, /** * Adds a Contact Material to the world. * * @method Phaser.Physics.P2#addContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. */ addContactMaterial: function (material) { this.world.addContactMaterial(material); this.onContactMaterialAdded.dispatch(material); return material; }, /** * Removes a Contact Material from the world. * * @method Phaser.Physics.P2#removeContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. */ removeContactMaterial: function (material) { this.world.removeContactMaterial(material); this.onContactMaterialRemoved.dispatch(material); return material; }, /** * Gets a Contact Material based on the two given Materials. * * @method Phaser.Physics.P2#getContactMaterial * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. */ getContactMaterial: function (materialA, materialB) { return this.world.getContactMaterial(materialA, materialB); }, /** * Sets the given Material against all Shapes owned by all the Bodies in the given array. * * @method Phaser.Physics.P2#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on. */ setMaterial: function (material, bodies) { var i = bodies.length; while (i--) { bodies[i].setMaterial(material); } }, /** * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. * * @method Phaser.Physics.P2#createMaterial * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. */ createMaterial: function (name, body) { name = name || ''; var material = new Phaser.Physics.P2.Material(name); this.materials.push(material); if (typeof body !== 'undefined') { body.setMaterial(material); } return material; }, /** * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. * * @method Phaser.Physics.P2#createContactMaterial * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {object} [options] - Material options object. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. */ createContactMaterial: function (materialA, materialB, options) { if (typeof materialA === 'undefined') { materialA = this.createMaterial(); } if (typeof materialB === 'undefined') { materialB = this.createMaterial(); } var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); return this.addContactMaterial(contact); }, /** * Populates and returns an array with references to of all current Bodies in the world. * * @method Phaser.Physics.P2#getBodies * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world. */ getBodies: function () { var output = []; var i = this.world.bodies.length; while (i--) { output.push(this.world.bodies[i].parent); } return output; }, /** * Checks the given object to see if it has a p2.Body and if so returns it. * * @method Phaser.Physics.P2#getBody * @param {object} object - The object to check for a p2.Body on. * @return {p2.Body} The p2.Body, or null if not found. */ getBody: function (object) { if (object instanceof p2.Body) { // Native p2 body return object; } else if (object instanceof Phaser.Physics.P2.Body) { // Phaser P2 Body return object.data; } else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) { // Sprite, TileSprite, etc return object.body.data; } return null; }, /** * Populates and returns an array of all current Springs in the world. * * @method Phaser.Physics.P2#getSprings * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world. */ getSprings: function () { var output = []; var i = this.world.springs.length; while (i--) { output.push(this.world.springs[i].parent); } return output; }, /** * Populates and returns an array of all current Constraints in the world. * * @method Phaser.Physics.P2#getConstraints * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world. */ getConstraints: function () { var output = []; var i = this.world.constraints.length; while (i--) { output.push(this.world.constraints[i].parent); } return output; }, /** * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. * * @method Phaser.Physics.P2#hitTest * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. * @return {Array} Array of bodies that overlap the point. */ hitTest: function (worldPoint, bodies, precision, filterStatic) { if (typeof bodies === 'undefined') { bodies = this.world.bodies; } if (typeof precision === 'undefined') { precision = 5; } if (typeof filterStatic === 'undefined') { filterStatic = false; } var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ]; var query = []; var i = bodies.length; while (i--) { if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.motionState === p2.Body.STATIC)) { query.push(bodies[i].data); } else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].motionState === p2.Body.STATIC)) { query.push(bodies[i]); } else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.motionState === p2.Body.STATIC)) { query.push(bodies[i].body.data); } } return this.world.hitTest(physicsPosition, query, precision); }, /** * Converts the current world into a JSON object. * * @method Phaser.Physics.P2#toJSON * @return {object} A JSON representation of the world. */ toJSON: function () { return this.world.toJSON(); }, /** * Creates a new Collision Group and optionally applies it to the given object. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. * * @method Phaser.Physics.P2#createCollisionGroup * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. */ createCollisionGroup: function (object) { var bitmask = Math.pow(2, this._collisionGroupID); if (this.walls.left) { this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask; } if (this.walls.right) { this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask; } if (this.walls.top) { this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask; } this._collisionGroupID++; var group = new Phaser.Physics.P2.CollisionGroup(bitmask); this.collisionGroups.push(group); if (object) { this.setCollisionGroup(object, group); } return group; }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. * * @method Phaser.Physics.P2y#setCollisionGroup * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. */ setCollisionGroup: function (object, group) { if (object instanceof Phaser.Group) { for (var i = 0; i < object.total; i++) { if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) { object.children[i].body.setCollisionGroup(group); } } } else { object.body.setCollisionGroup(group); } }, /** * Creates a spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @return {Phaser.Physics.P2.Spring} The spring */ createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); } }, /** * Creates a new Body and adds it to the World. * * @method Phaser.Physics.P2#createBody * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {Phaser.Physics.P2.Body} The body */ createBody: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Creates a new Particle and adds it to the World. * * @method Phaser.Physics.P2#createParticle * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. */ createParticle: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world. * Note that the polylines must be created in such a way that they can withstand polygon decomposition. * * @method Phaser.Physics.P2#convertCollisionObjects * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. * @return {array} An array of the Phaser.Physics.Body objects that have been created. */ convertCollisionObjects: function (map, layer, addToWorld) { if (typeof addToWorld === 'undefined') { addToWorld = true; } var output = []; for (var i = 0, len = map.collision[layer].length; i < len; i++) { // name: json.layers[i].objects[v].name, // x: json.layers[i].objects[v].x, // y: json.layers[i].objects[v].y, // width: json.layers[i].objects[v].width, // height: json.layers[i].objects[v].height, // visible: json.layers[i].objects[v].visible, // properties: json.layers[i].objects[v].properties, // polyline: json.layers[i].objects[v].polyline var object = map.collision[layer][i]; var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline); if (body) { output.push(body); } } return output; }, /** * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. * * @method Phaser.Physics.P2#clearTilemapLayerBodies * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. */ clearTilemapLayerBodies: function (map, layer) { layer = map.getLayer(layer); var i = map.layers[layer].bodies.length; while (i--) { map.layers[layer].bodies[i].destroy(); } map.layers[layer].bodies.length = 0; }, /** * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. * Every time you call this method it will destroy any previously created bodies and remove them from the world. * Therefore understand it's a very expensive operation and not to be done in a core game update loop. * * @method Phaser.Physics.P2#convertTilemap * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. */ convertTilemap: function (map, layer, addToWorld, optimize) { layer = map.getLayer(layer); if (typeof addToWorld === 'undefined') { addToWorld = true; } if (typeof optimize === 'undefined') { optimize = true; } // If the bodies array is already populated we need to nuke it this.clearTilemapLayerBodies(map, layer); var width = 0; var sx = 0; var sy = 0; for (var y = 0, h = map.layers[layer].height; y < h; y++) { width = 0; for (var x = 0, w = map.layers[layer].width; x < w; x++) { var tile = map.layers[layer].data[y][x]; if (tile && tile.index > -1 && tile.collides) { if (optimize) { var right = map.getTileRight(layer, x, y); if (width === 0) { sx = tile.x * tile.width; sy = tile.y * tile.height; width = tile.width; } if (right && right.collides) { width += tile.width; } else { var body = this.createBody(sx, sy, 0, false); body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); width = 0; } } else { var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false); body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); } } } } return map.layers[layer].bodies; }, /** * Convert p2 physics value (meters) to pixel scale. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpx * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpx: function (v) { return v *= 20; }, /** * Convert pixel value to p2 physics scale (meters). * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxm * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxm: function (v) { return v * 0.05; }, /** * Convert p2 physics value (meters) to pixel scale and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpxi * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpxi: function (v) { return v *= -20; }, /** * Convert pixel value to p2 physics scale (meters) and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxmi * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxmi: function (v) { return v * -0.05; } }; /** * @name Phaser.Physics.P2#friction * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#defaultFriction * @property {number} defaultFriction - DEPRECATED: Use World.friction instead. */ Object.defineProperty(Phaser.Physics.P2.prototype, "defaultFriction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#restitution * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#defaultRestitution * @property {number} defaultRestitution - DEPRECATED: Use World.restitution instead. */ Object.defineProperty(Phaser.Physics.P2.prototype, "defaultRestitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#contactMaterial * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. */ Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { get: function () { return this.world.defaultContactMaterial; }, set: function (value) { this.world.defaultContactMaterial = value; } }); /** * @name Phaser.Physics.P2#applySpringForces * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { get: function () { return this.world.applySpringForces; }, set: function (value) { this.world.applySpringForces = value; } }); /** * @name Phaser.Physics.P2#applyDamping * @property {boolean} applyDamping - Enable to automatically apply body damping each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { get: function () { return this.world.applyDamping; }, set: function (value) { this.world.applyDamping = value; } }); /** * @name Phaser.Physics.P2#applyGravity * @property {boolean} applyGravity - Enable to automatically apply gravity each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { get: function () { return this.world.applyGravity; }, set: function (value) { this.world.applyGravity = value; } }); /** * @name Phaser.Physics.P2#solveConstraints * @property {boolean} solveConstraints - Enable/disable constraint solving in each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { get: function () { return this.world.solveConstraints; }, set: function (value) { this.world.solveConstraints = value; } }); /** * @name Phaser.Physics.P2#time * @property {boolean} time - The World time. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "time", { get: function () { return this.world.time; } }); /** * @name Phaser.Physics.P2#emitImpactEvent * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. */ Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { get: function () { return this.world.emitImpactEvent; }, set: function (value) { this.world.emitImpactEvent = value; } }); /** * @name Phaser.Physics.P2#enableBodySleeping * @property {boolean} enableBodySleeping - Enable / disable automatic body sleeping. */ Object.defineProperty(Phaser.Physics.P2.prototype, "enableBodySleeping", { get: function () { return this.world.enableBodySleeping; }, set: function (value) { this.world.enableBodySleeping = value; } }); /** * @name Phaser.Physics.P2#total * @property {number} total - The total number of bodies in the world. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "total", { get: function () { return this.world.bodies.length; } }); /* jshint noarg: false */ /** * @author Georgios Kaleadis https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Allow to access a list of created fixture (coming from Body#addPhaserPolygon) * which itself parse the input from PhysicsEditor with the custom phaser exporter. * You can access fixtures of a Body by a group index or even by providing a fixture Key. * You can set the fixture key and also the group index for a fixture in PhysicsEditor. * This gives you the power to create a complex body built of many fixtures and modify them * during runtime (to remove parts, set masks, categories & sensor properties) * * @class Phaser.Physics.P2.FixtureList * @classdesc Collection for generated P2 fixtures * @constructor * @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) */ Phaser.Physics.P2.FixtureList = function (list) { if (!Array.isArray(list)) { list = [list]; } this.rawList = list; this.init(); this.parse(this.rawList); }; Phaser.Physics.P2.FixtureList.prototype = { /** * @method Phaser.Physics.P2.FixtureList#init */ init: function () { /** * @property {object} namedFixtures - Collect all fixtures with a key * @private */ this.namedFixtures = {}; /** * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group * @private */ this.groupedFixtures = []; /** * @property {Array} allFixtures - This is a list of everything in this collection * @private */ this.allFixtures = []; }, /** * @method Phaser.Physics.P2.FixtureList#setCategory * @param {number} bit - The bit to set as the collision group. * @param {string} fixtureKey - Only apply to the fixture with the given key. */ setCategory: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionGroup = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMask * @param {number} bit - The bit to set as the collision mask * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMask: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionMask = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setSensor * @param {boolean} value - sensor true or false * @param {string} fixtureKey - Only apply to the fixture with the given key */ setSensor: function (value, fixtureKey) { var setter = function(fixture) { fixture.sensor = value; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMaterial * @param {Object} material - The contact material for a fixture * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMaterial: function (material, fixtureKey) { var setter = function(fixture) { fixture.material = material; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * Accessor to get either a list of specified fixtures by key or the whole fixture list * * @method Phaser.Physics.P2.FixtureList#getFixtures * @param {array} keys - A list of fixture keys */ getFixtures: function (keys) { var fixtures = []; if (keys) { if (!(keys instanceof Array)) { keys = [keys]; } var self = this; keys.forEach(function(key) { if (self.namedFixtures[key]) { fixtures.push(self.namedFixtures[key]); } }); return this.flatten(fixtures); } else { return this.allFixtures; } }, /** * Accessor to get either a single fixture by its key. * * @method Phaser.Physics.P2.FixtureList#getFixtureByKey * @param {string} key - The key of the fixture. */ getFixtureByKey: function (key) { return this.namedFixtures[key]; }, /** * Accessor to get a group of fixtures by its group index. * * @method Phaser.Physics.P2.FixtureList#getGroup * @param {number} groupID - The group index. */ getGroup: function (groupID) { return this.groupedFixtures[groupID]; }, /** * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon * * @method Phaser.Physics.P2.FixtureList#parse */ parse: function () { var key, value, _ref, _results; _ref = this.rawList; _results = []; for (key in _ref) { value = _ref[key]; if (!isNaN(key - 0)) { this.groupedFixtures[key] = this.groupedFixtures[key] || []; this.groupedFixtures[key] = this.groupedFixtures[key].concat(value); } else { this.namedFixtures[key] = this.flatten(value); } _results.push(this.allFixtures = this.flatten(this.groupedFixtures)); } }, /** * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. * * @method Phaser.Physics.P2.FixtureList#flatten * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. */ flatten: function (array) { var result, self; result = []; self = arguments.callee; array.forEach(function(item) { return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item])); }); return result; } }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. * * @class Phaser.Physics.P2.PointProxy * @classdesc PointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.PointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; /** * @name Phaser.Physics.P2.PointProxy#x * @property {number} x - The x property of this PointProxy. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = this.world.pxm(value); } }); /** * @name Phaser.Physics.P2.PointProxy#y * @property {number} y - The y property of this PointProxy. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = this.world.pxm(value); } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. * * @class Phaser.Physics.P2.InversePointProxy * @classdesc InversePointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.InversePointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; /** * @name Phaser.Physics.P2.InversePointProxy#x * @property {number} x - The x property of this InversePointProxy. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = this.world.pxm(-value); } }); /** * @name Phaser.Physics.P2.InversePointProxy#y * @property {number} y - The y property of this InversePointProxy. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = this.world.pxm(-value); } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. * * @class Phaser.Physics.P2.Body * @classdesc Physics Body Constructor * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. * @param {number} [x=0] - The x coordinate of this Body. * @param {number} [y=0] - The y coordinate of this Body. * @param {number} [mass=1] - The default mass of this Body (0 = static). */ Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { sprite = sprite || null; x = x || 0; y = y || 0; if (typeof mass === 'undefined') { mass = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {Phaser.Physics.P2} world - Local reference to the P2 World. */ this.world = game.physics.p2; /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ this.sprite = sprite; /** * @property {number} type - The type of physics system this body belongs to. */ this.type = Phaser.Physics.P2JS; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ this.offset = new Phaser.Point(); /** * @property {p2.Body} data - The p2 Body data. * @protected */ this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); this.data.parent = this; /** * @property {Phaser.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. */ this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); /** * @property {Phaser.InversePointProxy} force - The force applied to the body. */ this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); /** * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. */ this.gravity = new Phaser.Point(); /** * Dispatched when a first contact is created between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 4 parameters: The body it is in contact with, the shape from this body that caused the contact, the shape from the contact body and the contact equation data array. * @property {Phaser.Signal} onBeginContact */ this.onBeginContact = new Phaser.Signal(); /** * Dispatched when contact ends between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 3 parameters: The body it is in contact with, the shape from this body that caused the contact and the shape from the contact body. * @property {Phaser.Signal} onEndContact */ this.onEndContact = new Phaser.Signal(); /** * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. */ this.collidesWith = []; /** * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. */ this.removeNextStep = false; /** * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. */ this.debugBody = null; /** * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. * @private */ this._collideWorldBounds = true; /** * @property {object} _bodyCallbacks - Array of Body callbacks. * @private */ this._bodyCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Body callback contexts. * @private */ this._bodyCallbackContext = {}; /** * @property {object} _groupCallbacks - Array of Group callbacks. * @private */ this._groupCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. * @private */ this._groupCallbackContext = {}; // Set-up the default shape if (sprite) { this.setRectangleFromSprite(sprite); if (sprite.exists) { this.game.physics.p2.addBody(this); } } }; Phaser.Physics.P2.Body.prototype = { /** * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createBodyCallback * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createBodyCallback: function (object, callback, callbackContext) { var id = -1; if (object['id']) { id = object.id; } else if (object['body']) { id = object.body.id; } if (id > -1) { if (callback === null) { delete (this._bodyCallbacks[id]); delete (this._bodyCallbackContext[id]); } else { this._bodyCallbacks[id] = callback; this._bodyCallbackContext[id] = callbackContext; } } }, /** * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * This callback will only fire if this Body has been assigned a collision group. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createGroupCallback * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createGroupCallback: function (group, callback, callbackContext) { if (callback === null) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbacksContext[group.mask]); } else { this._groupCallbacks[group.mask] = callback; this._groupCallbackContext[group.mask] = callbackContext; } }, /** * Gets the collision bitmask from the groups this body collides with. * * @method Phaser.Physics.P2.Body#getCollisionMask * @return {number} The bitmask. */ getCollisionMask: function () { var mask = 0; if (this._collideWorldBounds) { mask = this.game.physics.p2.boundsCollisionGroup.mask; } for (var i = 0; i < this.collidesWith.length; i++) { mask = mask | this.collidesWith[i].mask; } return mask; }, /** * Updates the collisionMask. * * @method Phaser.Physics.P2.Body#updateCollisionMask * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ updateCollisionMask: function (shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * This also resets the collisionMask. * * @method Phaser.Physics.P2.Body#setCollisionGroup * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ setCollisionGroup: function (group, shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionGroup = group.mask; this.data.shapes[i].collisionMask = mask; } } else { shape.collisionGroup = group.mask; shape.collisionMask = mask; } }, /** * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. * * @method Phaser.Physics.P2.Body#clearCollision * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. */ clearCollision: function (clearGroup, clearMask, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { if (clearGroup) { this.data.shapes[i].collisionGroup = null; } if (clearMask) { this.data.shapes[i].collisionMask = null; } } } else { if (clearGroup) { shape.collisionGroup = null; } if (clearMask) { shape.collisionMask = null; } } if (clearGroup) { this.collidesWith.length = 0; } }, /** * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#collides * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. * @param {object} [callbackContext] - The context under which the callback will be called. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. */ collides: function (group, callback, callbackContext, shape) { if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { if (this.collidesWith.indexOf(group[i]) === -1) { this.collidesWith.push(group[i]); if (callback) { this.createGroupCallback(group[i], callback, callbackContext); } } } } else { if (this.collidesWith.indexOf(group) === -1) { this.collidesWith.push(group); if (callback) { this.createGroupCallback(group, callback, callbackContext); } } } var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Moves the shape offsets so their center of mass becomes the body center of mass. * * @method Phaser.Physics.P2.Body#adjustCenterOfMass */ adjustCenterOfMass: function () { this.data.adjustCenterOfMass(); }, /** * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. * * @method Phaser.Physics.P2.Body#applyDamping * @param {number} dt - Current time step. */ applyDamping: function (dt) { this.data.applyDamping(dt); }, /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * * @method Phaser.Physics.P2.Body#applyForce * @param {Float32Array|Array} force - The force vector to add. * @param {number} worldX - The world x point to apply the force on. * @param {number} worldY - The world y point to apply the force on. */ applyForce: function (force, worldX, worldY) { this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Sets the force on the body to zero. * * @method Phaser.Physics.P2.Body#setZeroForce */ setZeroForce: function () { this.data.setZeroForce(); }, /** * If this Body is dynamic then this will zero its angular velocity. * * @method Phaser.Physics.P2.Body#setZeroRotation */ setZeroRotation: function () { this.data.angularVelocity = 0; }, /** * If this Body is dynamic then this will zero its velocity on both axis. * * @method Phaser.Physics.P2.Body#setZeroVelocity */ setZeroVelocity: function () { this.data.velocity[0] = 0; this.data.velocity[1] = 0; }, /** * Sets the Body damping and angularDamping to zero. * * @method Phaser.Physics.P2.Body#setZeroDamping */ setZeroDamping: function () { this.data.damping = 0; this.data.angularDamping = 0; }, /** * Transform a world point to local body frame. * * @method Phaser.Physics.P2.Body#toLocalFrame * @param {Float32Array|Array} out - The vector to store the result in. * @param {Float32Array|Array} worldPoint - The input world vector. */ toLocalFrame: function (out, worldPoint) { return this.data.toLocalFrame(out, worldPoint); }, /** * Transform a local point to world frame. * * @method Phaser.Physics.P2.Body#toWorldFrame * @param {Array} out - The vector to store the result in. * @param {Array} localPoint - The input local vector. */ toWorldFrame: function (out, localPoint) { return this.data.toWorldFrame(out, localPoint); }, /** * This will rotate the Body by the given speed to the left (counter-clockwise). * * @method Phaser.Physics.P2.Body#rotateLeft * @param {number} speed - The speed at which it should rotate. */ rotateLeft: function (speed) { this.data.angularVelocity = this.world.pxm(-speed); }, /** * This will rotate the Body by the given speed to the left (clockwise). * * @method Phaser.Physics.P2.Body#rotateRight * @param {number} speed - The speed at which it should rotate. */ rotateRight: function (speed) { this.data.angularVelocity = this.world.pxm(speed); }, /** * Moves the Body forwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveForward * @param {number} speed - The speed at which it should move forwards. */ moveForward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = magnitude * Math.cos(angle); this.data.velocity[1] = magnitude * Math.sin(angle); }, /** * Moves the Body backwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveBackward * @param {number} speed - The speed at which it should move backwards. */ moveBackward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = -(magnitude * Math.cos(angle)); this.data.velocity[1] = -(magnitude * Math.sin(angle)); }, /** * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrust * @param {number} speed - The speed at which it should thrust. */ thrust: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#reverse * @param {number} speed - The speed at which it should reverse. */ reverse: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveLeft * @param {number} speed - The speed at which it should move to the left, in pixels per second. */ moveLeft: function (speed) { this.data.velocity[0] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveRight * @param {number} speed - The speed at which it should move to the right, in pixels per second. */ moveRight: function (speed) { this.data.velocity[0] = this.world.pxmi(speed); }, /** * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveUp * @param {number} speed - The speed at which it should move up, in pixels per second. */ moveUp: function (speed) { this.data.velocity[1] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveDown * @param {number} speed - The speed at which it should move down, in pixels per second. */ moveDown: function (speed) { this.data.velocity[1] = this.world.pxmi(speed); }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#preUpdate * @protected */ preUpdate: function () { if (this.removeNextStep) { this.removeFromWorld(); this.removeNextStep = false; } }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#postUpdate * @protected */ postUpdate: function () { this.sprite.x = this.world.mpxi(this.data.position[0]); this.sprite.y = this.world.mpxi(this.data.position[1]); if (!this.fixedRotation) { this.sprite.rotation = this.data.angle; } }, /** * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. * * @method Phaser.Physics.P2.Body#reset * @param {number} x - The new x position of the Body. * @param {number} y - The new x position of the Body. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. */ reset: function (x, y, resetDamping, resetMass) { if (typeof resetDamping === 'undefined') { resetDamping = false; } if (typeof resetMass === 'undefined') { resetMass = false; } this.setZeroForce(); this.setZeroVelocity(); this.setZeroRotation(); if (resetDamping) { this.setZeroDamping(); } if (resetMass) { this.mass = 1; } this.x = x; this.y = y; }, /** * Adds this physics body to the world. * * @method Phaser.Physics.P2.Body#addToWorld */ addToWorld: function () { if (this.game.physics.p2._toRemove) { for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) { if (this.game.physics.p2._toRemove[i] === this) { this.game.physics.p2._toRemove.splice(i, 1); } } } if (this.data.world !== this.game.physics.p2.world) { this.game.physics.p2.addBody(this); } }, /** * Removes this physics body from the world. * * @method Phaser.Physics.P2.Body#removeFromWorld */ removeFromWorld: function () { if (this.data.world === this.game.physics.p2.world) { this.game.physics.p2.removeBodyNextStep(this); } }, /** * Destroys this Body and all references it holds to other objects. * * @method Phaser.Physics.P2.Body#destroy */ destroy: function () { this.removeFromWorld(); this.clearShapes(); this._bodyCallbacks = {}; this._bodyCallbackContext = {}; this._groupCallbacks = {}; this._groupCallbackContext = {}; if (this.debugBody) { this.debugBody.destroy(); } this.debugBody = null; this.sprite = null; }, /** * Removes all Shapes from this Body. * * @method Phaser.Physics.P2.Body#clearShapes */ clearShapes: function () { var i = this.data.shapes.length; while (i--) { this.data.removeShape(this.data.shapes[i]); } this.shapeChanged(); }, /** * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#addShape * @param {p2.Shape} shape - The shape to add to the body. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Shape} The shape that was added to the body. */ addShape: function (shape, offsetX, offsetY, rotation) { if (typeof offsetX === 'undefined') { offsetX = 0; } if (typeof offsetY === 'undefined') { offsetY = 0; } if (typeof rotation === 'undefined') { rotation = 0; } this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); this.shapeChanged(); return shape; }, /** * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Circle} The Circle shape that was added to the Body. */ addCircle: function (radius, offsetX, offsetY, rotation) { var shape = new p2.Circle(this.world.pxm(radius)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addRectangle * @param {number} width - The width of the rectangle in pixels. * @param {number} height - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ addRectangle: function (width, height, offsetX, offsetY, rotation) { var shape = new p2.Rectangle(this.world.pxm(width), this.world.pxm(height)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addPlane * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Plane} The Plane shape that was added to the Body. */ addPlane: function (offsetX, offsetY, rotation) { var shape = new p2.Plane(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addParticle * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Particle} The Particle shape that was added to the Body. */ addParticle: function (offsetX, offsetY, rotation) { var shape = new p2.Particle(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Line shape to this Body. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addLine * @param {number} length - The length of this line (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Line} The Line shape that was added to the Body. */ addLine: function (length, offsetX, offsetY, rotation) { var shape = new p2.Line(this.world.pxm(length)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Capsule shape to this Body. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCapsule * @param {number} length - The distance between the end points in pixels. * @param {number} radius - Radius of the capsule in radians. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Capsule} The Capsule shape that was added to the Body. */ addCapsule: function (length, radius, offsetX, offsetY, rotation) { var shape = new p2.Capsule(this.world.pxm(length), radius); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. * * @method Phaser.Physics.P2.Body#addPolygon * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {boolean} True on success, else false. */ addPolygon: function (options, points) { options = options || {}; if (!Array.isArray(points)) { points = Array.prototype.slice.call(arguments, 1); } var path = []; // Did they pass in a single array of points? if (points.length === 1 && Array.isArray(points[0])) { path = points[0].slice(0); } else if (Array.isArray(points[0])) { path = points[0].slice(0); } else if (typeof points[0] === 'number') { // We've a list of numbers for (var i = 0, len = points.length; i < len; i += 2) { path.push([points[i], points[i + 1]]); } } // top and tail var idx = path.length - 1; if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) { path.pop(); } // Now process them into p2 values for (var p = 0; p < path.length; p++) { path[p][0] = this.world.pxmi(path[p][0]); path[p][1] = this.world.pxmi(path[p][1]); } var result = this.data.fromPolygon(path, options); this.shapeChanged(); return result; }, /** * Remove a shape from the body. Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#removeShape * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. * @return {boolean} True if the shape was found and removed, else false. */ removeShape: function (shape) { var result = this.data.removeShape(shape); this.shapeChanged(); return result; }, /** * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. * * @method Phaser.Physics.P2.Body#setCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. */ setCircle: function (radius, offsetX, offsetY, rotation) { this.clearShapes(); return this.addCircle(radius, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. * * @method Phaser.Physics.P2.Body#setRectangle * @param {number} [width=16] - The width of the rectangle in pixels. * @param {number} [height=16] - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangle: function (width, height, offsetX, offsetY, rotation) { if (typeof width === 'undefined') { width = 16; } if (typeof height === 'undefined') { height = 16; } this.clearShapes(); return this.addRectangle(width, height, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. * If no Sprite is given it defaults to using the parent of this Body. * * @method Phaser.Physics.P2.Body#setRectangleFromSprite * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangleFromSprite: function (sprite) { if (typeof sprite === 'undefined') { sprite = this.sprite; } this.clearShapes(); return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); }, /** * Adds the given Material to all Shapes that belong to this Body. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. * * @method Phaser.Physics.P2.Body#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. */ setMaterial: function (material, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].material = material; } } else { shape.material = material; } }, /** * Updates the debug draw if any body shapes change. * * @method Phaser.Physics.P2.Body#shapeChanged */ shapeChanged: function() { if (this.debugBody) { this.debugBody.draw(); } }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * The shape data format is based on the custom phaser export in. * * @method Phaser.Physics.P2.Body#addPhaserPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. */ addPhaserPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); var createdFixtures = []; // Cycle through the fixtures for (var i = 0; i < data.length; i++) { var fixtureData = data[i]; var shapesOfFixture = this.addFixture(fixtureData); // Always add to a group createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); // if (unique) fixture key is provided if (fixtureData.fixtureKey) { createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; } } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return createdFixtures; }, /** * Add a polygon fixture. This is used during #loadPolygon. * * @method Phaser.Physics.P2.Body#addFixture * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. * @return {array} An array containing the generated shapes for the given polygon. */ addFixture: function (fixtureData) { var generatedShapes = []; if (fixtureData.circle) { var shape = new p2.Circle(this.world.pxm(fixtureData.circle.radius)); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; var offset = p2.vec2.create(); offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); this.data.addShape(shape, offset); generatedShapes.push(shape); } else { var polygons = fixtureData.polygons; var cm = p2.vec2.create(); for (var i = 0; i < polygons.length; i++) { var shapes = polygons[i]; var vertices = []; for (var s = 0; s < shapes.length; s += 2) { vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); } var shape = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== shape.vertices.length; j++) { var v = shape.vertices[j]; p2.vec2.sub(v, v, shape.centerOfMass); } p2.vec2.scale(cm, shape.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); shape.updateTriangles(); shape.updateCenterOfMass(); shape.updateBoundingRadius(); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; this.data.addShape(shape, cm); generatedShapes.push(shape); } } return generatedShapes; }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * * @method Phaser.Physics.P2.Body#loadPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); // We've multiple Convex shapes, they should be CCW automatically var cm = p2.vec2.create(); for (var i = 0; i < data.length; i++) { var vertices = []; for (var s = 0; s < data[i].shape.length; s += 2) { vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]); } var c = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== c.vertices.length; j++) { var v = c.vertices[j]; p2.vec2.sub(v, v, c.centerOfMass); } p2.vec2.scale(cm, c.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); this.data.addShape(c, cm); } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return true; }, /** * DEPRECATED: This method will soon be removed from the API. Please avoid using. * Reads the physics data from a physics data file stored in the Game.Cache. * It will add the shape data to this Body, as well as set the density (mass). * * @method Phaser.Physics.P2.Body#loadData * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadData: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); if (data && data.shape) { this.mass = data.density; return this.loadPolygon(key, object); } } }; Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Phaser.Physics.P2.Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.KINEMATIC = 4; /** * @name Phaser.Physics.P2.Body#static * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.STATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } } }); /** * @name Phaser.Physics.P2.Body#dynamic * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#kinematic * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.KINEMATIC; this.mass = 4; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#allowSleep * @property {boolean} allowSleep - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { get: function () { return this.data.allowSleep; }, set: function (value) { if (value !== this.data.allowSleep) { this.data.allowSleep = value; } } }); /** * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#angle * @property {number} angle - The angle of this Body in degrees. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); }, set: function(value) { this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#angularDamping * @property {number} angularDamping - The angular damping acting acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { get: function () { return this.data.angularDamping; }, set: function (value) { this.data.angularDamping = value; } }); /** * @name Phaser.Physics.P2.Body#angularForce * @property {number} angularForce - The angular force acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { get: function () { return this.data.angularForce; }, set: function (value) { this.data.angularForce = value; } }); /** * @name Phaser.Physics.P2.Body#angularVelocity * @property {number} angularVelocity - The angular velocity of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { get: function () { return this.data.angularVelocity; }, set: function (value) { this.data.angularVelocity = value; } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#damping * @property {number} damping - The linear damping acting on the body in the velocity direction. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { get: function () { return this.data.damping; }, set: function (value) { this.data.damping = value; } }); /** * @name Phaser.Physics.P2.Body#fixedRotation * @property {boolean} fixedRotation - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { get: function () { return this.data.fixedRotation; }, set: function (value) { if (value !== this.data.fixedRotation) { this.data.fixedRotation = value; } } }); /** * @name Phaser.Physics.P2.Body#inertia * @property {number} inertia - The inertia of the body around the Z axis.. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { get: function () { return this.data.inertia; }, set: function (value) { this.data.inertia = value; } }); /** * @name Phaser.Physics.P2.Body#mass * @property {number} mass - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { get: function () { return this.data.mass; }, set: function (value) { if (value !== this.data.mass) { this.data.mass = value; this.data.updateMassProperties(); } } }); /** * @name Phaser.Physics.P2.Body#motionState * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { get: function () { return this.data.motionState; }, set: function (value) { if (value !== this.data.motionState) { this.data.motionState = value; } } }); /** * The angle of the Body in radians. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#rotation * @property {number} rotation - The angle of this Body in radians. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { get: function() { return this.data.angle; }, set: function(value) { this.data.angle = value; } }); /** * @name Phaser.Physics.P2.Body#sleepSpeedLimit * @property {number} sleepSpeedLimit - . */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { get: function () { return this.data.sleepSpeedLimit; }, set: function (value) { this.data.sleepSpeedLimit = value; } }); /** * @name Phaser.Physics.P2.Body#x * @property {number} x - The x coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { get: function () { return this.world.mpxi(this.data.position[0]); }, set: function (value) { this.data.position[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#y * @property {number} y - The y coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { get: function () { return this.world.mpxi(this.data.position[1]); }, set: function (value) { this.data.position[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#id * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. * @readonly */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { get: function () { return this.data.id; } }); /** * @name Phaser.Physics.P2.Body#debug * @property {boolean} debug - Enable or disable debug drawing of this body */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { get: function () { return (this.debugBody !== null); }, set: function (value) { if (value && !this.debugBody) { // This will be added to the global space this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); } else if (!value && this.debugBody) { this.debugBody.destroy(); this.debugBody = null; } } }); /** * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. * * @name Phaser.Physics.P2.Body#collideWorldBounds * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { get: function () { return this._collideWorldBounds; }, set: function (value) { if (value && !this._collideWorldBounds) { this._collideWorldBounds = true; this.updateCollisionMask(); } else if (!value && this._collideWorldBounds) { this._collideWorldBounds = false; this.updateCollisionMask(); } } }); /** * @author George https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Draws a P2 Body to a Graphics instance for visual debugging. * Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. * So use sparingly and rarely (if ever) in production code. * * @class Phaser.Physics.P2.BodyDebug * @classdesc Physics Body Debug Constructor * @constructor * @extends Phaser.Group * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. * @param {object} settings - Settings object. */ Phaser.Physics.P2.BodyDebug = function(game, body, settings) { Phaser.Group.call(this, game); /** * @property {object} defaultSettings - Default debug settings. * @private */ var defaultSettings = { pixelsPerLengthUnit: 20, debugPolygons: false, lineWidth: 1, alpha: 0.5 }; this.settings = Phaser.Utils.extend(defaultSettings, settings); /** * @property {number} ppu - Pixels per Length Unit. */ this.ppu = this.settings.pixelsPerLengthUnit; this.ppu = -1 * this.ppu; /** * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. */ this.body = body; /** * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. */ this.canvas = new Phaser.Graphics(game); this.canvas.alpha = this.settings.alpha; this.add(this.canvas); this.draw(); }; Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, { /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#update */ update: function() { this.updateSpriteTransform(); }, /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform */ updateSpriteTransform: function() { this.position.x = this.body.position[0] * this.ppu; this.position.y = this.body.position[1] * this.ppu; return this.rotation = this.body.angle; }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ draw: function() { var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; obj = this.body; sprite = this.canvas; sprite.clear(); color = parseInt(this.randomPastelHex(), 16); lineColor = 0xff0000; lw = this.lineWidth; if (obj instanceof p2.Body && obj.shapes.length) { var l = obj.shapes.length; i = 0; while (i !== l) { child = obj.shapes[i]; offset = obj.shapeOffsets[i]; angle = obj.shapeAngles[i]; offset = offset || 0; angle = angle || 0; if (child instanceof p2.Circle) { this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); } else if (child instanceof p2.Convex) { verts = []; vrot = p2.vec2.create(); for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j) { v = child.vertices[j]; p2.vec2.rotate(vrot, v, angle); verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]); } this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]); } else if (child instanceof p2.Plane) { this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle); } else if (child instanceof p2.Line) { this.drawLine(sprite, child.length * this.ppu, lineColor, lw); } else if (child instanceof p2.Rectangle) { this.drawRectangle(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); } i++; } } }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); g.drawRect(x - w / 2, y - h / 2, w, h); }, /** * Draws a P2 Circle shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawCircle: function(g, x, y, angle, radius, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, 0x000000, 1); g.beginFill(color, 1.0); g.drawCircle(x, y, -radius); g.endFill(); g.moveTo(x, y); g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); }, /** * Draws a P2 Line shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawLine: function(g, len, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth * 5, color, 1); g.moveTo(-len / 2, 0); g.lineTo(len / 2, 0); }, /** * Draws a P2 Convex shape. * * @method Phaser.Physics.P2.BodyDebug#drawConvex */ drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } if (!debug) { g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); i = 0; while (i !== verts.length) { v = verts[i]; x = v[0]; y = v[1]; if (i === 0) { g.moveTo(x, -y); } else { g.lineTo(x, -y); } i++; } g.endFill(); if (verts.length > 2) { g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]); return g.lineTo(verts[0][0], -verts[0][1]); } } else { colors = [0xff0000, 0x00ff00, 0x0000ff]; i = 0; while (i !== verts.length + 1) { v0 = verts[i % verts.length]; v1 = verts[(i + 1) % verts.length]; x0 = v0[0]; y0 = v0[1]; x1 = v1[0]; y1 = v1[1]; g.lineStyle(lineWidth, colors[i % colors.length], 1); g.moveTo(x0, -y0); g.lineTo(x1, -y1); g.drawCircle(x0, -y0, lineWidth * 2); i++; } g.lineStyle(lineWidth, 0x000000, 1); return g.drawCircle(offset[0], offset[1], lineWidth * 2); } }, /** * Draws a P2 Path. * * @method Phaser.Physics.P2.BodyDebug#drawPath */ drawPath: function(g, path, color, fillColor, lineWidth) { var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); if (typeof fillColor === "number") { g.beginFill(fillColor); } lastx = null; lasty = null; i = 0; while (i < path.length) { v = path[i]; x = v[0]; y = v[1]; if (x !== lastx || y !== lasty) { if (i === 0) { g.moveTo(x, y); } else { p1x = lastx; p1y = lasty; p2x = x; p2y = y; p3x = path[(i + 1) % path.length][0]; p3y = path[(i + 1) % path.length][1]; area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); if (area !== 0) { g.lineTo(x, y); } } lastx = x; lasty = y; } i++; } if (typeof fillColor === "number") { g.endFill(); } if (path.length > 2 && typeof fillColor === "number") { g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); g.lineTo(path[0][0], path[0][1]); } }, /** * Draws a P2 Plane shape. * * @method Phaser.Physics.P2.BodyDebug#drawPlane */ drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { var max, xd, yd; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, lineColor, 11); g.beginFill(color); max = maxLength; g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * this.game.width; yd = x1 + Math.sin(angle) * this.game.height; g.lineTo(xd, -yd); g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * -this.game.width; yd = x1 + Math.sin(angle) * -this.game.height; g.lineTo(xd, -yd); }, /** * Picks a random pastel color. * * @method Phaser.Physics.P2.BodyDebug#randomPastelHex */ randomPastelHex: function() { var blue, green, mix, red; mix = [255, 255, 255]; red = Math.floor(Math.random() * 256); green = Math.floor(Math.random() * 256); blue = Math.floor(Math.random() * 256); red = Math.floor((red + 3 * mix[0]) / 4); green = Math.floor((green + 3 * mix[1]) / 4); blue = Math.floor((blue + 3 * mix[2]) / 4); return this.rgbToHex(red, green, blue); }, /** * Converts from RGB to Hex. * * @method Phaser.Physics.P2.BodyDebug#rgbToHex */ rgbToHex: function(r, g, b) { return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); }, /** * Component to hex conversion. * * @method Phaser.Physics.P2.BodyDebug#componentToHex */ componentToHex: function(c) { var hex; hex = c.toString(16); if (hex.len === 2) { return hex; } else { return hex + '0'; } } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @class Phaser.Physics.P2.Spring * @classdesc Physics Spring Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. */ Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; if (typeof restLength === 'undefined') { restLength = 1; } if (typeof stiffness === 'undefined') { stiffness = 100; } if (typeof damping === 'undefined') { damping = 1; } restLength = world.pxm(restLength); var options = { restLength: restLength, stiffness: stiffness, damping: damping }; if (typeof worldA !== 'undefined' && worldA !== null) { options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ]; } if (typeof worldB !== 'undefined' && worldB !== null) { options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ]; } if (typeof localA !== 'undefined' && localA !== null) { options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ]; } if (typeof localB !== 'undefined' && localB !== null) { options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ]; } p2.Spring.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.Spring.prototype = Object.create(p2.Spring.prototype); Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * \o/ ~ "Because I'm a Material girl" * * @class Phaser.Physics.P2.Material * @classdesc Physics Material Constructor * @constructor */ Phaser.Physics.P2.Material = function (name) { /** * @property {string} name - The user defined name given to this Material. * @default */ this.name = name; p2.Material.call(this); }; Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype); Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Defines a physics material * * @class Phaser.Physics.P2.ContactMaterial * @classdesc Physics ContactMaterial Constructor * @constructor * @param {Phaser.Physics.P2.Material} materialA * @param {Phaser.Physics.P2.Material} materialB * @param {object} [options] */ Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { /** * @property {number} id - The contact material identifier. */ /** * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. */ /** * @property {Phaser.Physics.P2.Material} materialB - First second participating in the contact material. */ /** * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. */ /** * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. */ /** * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. */ p2.ContactMaterial.call(this, materialA, materialB, options); }; Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype); Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Collision Group * * @class Phaser.Physics.P2.CollisionGroup * @classdesc Physics Collision Group Constructor * @constructor */ Phaser.Physics.P2.CollisionGroup = function (bitmask) { /** * @property {number} mask - The CollisionGroup bitmask. */ this.mask = bitmask; }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A constraint that tries to keep the distance between two bodies constant. * * @class Phaser.Physics.P2.DistanceConstraint * @classdesc Physics DistanceConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, maxForce) { if (typeof distance === 'undefined') { distance = 100; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; distance = world.pxm(distance); p2.DistanceConstraint.call(this, bodyA, bodyB, distance, {maxForce: maxForce}); }; Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.GearConstraint * @classdesc Physics GearConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. */ Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { if (typeof angle === 'undefined') { angle = 0; } if (typeof ratio === 'undefined') { ratio = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; var options = { angle: angle, ratio: ratio }; p2.GearConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype); Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Locks the relative position between two bodies. * * @class Phaser.Physics.P2.LockConstraint * @classdesc Physics LockConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { if (typeof offset === 'undefined') { offset = [0, 0]; } if (typeof angle === 'undefined') { angle = 0; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ]; var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce }; p2.LockConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype); Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.PrismaticConstraint * @classdesc Physics PrismaticConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { if (typeof lockRotation === 'undefined') { lockRotation = true; } if (typeof anchorA === 'undefined') { anchorA = [0, 0]; } if (typeof anchorB === 'undefined') { anchorB = [0, 0]; } if (typeof axis === 'undefined') { axis = [0, 0]; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ]; anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ]; var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation }; p2.PrismaticConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype); Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @class Phaser.Physics.P2.RevoluteConstraint * @classdesc Physics RevoluteConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {p2.Body} bodyB - Second connected body. * @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce) { if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; p2.RevoluteConstraint.call(this, bodyA, pivotA, bodyB, pivotB, {maxForce: maxForce}); }; Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
src/js/components/IconContainer.js
ejoreo/portfolio-site
import React, { Component } from 'react'; import Icon from './Icon'; class IconContainer extends Component { render() { return ( <div className="IconContainer"> <span>IconContainer</span> <Icon /> <Icon /> <Icon /> <Icon /> </div> ); } } export default IconContainer;
ajax/libs/forerunnerdb/1.3.505/fdb-legacy.js
holtkamp/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":10,"../lib/Highchart":11,"../lib/OldView":27,"../lib/OldView.Bind":26,"../lib/Overview":30,"../lib/Persist":32,"../lib/View":38}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * 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) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * 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 obj[sortType.key]; 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.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -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 += obj[sortType.key]; } // 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; },{"./Shared":37}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; this._keys = []; 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, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { // Convert the index object to an array of key val objects this.keys(this.extractKeys(index)); } return this.$super.call(this, index); }); BinaryTree.prototype.extractKeys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; 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.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return 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.key]; } return hash;*/ return obj[this._keys[0].key]; }; 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._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) { 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._compareFunc, this._hashFunc); } return true; } if (result === -1) { // 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._compareFunc, this._hashFunc); } return true; } if (result === 1) { // 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._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; 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; }; /*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; };*/ BinaryTree.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(), indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = pathSolver.parseArr(this._index, { verbose: true }); queryArr = pathSolver.parseArr(query, { 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 pathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":31,"./Shared":37}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { 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 }; // 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'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * 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); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } 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) { 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); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * 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.apply(this, arguments); }; 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 || {}; options = this.options(options); 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, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // 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)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], 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 = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } 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 = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } 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) { // 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); } }; /** * 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); }; /** * 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 }; }; /** * 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, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), 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) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), 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(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * 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; 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 pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== 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[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // 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[pm])) { // 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 * @param {String} collectionName The name of the collection. * @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,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":37}],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":37}],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; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ 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":15,"./Overload":29,"./Shared":37}],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":15,"./Overload":29,"./Shared":37}],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":37}],10:[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":35,"./Shared":37,"./View":38}],11:[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":29,"./Shared":37}],12:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map 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 (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); 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('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 = new (btree.create(2, this.sortAsc))(); 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, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; 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) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.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); }; 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":31,"./Shared":37}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; 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":31,"./Shared":37}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * 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":37}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":28,"./Shared":37}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @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() + '"'); } } 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; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * 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) { 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":29,"./Serialiser":36}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":29}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { 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 we have a database object to work from if (!this.db()) { throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!'); } // 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 || {}; result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } 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; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * 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":29}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; // 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":37}],27:[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":37}],28:[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":31,"./Shared":37}],29:[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 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; },{}],30:[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":37}],31:[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; }; Path.prototype.valueOne = 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; 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.valueOne(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 []; } }; /** * 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; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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":37}],32:[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 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":33,"./PersistCrypto":34,"./Shared":37,"async":39,"localforage":75}],33:[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 the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":37,"pako":76}],34:[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 the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":37,"crypto-js":48}],35:[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 || !reactorOut.chainReceive) { 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":37}],36:[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 = {}; // Register our handlers this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(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; },{}],37:[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.505', 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]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @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. */ mixin: new Overload({ '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); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":29}],38:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; 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, false); this.queryOptions(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; } 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 {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } 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 = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * 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,"./ReactorIO":35,"./Shared":37}],39:[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":74}],40:[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":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],41:[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":42}],42:[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; })); },{}],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) { (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":42}],44:[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":42}],45:[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":42,"./hmac":47,"./sha1":66}],46:[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":41,"./core":42}],47:[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":42}],48:[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":40,"./cipher-core":41,"./core":42,"./enc-base64":43,"./enc-utf16":44,"./evpkdf":45,"./format-hex":46,"./hmac":47,"./lib-typedarrays":49,"./md5":50,"./mode-cfb":51,"./mode-ctr":53,"./mode-ctr-gladman":52,"./mode-ecb":54,"./mode-ofb":55,"./pad-ansix923":56,"./pad-iso10126":57,"./pad-iso97971":58,"./pad-nopadding":59,"./pad-zeropadding":60,"./pbkdf2":61,"./rabbit":63,"./rabbit-legacy":62,"./rc4":64,"./ripemd160":65,"./sha1":66,"./sha224":67,"./sha256":68,"./sha3":69,"./sha384":70,"./sha512":71,"./tripledes":72,"./x64-core":73}],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 () { // 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":42}],50:[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":42}],51:[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":41,"./core":42}],52:[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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * 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":41,"./core":42}],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) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":41,"./core":42}],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) { /** * 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":41,"./core":42}],61:[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":42,"./hmac":47,"./sha1":66}],62:[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":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],63:[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":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],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; /** * 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":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],65:[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":42}],66:[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":42}],67:[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":42,"./sha256":68}],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 (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":42}],69:[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":42,"./x64-core":73}],70:[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":42,"./sha512":71,"./x64-core":73}],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 () { // 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":42,"./x64-core":73}],72:[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":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],73:[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":42}],74:[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; }; },{}],75:[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":74}],76:[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":77,"./lib/inflate":78,"./lib/utils/common":79,"./lib/zlib/constants":82}],77:[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":79,"./utils/strings":80,"./zlib/deflate.js":84,"./zlib/messages":89,"./zlib/zstream":91}],78:[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":79,"./utils/strings":80,"./zlib/constants":82,"./zlib/gzheader":85,"./zlib/inflate.js":87,"./zlib/messages":89,"./zlib/zstream":91}],79:[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); },{}],80:[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":79}],81:[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; },{}],82:[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 }; },{}],83:[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; },{}],84:[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":79,"./adler32":81,"./crc32":83,"./messages":89,"./trees":90}],85:[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; },{}],86:[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; }; },{}],87:[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":79,"./adler32":81,"./crc32":83,"./inffast":86,"./inftrees":88}],88:[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":79}],89:[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) */ }; },{}],90:[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":79}],91:[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]);
build/index.js
George-Payne/wikitraveller__district_mapper
/* eslint-disable */ require("source-map-support").install(); /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _stringify = __webpack_require__(1); var _stringify2 = _interopRequireDefault(_stringify); var _fs = __webpack_require__(4); var _fs2 = _interopRequireDefault(_fs); var _operations = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var colors = ['#c9815e', '#67b7b7', '#75bb75', '#bdbd7b', '#8888dc', '#aa6baa']; var _loop = function _loop(i) { (0, _operations.getImageData)('./assets/Berlin_map_new.png', colors[i]).then(function (regions) { console.log(colors[i], regions); _fs2.default.appendFile('test.json', (0, _stringify2.default)({ color: colors[i], regions: regions }, null, 4)); }); }; for (var i = 0; i < colors.length; i++) { _loop(i); } /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(2), __esModule: true }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var core = __webpack_require__(3) , $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify}); module.exports = function stringify(it){ // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }, /* 3 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = require("fs"); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _contiguousRegions = __webpack_require__(6); Object.defineProperty(exports, 'contiguousRegions', { enumerable: true, get: function get() { return _contiguousRegions.contiguousRegions; } }); var _contract = __webpack_require__(7); Object.defineProperty(exports, 'contract', { enumerable: true, get: function get() { return _contract.contract; } }); var _expand = __webpack_require__(8); Object.defineProperty(exports, 'expand', { enumerable: true, get: function get() { return _expand.expand; } }); var _findEdges = __webpack_require__(9); Object.defineProperty(exports, 'findEdges', { enumerable: true, get: function get() { return _findEdges.findEdges; } }); var _getCoords = __webpack_require__(10); Object.defineProperty(exports, 'getCoords', { enumerable: true, get: function get() { return _getCoords.getCoords; } }); var _getImageData = __webpack_require__(75); Object.defineProperty(exports, 'getImageData', { enumerable: true, get: function get() { return _getImageData.getImageData; } }); var _isolateDistrict = __webpack_require__(142); Object.defineProperty(exports, 'isolateDistrict', { enumerable: true, get: function get() { return _isolateDistrict.isolateDistrict; } }); var _match = __webpack_require__(143); Object.defineProperty(exports, 'match', { enumerable: true, get: function get() { return _match.match; } }); var _snipRegion = __webpack_require__(144); Object.defineProperty(exports, 'snipRegion', { enumerable: true, get: function get() { return _snipRegion.snipRegion; } }); var _tryToCombine = __webpack_require__(145); Object.defineProperty(exports, 'tryToCombine', { enumerable: true, get: function get() { return _tryToCombine.tryToCombine; } }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.contiguousRegions = undefined; var _ = __webpack_require__(5); var contiguousRegions = function contiguousRegions(imgData, color) { var regions = [], data = imgData.data, w = imgData.width, temp = data.slice(); for (var i = 0; i < temp.length; i += 4) { var r = temp[i], g = temp[i + 1], b = temp[i + 2]; if (color.r === r && color.g === g && color.b === b) { var cood = { x: i / 4 % w, y: (i / 4 - i / 4 % w) / w }, region = (0, _.snipRegion)([cood.x, cood.y], imgData, temp, color); if (region) { regions.push(region); } } } return regions; }; exports.contiguousRegions = contiguousRegions; /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* eslint-disable one-var-declaration-per-line */ var contract = function contract(imgData, color, amount) { var data = imgData.data, width = imgData.width, w = width * 4; while (amount-- > 0) { var temp = data.slice(); for (var i = 0; i < temp.length; i += 4) { var r = temp[i], g = temp[i + 1], b = temp[i + 2]; if (color.r === r && color.g === g && color.b === b) { var i1 = i - 4, r1 = temp[i1], g1 = temp[i1 + 1], b1 = temp[i1 + 2], i2 = i + 4, r2 = temp[i2], g2 = temp[i2 + 1], b2 = temp[i2 + 2], i3 = i - w, r3 = temp[i3], g3 = temp[i3 + 1], b3 = temp[i3 + 2], i4 = i + w, r4 = temp[i4], g4 = temp[i4 + 1], b4 = temp[i4 + 2]; if (color.r !== r1 || color.g !== g1 || color.b !== b1 || color.r !== r2 || color.g !== g2 || color.b !== b2 || color.r !== r3 || color.g !== g3 || color.b !== b3 || color.r !== r4 || color.g !== g4 || color.b !== b4) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 0; } } } } return imgData; }; exports.contract = contract; /***/ }, /* 8 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var expand = function expand(imgData, color, amount) { var data = imgData.data, width = imgData.width, w = width * 4; while (amount-- > 0) { var temp = data.slice(); for (var i = 0; i < temp.length; i += 4) { var r = temp[i], g = temp[i + 1], b = temp[i + 2], a = temp[i + 3]; if (color.r === r && color.g === g && color.b === b) { var i1 = i - 4, i2 = i + 4, i3 = i - w, i4 = i + w; data[i1] = r;data[i1 + 1] = g;data[i1 + 2] = b;data[i1 + 3] = a; data[i2] = r;data[i2 + 1] = g;data[i2 + 2] = b;data[i2 + 3] = a; data[i3] = r;data[i3 + 1] = g;data[i3 + 2] = b;data[i3 + 3] = a; data[i4] = r;data[i4 + 1] = g;data[i4 + 2] = b;data[i4 + 3] = a; } } } return imgData; }; exports.expand = expand; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* eslint-disable one-var-declaration-per-line */ var findEdges = function findEdges(imgData, color) { var data = imgData.data, width = imgData.width, w = width * 4, temp = data.slice(); for (var i = 0; i < temp.length; i += 4) { var r = temp[i], g = temp[i + 1], b = temp[i + 2]; if (color.r === r && color.g === g && color.b === b) { var i1 = i - 4, r1 = temp[i1], g1 = temp[i1 + 1], b1 = temp[i1 + 2], i2 = i + 4, r2 = temp[i2], g2 = temp[i2 + 1], b2 = temp[i2 + 2], i3 = i - w, r3 = temp[i3], g3 = temp[i3 + 1], b3 = temp[i3 + 2], i4 = i + w, r4 = temp[i4], g4 = temp[i4 + 1], b4 = temp[i4 + 2]; if (color.r === r1 && color.g === g1 && color.b === b1 && color.r === r2 && color.g === g2 && color.b === b2 && color.r === r3 && color.g === g3 && color.b === b3 && color.r === r4 && color.g === g4 && color.b === b4) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 0; } } } return imgData; }; exports.findEdges = findEdges; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCoords = undefined; var _turf = __webpack_require__(11); var _point = __webpack_require__(72); var _point2 = _interopRequireDefault(_point); var _matchColor = __webpack_require__(73); var _matchColor2 = _interopRequireDefault(_matchColor); var _clearColor = __webpack_require__(74); var _clearColor2 = _interopRequireDefault(_clearColor); var _ = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var getCoords = function getCoords(imgData, color) { var data = imgData.data, w = imgData.width, l = w * 4, paths = [], finalCoods = []; var coods = [], findingMore = false, iii = 0, g = 0, cpi = void 0; for (var i = 0; i < data.length; i += 4) { if ((0, _matchColor2.default)(i, data, color)) { findingMore = true; cpi = i; break; } } while (findingMore) { coods[g] = coods[g] || []; coods[g].push((0, _point2.default)(cpi, w)); (0, _clearColor2.default)(cpi, data); var matches = false; matches = (0, _.match)(cpi - l, iii, paths, data, color) || matches; matches = (0, _.match)(cpi + 4, iii, paths, data, color) || matches; matches = (0, _.match)(cpi + l, iii, paths, data, color) || matches; matches = (0, _.match)(cpi - 4, iii, paths, data, color) || matches; matches = (0, _.match)(cpi - l + 4, iii, paths, data, color) || matches; matches = (0, _.match)(cpi + l + 4, iii, paths, data, color) || matches; matches = (0, _.match)(cpi + l - 4, iii, paths, data, color) || matches; matches = (0, _.match)(cpi - l - 4, iii, paths, data, color) || matches; if (!matches) { while (paths.length && !_.match) { var _paths$shift = paths.shift(), pos = _paths$shift.pos; if ((0, _matchColor2.default)(pos, data, color)) { g++; matches = true; cpi = pos; } else { (0, _clearColor2.default)(pos, data); } } } else { cpi = paths.shift().pos; } if (!matches) { findingMore = false; for (var j = 0; j < data.length; j += 4) { if ((0, _matchColor2.default)(j, data, color)) { findingMore = true; g++; cpi = j; break; } } } iii++; } coods = (0, _.tryToCombine)(coods); for (var _i = 0; _i < coods.length; _i++) { if (coods[_i].length > 20) { coods[_i].push(coods[_i][0]); var simp = (0, _turf.simplify)({ type: 'Feature', properties: { fill: color }, geometry: { type: 'Polygon', coordinates: [coods[_i]] } }, 0.5, false); finalCoods.push(simp); } } return (0, _turf.combine)((0, _turf.featureCollection)(finalCoods)); }; exports.getCoords = getCoords; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /*eslint global-require: 0*/ /** * Turf is a modular geospatial analysis engine written in JavaScript. It performs geospatial * processing tasks with GeoJSON data and can be run on a server or in a browser. * * @module turf * @summary Geospatial analysis for JavaScript */ var helpers = __webpack_require__(12); var invariant = __webpack_require__(13); var turf = { isolines: __webpack_require__(14), convex: __webpack_require__(24), within: __webpack_require__(26), concave: __webpack_require__(27), difference: __webpack_require__(30), collect: __webpack_require__(31), flip: __webpack_require__(32), simplify: __webpack_require__(33), bezier: __webpack_require__(35), tag: __webpack_require__(37), sample: __webpack_require__(38), envelope: __webpack_require__(39), square: __webpack_require__(22), circle: __webpack_require__(41), midpoint: __webpack_require__(43), buffer: __webpack_require__(45), center: __webpack_require__(47), centerOfMass: __webpack_require__(48), centroid: __webpack_require__(49), combine: __webpack_require__(51), distance: __webpack_require__(18), explode: __webpack_require__(50), bbox: __webpack_require__(19), tesselate: __webpack_require__(52), bboxPolygon: __webpack_require__(40), inside: __webpack_require__(16), intersect: __webpack_require__(54), nearest: __webpack_require__(55), planepoint: __webpack_require__(21), random: __webpack_require__(56), tin: __webpack_require__(15), union: __webpack_require__(28), bearing: __webpack_require__(44), destination: __webpack_require__(42), kinks: __webpack_require__(58), pointOnSurface: __webpack_require__(59), area: __webpack_require__(60), along: __webpack_require__(63), lineDistance: __webpack_require__(64), lineSlice: __webpack_require__(65), lineSliceAlong: __webpack_require__(67), pointOnLine: __webpack_require__(66), pointGrid: __webpack_require__(17), squareGrid: __webpack_require__(68), triangleGrid: __webpack_require__(69), hexGrid: __webpack_require__(70), idw: __webpack_require__(71), point: helpers.point, polygon: helpers.polygon, lineString: helpers.lineString, multiPoint: helpers.multiPoint, multiPolygon: helpers.multiPolygon, multiLineString: helpers.multiLineString, feature: helpers.feature, featureCollection: helpers.featureCollection, geometryCollection: helpers.geometryCollection, getCoord: invariant.getCoord, geojsonType: invariant.geojsonType, featureOf: invariant.featureOf, collectionOf: invariant.collectionOf }; module.exports = turf; // Allow use of default import syntax in TypeScript module.exports.default = turf; /***/ }, /* 12 */ /***/ function(module, exports) { /** * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}. * * @name feature * @param {Geometry} geometry input geometry * @param {Object} properties properties * @returns {FeatureCollection} a FeatureCollection of input features * @example * var geometry = { * "type": "Point", * "coordinates": [ * 67.5, * 32.84267363195431 * ] * } * * var feature = turf.feature(geometry); * * //=feature */ function feature(geometry, properties) { return { type: 'Feature', properties: properties || {}, geometry: geometry }; } module.exports.feature = feature; /** * Takes coordinates and properties (optional) and returns a new {@link Point} feature. * * @name point * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees) * @param {Object=} properties an Object that is used as the {@link Feature}'s * properties * @returns {Feature<Point>} a Point feature * @example * var pt1 = turf.point([-75.343, 39.984]); * * //=pt1 */ module.exports.point = function (coordinates, properties) { if (!Array.isArray(coordinates)) throw new Error('Coordinates must be an array'); if (coordinates.length < 2) throw new Error('Coordinates must be at least 2 numbers long'); return feature({ type: 'Point', coordinates: coordinates.slice() }, properties); }; /** * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. * * @name polygon * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings * @param {Object=} properties a properties object * @returns {Feature<Polygon>} a Polygon feature * @throws {Error} throw an error if a LinearRing of the polygon has too few positions * or if a LinearRing of the Polygon does not have matching Positions at the * beginning & end. * @example * var polygon = turf.polygon([[ * [-2.275543, 53.464547], * [-2.275543, 53.489271], * [-2.215118, 53.489271], * [-2.215118, 53.464547], * [-2.275543, 53.464547] * ]], { name: 'poly1', population: 400}); * * //=polygon */ module.exports.polygon = function (coordinates, properties) { if (!coordinates) throw new Error('No coordinates passed'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[i]; if (ring.length < 4) { throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.'); } for (var j = 0; j < ring[ring.length - 1].length; j++) { if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return feature({ type: 'Polygon', coordinates: coordinates }, properties); }; /** * Creates a {@link LineString} based on a * coordinate array. Properties can be added optionally. * * @name lineString * @param {Array<Array<number>>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties * @returns {Feature<LineString>} a LineString feature * @throws {Error} if no coordinates are passed * @example * var linestring1 = turf.lineString([ * [-21.964416, 64.148203], * [-21.956176, 64.141316], * [-21.93901, 64.135924], * [-21.927337, 64.136673] * ]); * var linestring2 = turf.lineString([ * [-21.929054, 64.127985], * [-21.912918, 64.134726], * [-21.916007, 64.141016], * [-21.930084, 64.14446] * ], {name: 'line 1', distance: 145}); * * //=linestring1 * * //=linestring2 */ module.exports.lineString = function (coordinates, properties) { if (!coordinates) { throw new Error('No coordinates passed'); } return feature({ type: 'LineString', coordinates: coordinates }, properties); }; /** * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. * * @name featureCollection * @param {Feature[]} features input features * @returns {FeatureCollection} a FeatureCollection of input features * @example * var features = [ * turf.point([-75.343, 39.984], {name: 'Location A'}), * turf.point([-75.833, 39.284], {name: 'Location B'}), * turf.point([-75.534, 39.123], {name: 'Location C'}) * ]; * * var fc = turf.featureCollection(features); * * //=fc */ module.exports.featureCollection = function (features) { return { type: 'FeatureCollection', features: features }; }; /** * Creates a {@link Feature<MultiLineString>} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings * @param {Object=} properties an Object of key-value pairs to add as properties * @returns {Feature<MultiLineString>} a MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine * */ module.exports.multiLineString = function (coordinates, properties) { if (!coordinates) { throw new Error('No coordinates passed'); } return feature({ type: 'MultiLineString', coordinates: coordinates }, properties); }; /** * Creates a {@link Feature<MultiPoint>} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array<Array<number>>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties * @returns {Feature<MultiPoint>} a MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt * */ module.exports.multiPoint = function (coordinates, properties) { if (!coordinates) { throw new Error('No coordinates passed'); } return feature({ type: 'MultiPoint', coordinates: coordinates }, properties); }; /** * Creates a {@link Feature<MultiPolygon>} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons * @param {Object=} properties an Object of key-value pairs to add as properties * @returns {Feature<MultiPolygon>} a multipolygon feature * @throws {Error} if no coordinates are passed * @example * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]); * * //=multiPoly * */ module.exports.multiPolygon = function (coordinates, properties) { if (!coordinates) { throw new Error('No coordinates passed'); } return feature({ type: 'MultiPolygon', coordinates: coordinates }, properties); }; /** * Creates a {@link Feature<GeometryCollection>} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array<{Geometry}>} geometries an array of GeoJSON Geometries * @param {Object=} properties an Object of key-value pairs to add as properties * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ module.exports.geometryCollection = function (geometries, properties) { return feature({ type: 'GeometryCollection', geometries: geometries }, properties); }; var factors = { miles: 3960, nauticalmiles: 3441.145, degrees: 57.2957795, radians: 1, inches: 250905600, yards: 6969600, meters: 6373000, metres: 6373000, kilometers: 6373, kilometres: 6373, feet: 20908792.65 }; /* * Convert a distance measurement from radians to a more friendly unit. * * @name radiansToDistance * @param {number} distance in radians across the sphere * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * inches, yards, metres, meters, kilometres, kilometers. * @returns {number} distance */ module.exports.radiansToDistance = function (radians, units) { var factor = factors[units || 'kilometers']; if (factor === undefined) { throw new Error('Invalid unit'); } return radians * factor; }; /* * Convert a distance measurement from a real-world unit into radians * * @name distanceToRadians * @param {number} distance in real units * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * inches, yards, metres, meters, kilometres, kilometers. * @returns {number} radians */ module.exports.distanceToRadians = function (distance, units) { var factor = factors[units || 'kilometers']; if (factor === undefined) { throw new Error('Invalid unit'); } return distance / factor; }; /* * Convert a distance measurement from a real-world unit into degrees * * @name distanceToRadians * @param {number} distance in real units * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * inches, yards, metres, meters, kilometres, kilometers. * @returns {number} degrees */ module.exports.distanceToDegrees = function (distance, units) { var factor = factors[units || 'kilometers']; if (factor === undefined) { throw new Error('Invalid unit'); } return (distance / factor) * 57.2958; }; /***/ }, /* 13 */ /***/ function(module, exports) { /** * Unwrap a coordinate from a Feature with a Point geometry, a Point * geometry, or a single coordinate. * * @param {*} obj any value * @returns {Array<number>} a coordinate */ function getCoord(obj) { if (Array.isArray(obj) && typeof obj[0] === 'number' && typeof obj[1] === 'number') { return obj; } else if (obj) { if (obj.type === 'Feature' && obj.geometry && obj.geometry.type === 'Point' && Array.isArray(obj.geometry.coordinates)) { return obj.geometry.coordinates; } else if (obj.type === 'Point' && Array.isArray(obj.coordinates)) { return obj.coordinates; } } throw new Error('A coordinate, feature, or point geometry is required'); } /** * Enforce expectations about types of GeoJSON objects for Turf. * * @alias geojsonType * @param {GeoJSON} value any GeoJSON object * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} if value is not the expected type. */ function geojsonType(value, type, name) { if (!type || !name) throw new Error('type and name required'); if (!value || value.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type); } } /** * Enforce expectations about types of {@link Feature} inputs for Turf. * Internally this uses {@link geojsonType} to judge geometry types. * * @alias featureOf * @param {Feature} feature a feature with an expected geometry type * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} error if value is not the expected type. */ function featureOf(feature, type, name) { if (!name) throw new Error('.featureOf() requires a name'); if (!feature || feature.type !== 'Feature' || !feature.geometry) { throw new Error('Invalid input to ' + name + ', Feature with geometry required'); } if (!feature.geometry || feature.geometry.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type); } } /** * Enforce expectations about types of {@link FeatureCollection} inputs for Turf. * Internally this uses {@link geojsonType} to judge geometry types. * * @alias collectionOf * @param {FeatureCollection} featurecollection a featurecollection for which features will be judged * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} if value is not the expected type. */ function collectionOf(featurecollection, type, name) { if (!name) throw new Error('.collectionOf() requires a name'); if (!featurecollection || featurecollection.type !== 'FeatureCollection') { throw new Error('Invalid input to ' + name + ', FeatureCollection required'); } for (var i = 0; i < featurecollection.features.length; i++) { var feature = featurecollection.features[i]; if (!feature || feature.type !== 'Feature' || !feature.geometry) { throw new Error('Invalid input to ' + name + ', Feature with geometry required'); } if (!feature.geometry || feature.geometry.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type); } } } module.exports.geojsonType = geojsonType; module.exports.collectionOf = collectionOf; module.exports.featureOf = featureOf; module.exports.getCoord = getCoord; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { //https://github.com/jasondavies/conrec.js //http://stackoverflow.com/questions/263305/drawing-a-topographical-map var tin = __webpack_require__(15); var inside = __webpack_require__(16); var grid = __webpack_require__(17); var distance = __webpack_require__(18); var bbox = __webpack_require__(19); var planepoint = __webpack_require__(21); var featurecollection = __webpack_require__(12).featureCollection; var linestring = __webpack_require__(12).lineString; var point = __webpack_require__(12).point; var square = __webpack_require__(22); var Conrec = __webpack_require__(23); /** * Takes {@link Point|points} with z-values and an array of * value breaks and generates [isolines](http://en.wikipedia.org/wiki/Isoline). * * @name isolines * @param {FeatureCollection<Point>} points input points * @param {string} z the property name in `points` from which z-values will be pulled * @param {number} resolution resolution of the underlying grid * @param {Array<number>} breaks where to draw contours * @returns {FeatureCollection<LineString>} isolines * @example * // create random points with random * // z-values in their properties * var points = turf.random('point', 100, { * bbox: [0, 30, 20, 50] * }); * for (var i = 0; i < points.features.length; i++) { * points.features[i].properties.z = Math.random() * 10; * } * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; * var isolined = turf.isolines(points, 'z', 15, breaks); * //=isolined */ module.exports = function (points, z, resolution, breaks) { var tinResult = tin(points, z); var bboxBBox = bbox(points); var squareBBox = square(bboxBBox); var sizeCellGrid = distance(point([squareBBox[0], squareBBox[1]]), point([squareBBox[2], squareBBox[1]]), 'kilometers') / resolution; var gridResult = grid(squareBBox, sizeCellGrid, 'kilometers'); var data = []; for (var i = 0; i < gridResult.features.length; i++) { var pt = gridResult.features[i]; for (var j = 0; j < tinResult.features.length; j++) { var triangle = tinResult.features[j]; if (inside(pt, triangle)) { pt.properties = {}; pt.properties[z] = planepoint(pt, triangle); } } } var depth = Math.sqrt(gridResult.features.length); for (var x = 0; x < depth; x++) { var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth); var xFlat = []; for (var g = 0; g < xGroup.length; g++) { if (xGroup[g].properties) { xFlat.push(xGroup[g].properties[z]); } else { xFlat.push(0); } } data.push(xFlat); } var interval = (squareBBox[2] - squareBBox[0]) / depth; var xCoordinates = []; var yCoordinates = []; for (var d = 0; d < depth; d++) { xCoordinates.push(d * interval + squareBBox[0]); yCoordinates.push(d * interval + squareBBox[1]); } var c = new Conrec(); c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks); var contourList = c.contourList(); var fc = featurecollection([]); contourList.forEach(function (c) { if (c.length > 2) { var polyCoordinates = []; c.forEach(function (coord) { polyCoordinates.push([coord.x, coord.y]); }); var poly = linestring(polyCoordinates); poly.properties = {}; poly.properties[z] = c.level; fc.features.push(poly); } }); return fc; }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { //http://en.wikipedia.org/wiki/Delaunay_triangulation //https://github.com/ironwallaby/delaunay var polygon = __webpack_require__(12).polygon; var featurecollection = __webpack_require__(12).featureCollection; /** * Takes a set of {@link Point|points} and the name of a z-value property and * creates a [Triangulated Irregular Network](http://en.wikipedia.org/wiki/Triangulated_irregular_network), * or a TIN for short, returned as a collection of Polygons. These are often used * for developing elevation contour maps or stepped heat visualizations. * * This triangulates the points, as well as adds properties called `a`, `b`, * and `c` representing the value of the given `propertyName` at each of * the points that represent the corners of the triangle. * * @name tin * @param {FeatureCollection<Point>} points input points * @param {String=} z name of the property from which to pull z values * This is optional: if not given, then there will be no extra data added to the derived triangles. * @return {FeatureCollection<Polygon>} TIN output * @example * // generate some random point data * var points = turf.random('points', 30, { * bbox: [50, 30, 70, 50] * }); * //=points * // add a random property to each point between 0 and 9 * for (var i = 0; i < points.features.length; i++) { * points.features[i].properties.z = ~~(Math.random() * 9); * } * var tin = turf.tin(points, 'z') * for (var i = 0; i < tin.features.length; i++) { * var properties = tin.features[i].properties; * // roughly turn the properties of each * // triangle into a fill color * // so we can visualize the result * properties.fill = '#' + properties.a + * properties.b + properties.c; * } * //=tin */ module.exports = function (points, z) { //break down points return featurecollection(triangulate(points.features.map(function (p) { var point = { x: p.geometry.coordinates[0], y: p.geometry.coordinates[1] }; if (z) point.z = p.properties[z]; return point; })).map(function (triangle) { return polygon([[ [triangle.a.x, triangle.a.y], [triangle.b.x, triangle.b.y], [triangle.c.x, triangle.c.y], [triangle.a.x, triangle.a.y] ]], { a: triangle.a.z, b: triangle.b.z, c: triangle.c.z }); })); }; function Triangle(a, b, c) { this.a = a; this.b = b; this.c = c; var A = b.x - a.x, B = b.y - a.y, C = c.x - a.x, D = c.y - a.y, E = A * (a.x + b.x) + B * (a.y + b.y), F = C * (a.x + c.x) + D * (a.y + c.y), G = 2 * (A * (c.y - b.y) - B * (c.x - b.x)), dx, dy; // If the points of the triangle are collinear, then just find the // extremes and use the midpoint as the center of the circumcircle. this.x = (D * E - B * F) / G; this.y = (A * F - C * E) / G; dx = this.x - a.x; dy = this.y - a.y; this.r = dx * dx + dy * dy; } function byX(a, b) { return b.x - a.x; } function dedup(edges) { var j = edges.length, a, b, i, m, n; outer: while (j) { b = edges[--j]; a = edges[--j]; i = j; while (i) { n = edges[--i]; m = edges[--i]; if ((a === m && b === n) || (a === n && b === m)) { edges.splice(j, 2); edges.splice(i, 2); j -= 2; continue outer; } } } } function triangulate(vertices) { // Bail if there aren't enough vertices to form any triangles. if (vertices.length < 3) return []; // Ensure the vertex array is in order of descending X coordinate // (which is needed to ensure a subquadratic runtime), and then find // the bounding box around the points. vertices.sort(byX); var i = vertices.length - 1, xmin = vertices[i].x, xmax = vertices[0].x, ymin = vertices[i].y, ymax = ymin, epsilon = 1e-12; var a, b, c, A, B, G; while (i--) { if (vertices[i].y < ymin) ymin = vertices[i].y; if (vertices[i].y > ymax) ymax = vertices[i].y; } //Find a supertriangle, which is a triangle that surrounds all the //vertices. This is used like something of a sentinel value to remove //cases in the main algorithm, and is removed before we return any // results. // Once found, put it in the "open" list. (The "open" list is for // triangles who may still need to be considered; the "closed" list is // for triangles which do not.) var dx = xmax - xmin, dy = ymax - ymin, dmax = (dx > dy) ? dx : dy, xmid = (xmax + xmin) * 0.5, ymid = (ymax + ymin) * 0.5, open = [ new Triangle({ x: xmid - 20 * dmax, y: ymid - dmax, __sentinel: true }, { x: xmid, y: ymid + 20 * dmax, __sentinel: true }, { x: xmid + 20 * dmax, y: ymid - dmax, __sentinel: true } )], closed = [], edges = [], j; // Incrementally add each vertex to the mesh. i = vertices.length; while (i--) { // For each open triangle, check to see if the current point is // inside it's circumcircle. If it is, remove the triangle and add // it's edges to an edge list. edges.length = 0; j = open.length; while (j--) { // If this point is to the right of this triangle's circumcircle, // then this triangle should never get checked again. Remove it // from the open list, add it to the closed list, and skip. dx = vertices[i].x - open[j].x; if (dx > 0 && dx * dx > open[j].r) { closed.push(open[j]); open.splice(j, 1); continue; } // If not, skip this triangle. dy = vertices[i].y - open[j].y; if (dx * dx + dy * dy > open[j].r) continue; // Remove the triangle and add it's edges to the edge list. edges.push( open[j].a, open[j].b, open[j].b, open[j].c, open[j].c, open[j].a ); open.splice(j, 1); } // Remove any doubled edges. dedup(edges); // Add a new triangle for each edge. j = edges.length; while (j) { b = edges[--j]; a = edges[--j]; c = vertices[i]; // Avoid adding colinear triangles (which have error-prone // circumcircles) A = b.x - a.x; B = b.y - a.y; G = 2 * (A * (c.y - b.y) - B * (c.x - b.x)); if (Math.abs(G) > epsilon) { open.push(new Triangle(a, b, c)); } } } // Copy any remaining open triangles to the closed list, and then // remove any triangles that share a vertex with the supertriangle. Array.prototype.push.apply(closed, open); i = closed.length; while (i--) if (closed[i].a.__sentinel || closed[i].b.__sentinel || closed[i].c.__sentinel) closed.splice(i, 1); return closed; } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var invariant = __webpack_require__(13); // http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule // modified from: https://github.com/substack/point-in-polygon/blob/master/index.js // which was modified from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html /** * Takes a {@link Point} and a {@link Polygon} or {@link MultiPolygon} and determines if the point resides inside the polygon. The polygon can * be convex or concave. The function accounts for holes. * * @name inside * @param {Feature<Point>} point input point * @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon * @return {boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon * @example * var pt = point([-77, 44]); * var poly = polygon([[ * [-81, 41], * [-81, 47], * [-72, 47], * [-72, 41], * [-81, 41] * ]]); * * var isInside = turf.inside(pt, poly); * * //=isInside */ module.exports = function input(point, polygon) { var pt = invariant.getCoord(point); var polys = polygon.geometry.coordinates; // normalize to multipolygon if (polygon.geometry.type === 'Polygon') polys = [polys]; for (var i = 0, insidePoly = false; i < polys.length && !insidePoly; i++) { // check if it is in the outer ring first if (inRing(pt, polys[i][0])) { var inHole = false; var k = 1; // check for the point in any of the holes while (k < polys[i].length && !inHole) { if (inRing(pt, polys[i][k])) { inHole = true; } k++; } if (!inHole) insidePoly = true; } } return insidePoly; }; // pt is [x,y] and ring is [[x,y], [x,y],..] function inRing(pt, ring) { var isInside = false; for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) { var xi = ring[i][0], yi = ring[i][1]; var xj = ring[j][0], yj = ring[j][1]; var intersect = ((yi > pt[1]) !== (yj > pt[1])) && (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi); if (intersect) isInside = !isInside; } return isInside; } /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var point = __webpack_require__(12).point; var featurecollection = __webpack_require__(12).featureCollection; var distance = __webpack_require__(18); /** * Takes a bounding box and a cell depth and returns a set of {@link Point|points} in a grid. * * @name pointGrid * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @param {number} cellSize the distance across each cell * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers * @return {FeatureCollection<Point>} grid of points * @example * var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; * var cellSize = 3; * var units = 'miles'; * * var grid = turf.pointGrid(extent, cellSize, units); * * //=grid */ module.exports = function pointGrid(bbox, cellSize, units) { var fc = featurecollection([]); var xFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[2], bbox[1]]), units)); var cellWidth = xFraction * (bbox[2] - bbox[0]); var yFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[0], bbox[3]]), units)); var cellHeight = yFraction * (bbox[3] - bbox[1]); var currentX = bbox[0]; while (currentX <= bbox[2]) { var currentY = bbox[1]; while (currentY <= bbox[3]) { fc.features.push(point([currentX, currentY])); currentY += cellHeight; } currentX += cellWidth; } return fc; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var getCoord = __webpack_require__(13).getCoord; var radiansToDistance = __webpack_require__(12).radiansToDistance; //http://en.wikipedia.org/wiki/Haversine_formula //http://www.movable-type.co.uk/scripts/latlong.html /** * Calculates the distance between two {@link Point|points} in degrees, radians, * miles, or kilometers. This uses the * [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) * to account for global curvature. * * @name distance * @param {Feature<Point>} from origin point * @param {Feature<Point>} to destination point * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @return {number} distance between the two points * @example * var from = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-75.343, 39.984] * } * }; * var to = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-75.534, 39.123] * } * }; * var units = "miles"; * * var points = { * "type": "FeatureCollection", * "features": [from, to] * }; * * //=points * * var distance = turf.distance(from, to, units); * * //=distance */ module.exports = function (from, to, units) { var degrees2radians = Math.PI / 180; var coordinates1 = getCoord(from); var coordinates2 = getCoord(to); var dLat = degrees2radians * (coordinates2[1] - coordinates1[1]); var dLon = degrees2radians * (coordinates2[0] - coordinates1[0]); var lat1 = degrees2radians * coordinates1[1]; var lat2 = degrees2radians * coordinates2[1]; var a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); return radiansToDistance(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), units); }; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var each = __webpack_require__(20).coordEach; /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @name bbox * @param {(Feature|FeatureCollection)} geojson input features * @return {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @example * var pt1 = point([114.175329, 22.2524]) * var pt2 = point([114.170007, 22.267969]) * var pt3 = point([114.200649, 22.274641]) * var pt4 = point([114.200649, 22.274641]) * var pt5 = point([114.186744, 22.265745]) * var features = featureCollection([pt1, pt2, pt3, pt4, pt5]) * * var bbox = turf.bbox(features); * * var bboxPolygon = turf.bboxPolygon(bbox); * * //=bbox * * //=bboxPolygon */ module.exports = function (geojson) { var bbox = [Infinity, Infinity, -Infinity, -Infinity]; each(geojson, function (coord) { if (bbox[0] > coord[0]) bbox[0] = coord[0]; if (bbox[1] > coord[1]) bbox[1] = coord[1]; if (bbox[2] < coord[0]) bbox[2] = coord[0]; if (bbox[3] < coord[1]) bbox[3] = coord[1]; }); return bbox; }; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Iterate over coordinates in any GeoJSON object, similar to * Array.forEach. * * @name coordEach * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (value) * @param {boolean=} excludeWrapCoord whether or not to include * the final coordinate of LinearRings that wraps the ring in its iteration. * @example * var point = { type: 'Point', coordinates: [0, 0] }; * coordEach(point, function(coords) { * // coords is equal to [0, 0] * }); */ function coordEach(layer, callback, excludeWrapCoord) { var i, j, k, g, l, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, isGeometryCollection, isFeatureCollection = layer.type === 'FeatureCollection', isFeature = layer.type === 'Feature', stop = isFeatureCollection ? layer.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? layer.features[i].geometry : (isFeature ? layer.geometry : layer)); isGeometryCollection = geometryMaybeCollection.type === 'GeometryCollection'; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; coords = geometry.coordinates; wrapShrink = (excludeWrapCoord && (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon')) ? 1 : 0; if (geometry.type === 'Point') { callback(coords); } else if (geometry.type === 'LineString' || geometry.type === 'MultiPoint') { for (j = 0; j < coords.length; j++) callback(coords[j]); } else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') { for (j = 0; j < coords.length; j++) for (k = 0; k < coords[j].length - wrapShrink; k++) callback(coords[j][k]); } else if (geometry.type === 'MultiPolygon') { for (j = 0; j < coords.length; j++) for (k = 0; k < coords[j].length; k++) for (l = 0; l < coords[j][k].length - wrapShrink; l++) callback(coords[j][k][l]); } else if (geometry.type === 'GeometryCollection') { for (j = 0; j < geometry.geometries.length; j++) coordEach(geometry.geometries[j], callback, excludeWrapCoord); } else { throw new Error('Unknown Geometry Type'); } } } } module.exports.coordEach = coordEach; /** * Reduce coordinates in any GeoJSON object into a single value, * similar to how Array.reduce works. However, in this case we lazily run * the reduction, so an array of all coordinates is unnecessary. * * @name coordReduce * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (memo, value) and returns * a new memo * @param {*} memo the starting value of memo: can be any type. * @param {boolean=} excludeWrapCoord whether or not to include * the final coordinate of LinearRings that wraps the ring in its iteration. * @returns {*} combined value */ function coordReduce(layer, callback, memo, excludeWrapCoord) { coordEach(layer, function (coord) { memo = callback(memo, coord); }, excludeWrapCoord); return memo; } module.exports.coordReduce = coordReduce; /** * Iterate over property objects in any GeoJSON object, similar to * Array.forEach. * * @name propEach * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (value) * @example * var point = { type: 'Feature', geometry: null, properties: { foo: 1 } }; * propEach(point, function(props) { * // props is equal to { foo: 1} * }); */ function propEach(layer, callback) { var i; switch (layer.type) { case 'FeatureCollection': for (i = 0; i < layer.features.length; i++) { callback(layer.features[i].properties, i); } break; case 'Feature': callback(layer.properties, 0); break; } } module.exports.propEach = propEach; /** * Reduce properties in any GeoJSON object into a single value, * similar to how Array.reduce works. However, in this case we lazily run * the reduction, so an array of all properties is unnecessary. * * @name propReduce * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (memo, coord) and returns * a new memo * @param {*} memo the starting value of memo: can be any type. * @returns {*} combined value * @example * // an example of an even more advanced function that gives you the * // javascript type of each property of every feature * function propTypes (layer) { * opts = opts || {} * return propReduce(layer, function (prev, props) { * for (var prop in props) { * if (prev[prop]) continue * prev[prop] = typeof props[prop] * } * }, {}) * } */ function propReduce(layer, callback, memo) { propEach(layer, function (prop, i) { memo = callback(memo, prop, i); }); return memo; } module.exports.propReduce = propReduce; /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (value) * @example * var feature = { type: 'Feature', geometry: null, properties: {} }; * featureEach(feature, function(feature) { * // feature == feature * }); */ function featureEach(layer, callback) { if (layer.type === 'Feature') { callback(layer, 0); } else if (layer.type === 'FeatureCollection') { for (var i = 0; i < layer.features.length; i++) { callback(layer.features[i], i); } } } module.exports.featureEach = featureEach; /** * Get all coordinates from any GeoJSON object, returning an array of coordinate * arrays. * * @name coordAll * @param {Object} layer any GeoJSON object * @returns {Array<Array<number>>} coordinate position array */ function coordAll(layer) { var coords = []; coordEach(layer, function (coord) { coords.push(coord); }); return coords; } module.exports.coordAll = coordAll; /** * Iterate over each geometry in any GeoJSON object, similar to * Array.forEach. * * @name geomEach * @param {Object} layer any GeoJSON object * @param {Function} callback a method that takes (value) * @example * var point = { * type: 'Feature', * geometry: { type: 'Point', coordinates: [0, 0] }, * properties: {} * }; * geomEach(point, function(geom) { * // geom is the point geometry * }); */ function geomEach(layer, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, isFeatureCollection = layer.type === 'FeatureCollection', isFeature = layer.type === 'Feature', stop = isFeatureCollection ? layer.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? layer.features[i].geometry : (isFeature ? layer.geometry : layer)); isGeometryCollection = geometryMaybeCollection.type === 'GeometryCollection'; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; if (geometry.type === 'Point' || geometry.type === 'LineString' || geometry.type === 'MultiPoint' || geometry.type === 'Polygon' || geometry.type === 'MultiLineString' || geometry.type === 'MultiPolygon') { callback(geometry); } else if (geometry.type === 'GeometryCollection') { for (j = 0; j < geometry.geometries.length; j++) callback(geometry.geometries[j]); } else { throw new Error('Unknown Geometry Type'); } } } } module.exports.geomEach = geomEach; /***/ }, /* 21 */ /***/ function(module, exports) { /** * Takes a triangular plane as a {@link Polygon} * and a {@link Point} within that triangle and returns the z-value * at that point. The Polygon needs to have properties `a`, `b`, and `c` * that define the values at its three corners. * * @name planepoint * @param {Feature<Point>} point the Point for which a z-value will be calculated * @param {Feature<Polygon>} triangle a Polygon feature with three vertices * @return {number} the z-value for `interpolatedPoint` * @example * var point = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-75.3221, 39.529] * } * }; * var point = turf.point([-75.3221, 39.529]); * // triangle is a polygon with "a", "b", * // and "c" values representing * // the values of the coordinates in order. * var triangle = { * "type": "Feature", * "properties": { * "a": 11, * "b": 122, * "c": 44 * }, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-75.1221, 39.57], * [-75.58, 39.18], * [-75.97, 39.86], * [-75.1221, 39.57] * ]] * } * }; * * var features = { * "type": "FeatureCollection", * "features": [triangle, point] * }; * * var zValue = turf.planepoint(point, triangle); * * //=features * * //=zValue */ module.exports = function (point, triangle) { var x = point.geometry.coordinates[0], y = point.geometry.coordinates[1], x1 = triangle.geometry.coordinates[0][0][0], y1 = triangle.geometry.coordinates[0][0][1], z1 = triangle.properties.a, x2 = triangle.geometry.coordinates[0][1][0], y2 = triangle.geometry.coordinates[0][1][1], z2 = triangle.properties.b, x3 = triangle.geometry.coordinates[0][2][0], y3 = triangle.geometry.coordinates[0][2][1], z3 = triangle.properties.c; var z = (z3 * (x - x1) * (y - y2) + z1 * (x - x2) * (y - y3) + z2 * (x - x3) * (y - y1) - z2 * (x - x1) * (y - y3) - z3 * (x - x2) * (y - y1) - z1 * (x - x3) * (y - y2)) / ((x - x1) * (y - y2) + (x - x2) * (y - y3) + (x - x3) * (y - y1) - (x - x1) * (y - y3) - (x - x2) * (y - y1) - (x - x3) * (y - y2)); return z; }; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var distance = __webpack_require__(18); /** * Takes a bounding box and calculates the minimum square bounding box that * would contain the input. * * @name square * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @return {Array<number>} a square surrounding `bbox` * @example * var bbox = [-20,-20,-15,0]; * * var squared = turf.square(bbox); * * var features = { * "type": "FeatureCollection", * "features": [ * turf.bboxPolygon(bbox), * turf.bboxPolygon(squared) * ] * }; * * //=features */ module.exports = function (bbox) { var horizontalDistance = distance(bbox.slice(0, 2), [bbox[2], bbox[1]], 'miles'); var verticalDistance = distance(bbox.slice(0, 2), [bbox[0], bbox[3]], 'miles'); if (horizontalDistance >= verticalDistance) { var verticalMidpoint = (bbox[1] + bbox[3]) / 2; return [ bbox[0], verticalMidpoint - ((bbox[2] - bbox[0]) / 2), bbox[2], verticalMidpoint + ((bbox[2] - bbox[0]) / 2) ]; } else { var horizontalMidpoint = (bbox[0] + bbox[2]) / 2; return [ horizontalMidpoint - ((bbox[3] - bbox[1]) / 2), bbox[1], horizontalMidpoint + ((bbox[3] - bbox[1]) / 2), bbox[3] ]; } }; /***/ }, /* 23 */ /***/ function(module, exports) { /* eslint-disable */ /* * Copyright (c) 2010, Jason Davies. * * All rights reserved. This code is based on Bradley White's Java version, * which is in turn based on Nicholas Yue's C++ version, which in turn is based * on Paul D. Bourke's original Fortran version. See below for the respective * copyright notices. * * See http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/ for the original * paper by Paul D. Bourke. * * The vector conversion code is based on http://apptree.net/conrec.htm by * Graham Cox. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1996-1997 Nicholas Yue * * This software is copyrighted by Nicholas Yue. This code is based on Paul D. * Bourke's CONREC.F routine. * * The authors hereby grant permission to use, copy, and distribute this * software and its documentation for any purpose, provided that existing * copyright notices are retained in all copies and that this notice is * included verbatim in any distributions. Additionally, the authors grant * permission to modify this software and its documentation for any purpose, * provided that such modifications are not distributed without the explicit * consent of the authors and that existing copyright notices are retained in * all copies. Some of the algorithms implemented by this software are * patented, observe all applicable patent law. * * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, * EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS * PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR * MODIFICATIONS. */ module.exports = Conrec; var EPSILON = 1e-10; function pointsEqual(a, b) { var x = a.x - b.x, y = a.y - b.y; return x * x + y * y < EPSILON; } function reverseList(list) { var pp = list.head; while (pp) { // swap prev/next pointers var temp = pp.next; pp.next = pp.prev; pp.prev = temp; // continue through the list pp = temp; } // swap head/tail pointers var temp = list.head; list.head = list.tail; list.tail = temp; } function ContourBuilder(level) { this.level = level; this.s = null; this.count = 0; } ContourBuilder.prototype.remove_seq = function (list) { // if list is the first item, static ptr s is updated if (list.prev) { list.prev.next = list.next; } else { this.s = list.next; } if (list.next) { list.next.prev = list.prev; } --this.count; }; ContourBuilder.prototype.addSegment = function (a, b) { var ss = this.s; var ma = null; var mb = null; var prependA = false; var prependB = false; while (ss) { if (ma == null) { // no match for a yet if (pointsEqual(a, ss.head.p)) { ma = ss; prependA = true; } else if (pointsEqual(a, ss.tail.p)) { ma = ss; } } if (mb == null) { // no match for b yet if (pointsEqual(b, ss.head.p)) { mb = ss; prependB = true; } else if (pointsEqual(b, ss.tail.p)) { mb = ss; } } // if we matched both no need to continue searching if (mb != null && ma != null) { break; } else { ss = ss.next; } } // c is the case selector based on which of ma and/or mb are set var c = ((ma != null) ? 1 : 0) | ((mb != null) ? 2 : 0); switch (c) { case 0: // both unmatched, add as new sequence var aa = {p: a, prev: null}; var bb = {p: b, next: null}; aa.next = bb; bb.prev = aa; // create sequence element and push onto head of main list. The order // of items in this list is unimportant ma = {head: aa, tail: bb, next: this.s, prev: null, closed: false}; if (this.s) { this.s.prev = ma; } this.s = ma; ++this.count; // not essential - tracks number of unmerged sequences break; case 1: // a matched, b did not - thus b extends sequence ma var pp = {p: b}; if (prependA) { pp.next = ma.head; pp.prev = null; ma.head.prev = pp; ma.head = pp; } else { pp.next = null; pp.prev = ma.tail; ma.tail.next = pp; ma.tail = pp; } break; case 2: // b matched, a did not - thus a extends sequence mb var pp = {p: a}; if (prependB) { pp.next = mb.head; pp.prev = null; mb.head.prev = pp; mb.head = pp; } else { pp.next = null; pp.prev = mb.tail; mb.tail.next = pp; mb.tail = pp; } break; case 3: // both matched, can merge sequences // if the sequences are the same, do nothing, as we are simply closing this path (could set a flag) if (ma === mb) { var pp = {p: ma.tail.p, next: ma.head, prev: null}; ma.head.prev = pp; ma.head = pp; ma.closed = true; break; } // there are 4 ways the sequence pair can be joined. The current setting of prependA and // prependB will tell us which type of join is needed. For head/head and tail/tail joins // one sequence needs to be reversed switch ((prependA ? 1 : 0) | (prependB ? 2 : 0)) { case 0: // tail-tail // reverse ma and append to mb reverseList(ma); // fall through to head/tail case case 1: // head-tail // ma is appended to mb and ma discarded mb.tail.next = ma.head; ma.head.prev = mb.tail; mb.tail = ma.tail; //discard ma sequence record this.remove_seq(ma); break; case 3: // head-head // reverse ma and append mb to it reverseList(ma); // fall through to tail/head case case 2: // tail-head // mb is appended to ma and mb is discarded ma.tail.next = mb.head; mb.head.prev = ma.tail; ma.tail = mb.tail; //discard mb sequence record this.remove_seq(mb); break; } } }; /* * Implements CONREC. * * @private * @param {function} drawContour function for drawing contour. Defaults to a * custom "contour builder", which populates the * contours property. */ function Conrec(drawContour) { if (!drawContour) { var c = this; c.contours = {}; /** * drawContour - interface for implementing the user supplied method to * render the countours. * * Draws a line between the start and end coordinates. * * @private * @param startX - start coordinate for X * @param startY - start coordinate for Y * @param endX - end coordinate for X * @param endY - end coordinate for Y * @param contourLevel - Contour level for line. */ this.drawContour = function (startX, startY, endX, endY, contourLevel, k) { var cb = c.contours[k]; if (!cb) { cb = c.contours[k] = new ContourBuilder(contourLevel); } cb.addSegment({x: startX, y: startY}, {x: endX, y: endY}); }; this.contourList = function () { var l = []; var a = c.contours; for (var k in a) { var s = a[k].s; var level = a[k].level; while (s) { var h = s.head; var l2 = []; l2.level = level; l2.k = k; while (h && h.p) { l2.push(h.p); h = h.next; } l.push(l2); s = s.next; } } l.sort(function (a, b) { return a.k - b.k; }); return l; }; } else { this.drawContour = drawContour; } this.h = new Array(5); this.sh = new Array(5); this.xh = new Array(5); this.yh = new Array(5); } /* * contour is a contouring subroutine for rectangularily spaced data * * It emits calls to a line drawing subroutine supplied by the user which * draws a contour map corresponding to real*4data on a randomly spaced * rectangular grid. The coordinates emitted are in the same units given in * the x() and y() arrays. * * Any number of contour levels may be specified but they must be in order of * increasing value. * * * @param {number[][]} d - matrix of data to contour * @param {number} ilb,iub,jlb,jub - index bounds of data matrix * * The following two, one dimensional arrays (x and y) contain * the horizontal and vertical coordinates of each sample points. * @param {number[]} x - data matrix column coordinates * @param {number[]} y - data matrix row coordinates * @param {number} nc - number of contour levels * @param {number[]} z - contour levels in increasing order. */ Conrec.prototype.contour = function (d, ilb, iub, jlb, jub, x, y, nc, z) { var h = this.h, sh = this.sh, xh = this.xh, yh = this.yh; var drawContour = this.drawContour; this.contours = {}; var xsect = function (p1, p2) { return (h[p2] * xh[p1] - h[p1] * xh[p2]) / (h[p2] - h[p1]); }; var ysect = function (p1, p2) { return (h[p2] * yh[p1] - h[p1] * yh[p2]) / (h[p2] - h[p1]); }; var m1; var m2; var m3; var case_value; var dmin; var dmax; var x1 = 0.0; var x2 = 0.0; var y1 = 0.0; var y2 = 0.0; // The indexing of im and jm should be noted as it has to start from zero // unlike the fortran counter part var im = [0, 1, 1, 0]; var jm = [0, 0, 1, 1]; // Note that castab is arranged differently from the FORTRAN code because // Fortran and C/C++ arrays are transposed of each other, in this case // it is more tricky as castab is in 3 dimensions var castab = [ [ [0, 0, 8], [0, 2, 5], [7, 6, 9] ], [ [0, 3, 4], [1, 3, 1], [4, 3, 0] ], [ [9, 6, 7], [5, 2, 0], [8, 0, 0] ] ]; for (var j = (jub - 1); j >= jlb; j--) { for (var i = ilb; i <= iub - 1; i++) { var temp1, temp2; temp1 = Math.min(d[i][j], d[i][j + 1]); temp2 = Math.min(d[i + 1][j], d[i + 1][j + 1]); dmin = Math.min(temp1, temp2); temp1 = Math.max(d[i][j], d[i][j + 1]); temp2 = Math.max(d[i + 1][j], d[i + 1][j + 1]); dmax = Math.max(temp1, temp2); if (dmax >= z[0] && dmin <= z[nc - 1]) { for (var k = 0; k < nc; k++) { if (z[k] >= dmin && z[k] <= dmax) { for (var m = 4; m >= 0; m--) { if (m > 0) { // The indexing of im and jm should be noted as it has to // start from zero h[m] = d[i + im[m - 1]][j + jm[m - 1]] - z[k]; xh[m] = x[i + im[m - 1]]; yh[m] = y[j + jm[m - 1]]; } else { h[0] = 0.25 * (h[1] + h[2] + h[3] + h[4]); xh[0] = 0.5 * (x[i] + x[i + 1]); yh[0] = 0.5 * (y[j] + y[j + 1]); } if (h[m] > EPSILON) { sh[m] = 1; } else if (h[m] < -EPSILON) { sh[m] = -1; } else sh[m] = 0; } // // Note: at this stage the relative heights of the corners and the // centre are in the h array, and the corresponding coordinates are // in the xh and yh arrays. The centre of the box is indexed by 0 // and the 4 corners by 1 to 4 as shown below. // Each triangle is then indexed by the parameter m, and the 3 // vertices of each triangle are indexed by parameters m1,m2,and // m3. // It is assumed that the centre of the box is always vertex 2 // though this isimportant only when all 3 vertices lie exactly on // the same contour level, in which case only the side of the box // is drawn. // // // vertex 4 +-------------------+ vertex 3 // | \ / | // | \ m-3 / | // | \ / | // | \ / | // | m=2 X m=2 | the centre is vertex 0 // | / \ | // | / \ | // | / m=1 \ | // | / \ | // vertex 1 +-------------------+ vertex 2 // // // // Scan each triangle in the box // for (m = 1; m <= 4; m++) { m1 = m; m2 = 0; if (m != 4) { m3 = m + 1; } else { m3 = 1; } case_value = castab[sh[m1] + 1][sh[m2] + 1][sh[m3] + 1]; if (case_value != 0) { switch (case_value) { case 1: // Line between vertices 1 and 2 x1 = xh[m1]; y1 = yh[m1]; x2 = xh[m2]; y2 = yh[m2]; break; case 2: // Line between vertices 2 and 3 x1 = xh[m2]; y1 = yh[m2]; x2 = xh[m3]; y2 = yh[m3]; break; case 3: // Line between vertices 3 and 1 x1 = xh[m3]; y1 = yh[m3]; x2 = xh[m1]; y2 = yh[m1]; break; case 4: // Line between vertex 1 and side 2-3 x1 = xh[m1]; y1 = yh[m1]; x2 = xsect(m2, m3); y2 = ysect(m2, m3); break; case 5: // Line between vertex 2 and side 3-1 x1 = xh[m2]; y1 = yh[m2]; x2 = xsect(m3, m1); y2 = ysect(m3, m1); break; case 6: // Line between vertex 3 and side 1-2 x1 = xh[m3]; y1 = yh[m3]; x2 = xsect(m1, m2); y2 = ysect(m1, m2); break; case 7: // Line between sides 1-2 and 2-3 x1 = xsect(m1, m2); y1 = ysect(m1, m2); x2 = xsect(m2, m3); y2 = ysect(m2, m3); break; case 8: // Line between sides 2-3 and 3-1 x1 = xsect(m2, m3); y1 = ysect(m2, m3); x2 = xsect(m3, m1); y2 = ysect(m3, m1); break; case 9: // Line between sides 3-1 and 1-2 x1 = xsect(m3, m1); y1 = ysect(m3, m1); x2 = xsect(m1, m2); y2 = ysect(m1, m2); break; default: break; } // Put your processing code here and comment out the printf //printf("%f %f %f %f %f\n",x1,y1,x2,y2,z[k]); drawContour(x1, y1, x2, y2, z[k], k); } } } } } } } }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var each = __webpack_require__(20).coordEach, convexHull = __webpack_require__(25), polygon = __webpack_require__(12).polygon; /** * Takes a [feature](http://geojson.org/geojson-spec.html#feature-objects) * or a [featureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects) * and returns a [convex hull](http://en.wikipedia.org/wiki/Convex_hull) polygon. * * Internally this uses * the [convex-hull](https://github.com/mikolalysenko/convex-hull) module that * implements a [monotone chain hull](http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain). * * @name convex * @param {(Feature|FeatureCollection)} feature input Feature or FeatureCollection * @returns {Feature<Polygon>} a convex hull * @example * var points = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.195312, 43.755225] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.404052, 43.8424511] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.579833, 43.659924] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.360107, 43.516688] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.14038, 43.588348] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [10.195312, 43.755225] * } * } * ] * }; * * var hull = turf.convex(points); * * var resultFeatures = points.features.concat(hull); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ module.exports = function (feature) { var points = []; // Remove Z in coordinates because it breaks the convexHull algorithm each(feature, function (coord) { points.push([coord[0], coord[1]]); }); var hull = convexHull(points); // Hull should have at least 3 different vertices in order to create a valid polygon if (hull.length >= 3) { var ring = []; for (var i = 0; i < hull.length; i++) { ring.push(points[hull[i][0]]); } ring.push(points[hull[hull.length - 1][1]]); return polygon([ring]); } return undefined; }; /***/ }, /* 25 */ /***/ function(module, exports) { module.exports = require("convex-hull"); /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var inside = __webpack_require__(16); var featureCollection = __webpack_require__(12).featureCollection; /** * Takes a set of {@link Point|points} and a set of {@link Polygon|polygons} and returns the points that fall within the polygons. * * @name within * @param {FeatureCollection<Point>} points input points * @param {FeatureCollection<Polygon>} polygons input polygons * @return {FeatureCollection<Point>} points that land within at least one polygon * @example * var searchWithin = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-46.653,-23.543], * [-46.634,-23.5346], * [-46.613,-23.543], * [-46.614,-23.559], * [-46.631,-23.567], * [-46.653,-23.560], * [-46.653,-23.543] * ]] * } * } * ] * }; * var points = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-46.6318, -23.5523] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-46.6246, -23.5325] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-46.6062, -23.5513] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-46.663, -23.554] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-46.643, -23.557] * } * } * ] * }; * * var ptsWithin = turf.within(points, searchWithin); * * //=points * * //=searchWithin * * //=ptsWithin */ module.exports = function (points, polygons) { var pointsWithin = featureCollection([]); for (var i = 0; i < polygons.features.length; i++) { for (var j = 0; j < points.features.length; j++) { var isInside = inside(points.features[j], polygons.features[i]); if (isInside) { pointsWithin.features.push(points.features[j]); } } } return pointsWithin; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // 1. run tin on points // 2. calculate lenth of all edges and area of all triangles // 3. remove triangles that fail the max length test // 4. buffer the results slightly // 5. merge the results var tin = __webpack_require__(15); var union = __webpack_require__(28); var distance = __webpack_require__(18); /** * Takes a set of {@link Point|points} and returns a concave hull polygon. * * Internally, this uses [turf-tin](https://github.com/Turfjs/turf-tin) to generate geometries. * * @param {FeatureCollection<Point>} points input points * @param {number} maxEdge the size of an edge necessary for part of the * hull to become concave (in miles) * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @returns {Feature<Polygon>} a concave hull * @throws {Error} if maxEdge parameter is missing * @example * var points = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.601226, 44.642643] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.591442, 44.651436] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.580799, 44.648749] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.573589, 44.641788] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.587665, 44.64533] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-63.595218, 44.64765] * } * } * ] * }; * * var hull = turf.concave(points, 1, 'miles'); * * var resultFeatures = points.features.concat(hull); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ function concave(points, maxEdge, units) { if (typeof maxEdge !== 'number') throw new Error('maxEdge parameter is required'); var tinPolys = tin(points); var filteredPolys = tinPolys.features.filter(filterTriangles); tinPolys.features = filteredPolys; function filterTriangles(triangle) { var pt1 = triangle.geometry.coordinates[0][0]; var pt2 = triangle.geometry.coordinates[0][1]; var pt3 = triangle.geometry.coordinates[0][2]; var dist1 = distance(pt1, pt2, units); var dist2 = distance(pt2, pt3, units); var dist3 = distance(pt1, pt3, units); return (dist1 <= maxEdge && dist2 <= maxEdge && dist3 <= maxEdge); } return merge(tinPolys); } function merge(polygons) { var merged = JSON.parse(JSON.stringify(polygons.features[0])), features = polygons.features; for (var i = 0, len = features.length; i < len; i++) { var poly = features[i]; if (poly.geometry) { merged = union(merged, poly); } } return merged; } module.exports = concave; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // look here for help http://svn.osgeo.org/grass/grass/branches/releasebranch_6_4/vector/v.overlay/main.c //must be array of polygons // depend on jsts for now https://github.com/bjornharrtell/jsts/blob/master/examples/overlay.html var jsts = __webpack_require__(29); /** * Takes two or more {@link Polygon|polygons} and returns a combined polygon. If the input polygons are not contiguous, this function returns a {@link MultiPolygon} feature. * * @name union * @param {...Feature<Polygon>} A polygon to combine * @return {Feature<(Polygon|MultiPolygon)>} a combined {@link Polygon} or {@link MultiPolygon} feature * @example * var poly1 = { * "type": "Feature", * "properties": { * "fill": "#0f0" * }, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-82.574787, 35.594087], * [-82.574787, 35.615581], * [-82.545261, 35.615581], * [-82.545261, 35.594087], * [-82.574787, 35.594087] * ]] * } * }; * var poly2 = { * "type": "Feature", * "properties": { * "fill": "#00f" * }, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-82.560024, 35.585153], * [-82.560024, 35.602602], * [-82.52964, 35.602602], * [-82.52964, 35.585153], * [-82.560024, 35.585153] * ]] * } * }; * var polygons = { * "type": "FeatureCollection", * "features": [poly1, poly2] * }; * * var union = turf.union(poly1, poly2); * * //=polygons * * //=union */ module.exports = function () { var reader = new jsts.io.GeoJSONReader(); var result = reader.read(JSON.stringify(arguments[0].geometry)); for (var i = 1; i < arguments.length; i++) { result = result.union(reader.read(JSON.stringify(arguments[i].geometry))); } var writer = new jsts.io.GeoJSONWriter(); result = writer.write(result); return { type: 'Feature', geometry: result, properties: arguments[0].properties }; }; /***/ }, /* 29 */ /***/ function(module, exports) { module.exports = require("jsts"); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { // depend on jsts for now https://github.com/bjornharrtell/jsts/blob/master/examples/overlay.html var jsts = __webpack_require__(29); /** * Finds the difference between two {@link Polygon|polygons} by clipping the second * polygon from the first. * * @name difference * @param {Feature<Polygon>} p1 input Polygon feature * @param {Feature<Polygon>} p2 Polygon feature to difference from `p1` * @return {Feature<Polygon>} a Polygon feature showing the area of `p1` excluding the area of `p2` * @example * var poly1 = { * "type": "Feature", * "properties": { * "fill": "#0f0" * }, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-46.738586, -23.596711], * [-46.738586, -23.458207], * [-46.560058, -23.458207], * [-46.560058, -23.596711], * [-46.738586, -23.596711] * ]] * } * }; * var poly2 = { * "type": "Feature", * "properties": { * "fill": "#00f" * }, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-46.650009, -23.631314], * [-46.650009, -23.5237], * [-46.509246, -23.5237], * [-46.509246, -23.631314], * [-46.650009, -23.631314] * ]] * } * }; * * var differenced = turf.difference(poly1, poly2); * differenced.properties.fill = '#f00'; * * var polygons = { * "type": "FeatureCollection", * "features": [poly1, poly2] * }; * * //=polygons * * //=differenced */ module.exports = function (p1, p2) { var poly1 = JSON.parse(JSON.stringify(p1)); var poly2 = JSON.parse(JSON.stringify(p2)); if (poly1.type !== 'Feature') { poly1 = { type: 'Feature', properties: {}, geometry: poly1 }; } if (poly2.type !== 'Feature') { poly2 = { type: 'Feature', properties: {}, geometry: poly2 }; } var reader = new jsts.io.GeoJSONReader(); var a = reader.read(JSON.stringify(poly1.geometry)); var b = reader.read(JSON.stringify(poly2.geometry)); var differenced = a.difference(b); if (differenced.isEmpty()) return undefined; var writer = new jsts.io.GeoJSONWriter(); var geojsonGeometry = writer.write(differenced); poly1.geometry = differenced; return { type: 'Feature', properties: poly1.properties, geometry: geojsonGeometry }; }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var inside = __webpack_require__(16); /** * Merges a specified property from a FeatureCollection of points into a * FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` * for polygons, this finds every point that lies within each polygon, collects the * `inProperty` values from those points, and adds them as an array to `outProperty` * on the polygon. * * @name collect * @param {FeatureCollection<Polygon>} polygons polygons with values on which to aggregate * @param {FeatureCollection<Point>} points points to be aggregated * @param {string} inProperty property to be nested from * @param {string} outProperty property to be nested into * @return {FeatureCollection<Polygon>} polygons with properties listed based on `outField` * @example * var poly1 = turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]); * var poly2 = turf.polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]); * var polyFC = turf.featureCollection([poly1, poly2]); * var pt1 = turf.point([5,5], {population: 200}); * var pt2 = turf.point([1,3], {population: 600}); * var pt3 = turf.point([14,2], {population: 100}); * var pt4 = turf.point([13,1], {population: 200}); * var pt5 = turf.point([19,7], {population: 300}); * var ptFC = turf.featureCollection([pt1, pt2, pt3, pt4, pt5]); * var collected = turf.collect(polyFC, ptFC, 'population', 'values'); * * collected.features[0].properties.values // => [200, 600]); */ module.exports = function collect(polygons, points, inProperty, outProperty) { polygons.features.forEach(function (poly) { var values = points.features.filter(function (pt) { return inside(pt, poly); }).map(function (pt) { return pt.properties[inProperty]; }); if (!poly.properties) { poly.properties = {}; } poly.properties[outProperty] = values; }); return polygons; }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var coordEach = __webpack_require__(20).coordEach; /** * Takes input features and flips all of their coordinates * from `[x, y]` to `[y, x]`. * * @name flip * @param {(Feature|FeatureCollection)} input input features * @returns {(Feature|FeatureCollection)} a feature or set of features of the same type as `input` with flipped coordinates * @example * var serbia = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [20.566406, 43.421008] * } * }; * * //=serbia * * var saudiArabia = turf.flip(serbia); * * //=saudiArabia */ module.exports = function flip(input) { // ensure that we don't modify features in-place and changes to the // output do not change the previous feature, including changes to nested // properties. input = JSON.parse(JSON.stringify(input)); coordEach(input, function (coord) { coord.reverse(); }); return input; }; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var simplify = __webpack_require__(34); // supported GeoJSON geometries, used to check whether to wrap in simpleFeature() var supportedTypes = ['LineString', 'MultiLineString', 'Polygon', 'MultiPolygon']; /** * Takes a {@link LineString} or {@link Polygon} and returns a simplified version. Internally uses [simplify-js](http://mourner.github.io/simplify-js/) to perform simplification. * * @name simplify * @param {Feature<(LineString|Polygon|MultiLineString|MultiPolygon)>|FeatureCollection|GeometryCollection} feature feature to be simplified * @param {number} [tolerance=1] simplification tolerance * @param {boolean} [highQuality=false] whether or not to spend more time to create * a higher-quality simplification with a different algorithm * @return {Feature<(LineString|Polygon|MultiLineString|MultiPolygon)>|FeatureCollection|GeometryCollection} a simplified feature * @example * var feature = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-70.603637, -33.399918], * [-70.614624, -33.395332], * [-70.639343, -33.392466], * [-70.659942, -33.394759], * [-70.683975, -33.404504], * [-70.697021, -33.419406], * [-70.701141, -33.434306], * [-70.700454, -33.446339], * [-70.694274, -33.458369], * [-70.682601, -33.465816], * [-70.668869, -33.472117], * [-70.646209, -33.473835], * [-70.624923, -33.472117], * [-70.609817, -33.468107], * [-70.595397, -33.458369], * [-70.587158, -33.442901], * [-70.587158, -33.426283], * [-70.590591, -33.414248], * [-70.594711, -33.406224], * [-70.603637, -33.399918] * ]] * } * }; * var tolerance = 0.01; * * var simplified = turf.simplify( * feature, tolerance, false); * * //=feature * * //=simplified */ module.exports = function (feature, tolerance, highQuality) { if (feature.type === 'Feature') { return simpleFeature( simplifyHelper(feature, tolerance, highQuality), feature.properties); } else if (feature.type === 'FeatureCollection') { return { type: 'FeatureCollection', features: feature.features.map(function (f) { var simplified = simplifyHelper(f, tolerance, highQuality); // we create simpleFeature here because it doesn't apply to GeometryCollection // so we can't create it at simplifyHelper() if (supportedTypes.indexOf(simplified.type) > -1) { return simpleFeature(simplified, f.properties); } else { return simplified; } }) }; } else if (feature.type === 'GeometryCollection') { return { type: 'GeometryCollection', geometries: feature.geometries.map(function (g) { if (supportedTypes.indexOf(g.type) > -1) { return simplifyHelper({ type: 'Feature', geometry: g }, tolerance, highQuality); } return g; }) }; } else { return feature; } }; function simplifyHelper(feature, tolerance, highQuality) { if (feature.geometry.type === 'LineString') { return { type: 'LineString', coordinates: simplifyLine(feature.geometry.coordinates, tolerance, highQuality) }; } else if (feature.geometry.type === 'MultiLineString') { return { type: 'MultiLineString', coordinates: feature.geometry.coordinates.map(function (lines) { return simplifyLine(lines, tolerance, highQuality); }) }; } else if (feature.geometry.type === 'Polygon') { return { type: 'Polygon', coordinates: simplifyPolygon(feature.geometry.coordinates, tolerance, highQuality) }; } else if (feature.geometry.type === 'MultiPolygon') { return { type: 'MultiPolygon', coordinates: feature.geometry.coordinates.map(function (rings) { return simplifyPolygon(rings, tolerance, highQuality); }) }; } else { // unsupported geometry type supplied return feature; } } /* * returns true if ring's first coordinate is the same as its last */ function checkValidity(ring) { if (ring.length < 3) { return false; //if the last point is the same as the first, it's not a triangle } else if (ring.length === 3 && ((ring[2][0] === ring[0][0]) && (ring[2][1] === ring[0][1]))) { return false; } else { return true; } } function simpleFeature(geom, properties) { return { type: 'Feature', geometry: geom, properties: properties }; } function simplifyLine(coordinates, tolerance, highQuality) { return simplify(coordinates.map(function (coord) { return {x: coord[0], y: coord[1]}; }), tolerance, highQuality).map(function (coords) { return [coords.x, coords.y]; }); } function simplifyPolygon(coordinates, tolerance, highQuality) { return coordinates.map(function (ring) { var pts = ring.map(function (coord) { return {x: coord[0], y: coord[1]}; }); if (pts.length < 4) { throw new Error('Invalid polygon'); } var simpleRing = simplify(pts, tolerance, highQuality).map(function (coords) { return [coords.x, coords.y]; }); //remove 1 percent of tolerance until enough points to make a triangle while (!checkValidity(simpleRing)) { tolerance -= tolerance * 0.01; simpleRing = simplify(pts, tolerance, highQuality).map(function (coords) { return [coords.x, coords.y]; }); } if ( (simpleRing[simpleRing.length - 1][0] !== simpleRing[0][0]) || (simpleRing[simpleRing.length - 1][1] !== simpleRing[0][1])) { simpleRing.push(simpleRing[0]); } return simpleRing; }); } /***/ }, /* 34 */ /***/ function(module, exports) { module.exports = require("simplify-js"); /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var linestring = __webpack_require__(12).lineString; var Spline = __webpack_require__(36); /** * Takes a {@link LineString|line} and returns a curved version * by applying a [Bezier spline](http://en.wikipedia.org/wiki/B%C3%A9zier_spline) * algorithm. * * The bezier spline implementation is by [Leszek Rybicki](http://leszek.rybicki.cc/). * * @name bezier * @param {Feature<LineString>} line input LineString * @param {number} [resolution=10000] time in milliseconds between points * @param {number} [sharpness=0.85] a measure of how curvy the path should be between splines * @returns {Feature<LineString>} curved line * @example * var line = { * "type": "Feature", * "properties": { * "stroke": "#f00" * }, * "geometry": { * "type": "LineString", * "coordinates": [ * [-76.091308, 18.427501], * [-76.695556, 18.729501], * [-76.552734, 19.40443], * [-74.61914, 19.134789], * [-73.652343, 20.07657], * [-73.157958, 20.210656] * ] * } * }; * * var curved = turf.bezier(line); * curved.properties = { stroke: '#0f0' }; * * var result = { * "type": "FeatureCollection", * "features": [line, curved] * }; * * //=result */ module.exports = function (line, resolution, sharpness) { var lineOut = linestring([]); lineOut.properties = line.properties; var spline = new Spline({ points: line.geometry.coordinates.map(function (pt) { return {x: pt[0], y: pt[1]}; }), duration: resolution, sharpness: sharpness }); for (var i = 0; i < spline.duration; i += 10) { var pos = spline.pos(i); if (Math.floor(i / 100) % 2 === 0) { lineOut.geometry.coordinates.push([pos.x, pos.y]); } } return lineOut; }; /***/ }, /* 36 */ /***/ function(module, exports) { /* eslint-disable */ /** * BezierSpline * https://github.com/leszekr/bezier-spline-js * * @private * @copyright * Copyright (c) 2013 Leszek Rybicki * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var Spline = function (options) { this.points = options.points || []; this.duration = options.duration || 10000; this.sharpness = options.sharpness || 0.85; this.centers = []; this.controls = []; this.stepLength = options.stepLength || 60; this.length = this.points.length; this.delay = 0; // this is to ensure compatibility with the 2d version for (var i = 0; i < this.length; i++) this.points[i].z = this.points[i].z || 0; for (var i = 0; i < this.length - 1; i++) { var p1 = this.points[i]; var p2 = this.points[i + 1]; this.centers.push({ x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2, z: (p1.z + p2.z) / 2 }); } this.controls.push([this.points[0], this.points[0]]); for (var i = 0; i < this.centers.length - 1; i++) { var p1 = this.centers[i]; var p2 = this.centers[i + 1]; var dx = this.points[i + 1].x - (this.centers[i].x + this.centers[i + 1].x) / 2; var dy = this.points[i + 1].y - (this.centers[i].y + this.centers[i + 1].y) / 2; var dz = this.points[i + 1].z - (this.centers[i].y + this.centers[i + 1].z) / 2; this.controls.push([{ x: (1.0 - this.sharpness) * this.points[i + 1].x + this.sharpness * (this.centers[i].x + dx), y: (1.0 - this.sharpness) * this.points[i + 1].y + this.sharpness * (this.centers[i].y + dy), z: (1.0 - this.sharpness) * this.points[i + 1].z + this.sharpness * (this.centers[i].z + dz)}, { x: (1.0 - this.sharpness) * this.points[i + 1].x + this.sharpness * (this.centers[i + 1].x + dx), y: (1.0 - this.sharpness) * this.points[i + 1].y + this.sharpness * (this.centers[i + 1].y + dy), z: (1.0 - this.sharpness) * this.points[i + 1].z + this.sharpness * (this.centers[i + 1].z + dz)}]); } this.controls.push([this.points[this.length - 1], this.points[this.length - 1]]); this.steps = this.cacheSteps(this.stepLength); return this; }; /* Caches an array of equidistant (more or less) points on the curve. */ Spline.prototype.cacheSteps = function (mindist) { var steps = []; var laststep = this.pos(0); steps.push(0); for (var t = 0; t < this.duration; t += 10) { var step = this.pos(t); var dist = Math.sqrt((step.x - laststep.x) * (step.x - laststep.x) + (step.y - laststep.y) * (step.y - laststep.y) + (step.z - laststep.z) * (step.z - laststep.z)); if (dist > mindist) { steps.push(t); laststep = step; } } return steps; }; /* returns angle and speed in the given point in the curve */ Spline.prototype.vector = function (t) { var p1 = this.pos(t + 10); var p2 = this.pos(t - 10); return { angle:180 * Math.atan2(p1.y - p2.y, p1.x - p2.x) / 3.14, speed:Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) + (p2.z - p1.z) * (p2.z - p1.z)) }; }; /* Gets the position of the point, given time. WARNING: The speed is not constant. The time it takes between control points is constant. For constant speed, use Spline.steps[i]; */ Spline.prototype.pos = function (time) { function bezier(t, p1, c1, c2, p2) { var B = function (t) { var t2 = t * t, t3 = t2 * t; return [(t3), (3 * t2 * (1 - t)), (3 * t * (1 - t) * (1 - t)), ((1 - t) * (1 - t) * (1 - t))]; }; var b = B(t); var pos = { x : p2.x * b[0] + c2.x * b[1] + c1.x * b[2] + p1.x * b[3], y : p2.y * b[0] + c2.y * b[1] + c1.y * b[2] + p1.y * b[3], z : p2.z * b[0] + c2.z * b[1] + c1.z * b[2] + p1.z * b[3] }; return pos; } var t = time - this.delay; if (t < 0) t = 0; if (t > this.duration) t = this.duration - 1; //t = t-this.delay; var t2 = (t) / this.duration; if (t2 >= 1) return this.points[this.length - 1]; var n = Math.floor((this.points.length - 1) * t2); var t1 = (this.length - 1) * t2 - n; return bezier(t1, this.points[n], this.controls[n][1], this.controls[n + 1][0], this.points[n + 1]); }; module.exports = Spline; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var inside = __webpack_require__(16); /** * Takes a set of {@link Point|points} and a set of {@link Polygon|polygons} and performs a spatial join. * * @name tag * @param {FeatureCollection<Point>} points input points * @param {FeatureCollection<Polygon>} polygons input polygons * @param {string} field property in `polygons` to add to joined {<Point>} features * @param {string} outField property in `points` in which to store joined property from `polygons` * @return {FeatureCollection<Point>} points with `containingPolyId` property containing values from `polyId` * @example * var pt1 = point([-77, 44]); * var pt2 = point([-77, 38]); * var poly1 = polygon([[ * [-81, 41], * [-81, 47], * [-72, 47], * [-72, 41], * [-81, 41] * ]], {pop: 3000}); * var poly2 = polygon([[ * [-81, 35], * [-81, 41], * [-72, 41], * [-72, 35], * [-81, 35] * ]], {pop: 1000}); * * var points = featureCollection([pt1, pt2]); * var polygons = featureCollection([poly1, poly2]); * * var tagged = turf.tag(points, polygons, * 'pop', 'population'); * * //=tagged */ module.exports = function (points, polygons, field, outField) { // prevent mutations points = JSON.parse(JSON.stringify(points)); polygons = JSON.parse(JSON.stringify(polygons)); points.features.forEach(function (pt) { if (!pt.properties) { pt.properties = {}; } polygons.features.forEach(function (poly) { if (pt.properties[outField] === undefined) { var isInside = inside(pt, poly); if (isInside) { pt.properties[outField] = poly.properties[field]; } } }); }); return points; }; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { // http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array var featureCollection = __webpack_require__(12).featureCollection; /** * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. * * @name sample * @param {FeatureCollection} featurecollection set of input features * @param {number} num number of features to select * @return {FeatureCollection} a FeatureCollection with `n` features * @example * var points = turf.random('points', 1000); * * //=points * * var sample = turf.sample(points, 10); * * //=sample */ module.exports = function (featurecollection, num) { var outFC = featureCollection(getRandomSubarray(featurecollection.features, num)); return outFC; }; function getRandomSubarray(arr, size) { var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index; while (i-- > min) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } return shuffled.slice(min); } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var bbox = __webpack_require__(19); var bboxPolygon = __webpack_require__(40); /** * Takes any number of features and returns a rectangular {@link Polygon} that encompasses all vertices. * * @name envelope * @param {(Feature|FeatureCollection)} features input features * @return {Feature<Polygon>} a rectangular Polygon feature that encompasses all vertices * @example * var fc = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": { * "name": "Location A" * }, * "geometry": { * "type": "Point", * "coordinates": [-75.343, 39.984] * } * }, { * "type": "Feature", * "properties": { * "name": "Location B" * }, * "geometry": { * "type": "Point", * "coordinates": [-75.833, 39.284] * } * }, { * "type": "Feature", * "properties": { * "name": "Location C" * }, * "geometry": { * "type": "Point", * "coordinates": [-75.534, 39.123] * } * } * ] * }; * * var enveloped = turf.envelope(fc); * * var resultFeatures = fc.features.concat(enveloped); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ module.exports = function (features) { return bboxPolygon(bbox(features)); }; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var polygon = __webpack_require__(12).polygon; /** * Takes a bbox and returns an equivalent {@link Polygon|polygon}. * * @name bboxPolygon * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @return {Feature<Polygon>} a Polygon representation of the bounding box * @example * var bbox = [0, 0, 10, 10]; * * var poly = turf.bboxPolygon(bbox); * * //=poly */ module.exports = function (bbox) { var lowLeft = [bbox[0], bbox[1]]; var topLeft = [bbox[0], bbox[3]]; var topRight = [bbox[2], bbox[3]]; var lowRight = [bbox[2], bbox[1]]; return polygon([[ lowLeft, lowRight, topRight, topLeft, lowLeft ]]); }; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var destination = __webpack_require__(42); var helpers = __webpack_require__(12); var polygon = helpers.polygon; /** * Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, miles, or kilometers; and steps for precision. * * @name circle * @param {Feature<Point>} center center point * @param {number} radius radius of the circle * @param {number} [steps=64] number of steps * @param {string} [units=kilometers] miles, kilometers, degrees, or radians * @returns {Feature<Polygon>} circle polygon * @example * var center = point([-75.343, 39.984]); * var radius = 5; * var steps = 10; * var units = 'kilometers'; * * var circle = turf.circle(center, radius, steps, units); * * //=circle */ module.exports = function (center, radius, steps, units) { steps = steps || 64; var coordinates = []; for (var i = 0; i < steps; i++) { coordinates.push(destination(center, radius, i * 360 / steps, units).geometry.coordinates); } coordinates.push(coordinates[0]); return polygon([coordinates]); }; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { //http://en.wikipedia.org/wiki/Haversine_formula //http://www.movable-type.co.uk/scripts/latlong.html var getCoord = __webpack_require__(13).getCoord; var helpers = __webpack_require__(12); var point = helpers.point; var distanceToRadians = helpers.distanceToRadians; /** * Takes a {@link Point} and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature. * * @name destination * @param {Feature<Point>} from starting point * @param {number} distance distance from the starting point * @param {number} bearing ranging from -180 to 180 * @param {string} [units=kilometers] miles, kilometers, degrees, or radians * @returns {Feature<Point>} destination point * @example * var point = { * "type": "Feature", * "properties": { * "marker-color": "#0f0" * }, * "geometry": { * "type": "Point", * "coordinates": [-75.343, 39.984] * } * }; * var distance = 50; * var bearing = 90; * var units = 'miles'; * * var destination = turf.destination(point, distance, bearing, units); * destination.properties['marker-color'] = '#f00'; * * var result = { * "type": "FeatureCollection", * "features": [point, destination] * }; * * //=result */ module.exports = function (from, distance, bearing, units) { var degrees2radians = Math.PI / 180; var radians2degrees = 180 / Math.PI; var coordinates1 = getCoord(from); var longitude1 = degrees2radians * coordinates1[0]; var latitude1 = degrees2radians * coordinates1[1]; var bearing_rad = degrees2radians * bearing; var radians = distanceToRadians(distance, units); var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) + Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearing_rad)); var longitude2 = longitude1 + Math.atan2(Math.sin(bearing_rad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2)); return point([radians2degrees * longitude2, radians2degrees * latitude2]); }; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var bearing = __webpack_require__(44); var destination = __webpack_require__(42); var distance = __webpack_require__(18); /** * Takes two {@link Point|points} and returns a point midway between them. * The midpoint is calculated geodesically, meaning the curvature of the earth is taken into account. * * @name midpoint * @param {Feature<Point>} from first point * @param {Feature<Point>} to second point * @return {Feature<Point>} a point midway between `pt1` and `pt2` * @example * var pt1 = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [144.834823, -37.771257] * } * }; * var pt2 = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [145.14244, -37.830937] * } * }; * * var midpointed = turf.midpoint(pt1, pt2); * midpointed.properties['marker-color'] = '#f00'; * * * var result = { * "type": "FeatureCollection", * "features": [pt1, pt2, midpointed] * }; * * //=result */ module.exports = function (from, to) { var dist = distance(from, to, 'miles'); var heading = bearing(from, to); var midpoint = destination(from, dist / 2, heading, 'miles'); return midpoint; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var getCoord = __webpack_require__(13).getCoord; //http://en.wikipedia.org/wiki/Haversine_formula //http://www.movable-type.co.uk/scripts/latlong.html /** * Takes two {@link Point|points} and finds the geographic bearing between them. * * @name bearing * @param {Feature<Point>} start starting Point * @param {Feature<Point>} end ending Point * @returns {number} bearing in decimal degrees * @example * var point1 = { * "type": "Feature", * "properties": { * "marker-color": '#f00' * }, * "geometry": { * "type": "Point", * "coordinates": [-75.343, 39.984] * } * }; * var point2 = { * "type": "Feature", * "properties": { * "marker-color": '#0f0' * }, * "geometry": { * "type": "Point", * "coordinates": [-75.534, 39.123] * } * }; * * var points = { * "type": "FeatureCollection", * "features": [point1, point2] * }; * * //=points * * var bearing = turf.bearing(point1, point2); * * //=bearing */ module.exports = function (start, end) { var degrees2radians = Math.PI / 180; var radians2degrees = 180 / Math.PI; var coordinates1 = getCoord(start); var coordinates2 = getCoord(end); var lon1 = degrees2radians * coordinates1[0]; var lon2 = degrees2radians * coordinates2[0]; var lat1 = degrees2radians * coordinates1[1]; var lat2 = degrees2radians * coordinates2[1]; var a = Math.sin(lon2 - lon1) * Math.cos(lat2); var b = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1); var bearing = radians2degrees * Math.atan2(a, b); return bearing; }; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { // http://stackoverflow.com/questions/839899/how-do-i-calculate-a-point-on-a-circles-circumference // radians = degrees * (pi/180) // https://github.com/bjornharrtell/jsts/blob/master/examples/buffer.html var helpers = __webpack_require__(12); var featureCollection = helpers.featureCollection; var jsts = __webpack_require__(29); var normalize = __webpack_require__(46); /** * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. * * @name buffer * @param {(Feature|FeatureCollection)} feature input to be buffered * @param {number} radius distance to draw the buffer * @param {string} units any of the options supported by turf units * @return {FeatureCollection<Polygon>|FeatureCollection<MultiPolygon>|Polygon|MultiPolygon} buffered features * * @example * var pt = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-90.548630, 14.616599] * } * }; * var unit = 'miles'; * * var buffered = turf.buffer(pt, 500, unit); * var result = turf.featurecollection([buffered, pt]); * * //=result */ module.exports = function (feature, radius, units) { var degrees = helpers.distanceToDegrees(radius, units); var fc = normalize(feature); var buffered = normalize(featureCollection(fc.features.map(function (f) { return bufferOp(f, degrees); }))); if (buffered.features.length > 1) return buffered; else if (buffered.features.length === 1) return buffered.features[0]; }; function bufferOp(feature, radius) { var reader = new jsts.io.GeoJSONReader(); var geom = reader.read(feature.geometry); var buffered = geom.buffer(radius); var writer = new jsts.io.GeoJSONWriter(); buffered = writer.write(buffered); return { type: 'Feature', geometry: buffered, properties: {} }; } /***/ }, /* 46 */ /***/ function(module, exports) { module.exports = require("geojson-normalize"); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var bbox = __webpack_require__(19), point = __webpack_require__(12).point; /** * Takes a {@link Feature} or {@link FeatureCollection} and returns the absolute center point of all features. * * @name center * @param {(Feature|FeatureCollection)} layer input features * @return {Feature<Point>} a Point feature at the absolute center point of all input features * @example * var features = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.522259, 35.4691] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.502754, 35.463455] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.508269, 35.463245] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.516809, 35.465779] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.515372, 35.467072] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.509363, 35.463053] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.511123, 35.466601] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.518547, 35.469327] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.519706, 35.469659] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.517839, 35.466998] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.508678, 35.464942] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-97.514914, 35.463453] * } * } * ] * }; * * var centerPt = turf.center(features); * centerPt.properties['marker-size'] = 'large'; * centerPt.properties['marker-color'] = '#000'; * * var resultFeatures = features.features.concat(centerPt); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ module.exports = function (layer) { var ext = bbox(layer); var x = (ext[0] + ext[2]) / 2; var y = (ext[1] + ext[3]) / 2; return point([x, y]); }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var each = __webpack_require__(20).coordEach, centroid = __webpack_require__(49), convex = __webpack_require__(24), explode = __webpack_require__(50), point = __webpack_require__(12).point; /** * Takes a [feature](http://geojson.org/geojson-spec.html#feature-objects) * or a [featureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects) * and returns its [center of mass](https://en.wikipedia.org/wiki/Center_of_mass) * using this formula: [Centroid of Polygon](https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon). * * @param {FeatureCollection|Feature} fc - the feature collection or feature * @returns {Feature<Point>} the center of mass * @example * var feature = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [ * [ * [ * 4.854240417480469, * 45.77258200374433 * ], * [ * 4.8445844650268555, * 45.777431068484894 * ], * [ * 4.845442771911621, * 45.778658234059755 * ], * [ * 4.845914840698242, * 45.779376562352425 * ], * [ * 4.846644401550292, * 45.78021460033108 * ], * [ * 4.847245216369629, * 45.78078326178593 * ], * [ * 4.848060607910156, * 45.78138184652523 * ], * [ * 4.8487043380737305, * 45.78186070968964 * ], * [ * 4.849562644958495, * 45.78248921135124 * ], * [ * 4.850893020629883, * 45.78302792142197 * ], * [ * 4.852008819580077, * 45.78374619341895 * ], * [ * 4.852995872497559, * 45.784075398324866 * ], * [ * 4.853854179382324, * 45.78443452873236 * ], * [ * 4.8549699783325195, * 45.78470387501975 * ], * [ * 4.85569953918457, * 45.784793656826345 * ], * [ * 4.857330322265624, * 45.784853511283764 * ], * [ * 4.858231544494629, * 45.78494329284938 * ], * [ * 4.859304428100585, * 45.784883438488365 * ], * [ * 4.858360290527344, * 45.77294120818474 * ], * [ * 4.854240417480469, * 45.77258200374433 * ] * ] * ] * } * }; * * var centerOfMass = turf.centerOfMass(feature); * * //=centerOfMass */ function centerOfMass(fc) { if (fc.type === 'Feature' && fc.geometry.type === 'Polygon') { var coords = []; each(fc, function (coord) { coords.push(coord); }); // First, we neutralize the feature (set it around coordinates [0,0]) to prevent rounding errors // We take any point to translate all the points around 0 var centre = centroid(fc); var translation = centre.geometry.coordinates; var sx = 0; var sy = 0; var sArea = 0; var i, pi, pj, xi, xj, yi, yj, a; var neutralizedPoints = coords.map(function (point) { return [ point[0] - translation[0], point[1] - translation[1] ]; }); for (i = 0; i < coords.length - 1; i++) { // pi is the current point pi = neutralizedPoints[i]; xi = pi[0]; yi = pi[1]; // pj is the next point (pi+1) pj = neutralizedPoints[i + 1]; xj = pj[0]; yj = pj[1]; // a is the common factor to compute the signed area and the final coordinates a = xi * yj - xj * yi; // sArea is the sum used to compute the signed area sArea += a; // sx and sy are the sums used to compute the final coordinates sx += (xi + xj) * a; sy += (yi + yj) * a; } // Shape has no area: fallback on turf.centroid if (sArea === 0) { return centre; } else { // Compute the signed area, and factorize 1/6A var area = sArea * 0.5; var areaFactor = 1 / (6 * area); // Compute the final coordinates, adding back the values that have been neutralized return point([ translation[0] + areaFactor * sx, translation[1] + areaFactor * sy ]); } } else { // Not a polygon: Compute the convex hull and work with that var hull = convex(explode(fc)); if (hull) { return module.exports(hull); } else { // Hull is empty: fallback on the centroid return centroid(fc); } } } module.exports = centerOfMass; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var each = __webpack_require__(20).coordEach; var point = __webpack_require__(12).point; /** * Takes one or more features and calculates the centroid using * the mean of all vertices. * This lessens the effect of small islands and artifacts when calculating * the centroid of a set of polygons. * * @name centroid * @param {(Feature|FeatureCollection)} features input features * @return {Feature<Point>} the centroid of the input features * @example * var poly = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [105.818939,21.004714], * [105.818939,21.061754], * [105.890007,21.061754], * [105.890007,21.004714], * [105.818939,21.004714] * ]] * } * }; * * var centroidPt = turf.centroid(poly); * * var result = { * "type": "FeatureCollection", * "features": [poly, centroidPt] * }; * * //=result */ module.exports = function (features) { var xSum = 0, ySum = 0, len = 0; each(features, function (coord) { xSum += coord[0]; ySum += coord[1]; len++; }, true); return point([xSum / len, ySum / len]); }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var featureCollection = __webpack_require__(12).featureCollection; var each = __webpack_require__(20).coordEach; var point = __webpack_require__(12).point; /** * Takes a feature or set of features and returns all positions as * {@link Point|points}. * * @name explode * @param {(Feature|FeatureCollection)} geojson input features * @return {FeatureCollection<point>} points representing the exploded input features * @throws {Error} if it encounters an unknown geometry type * @example * var poly = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [177.434692, -17.77517], * [177.402076, -17.779093], * [177.38079, -17.803937], * [177.40242, -17.826164], * [177.438468, -17.824857], * [177.454948, -17.796746], * [177.434692, -17.77517] * ]] * } * }; * * var points = turf.explode(poly); * * //=poly * * //=points */ module.exports = function (geojson) { var points = []; each(geojson, function (coord) { points.push(point(coord)); }); return featureCollection(points); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var meta = __webpack_require__(20); /** * Combines a {@link FeatureCollection} of {@link Point}, * {@link LineString}, or {@link Polygon} features * into {@link MultiPoint}, {@link MultiLineString}, or * {@link MultiPolygon} features. * * @name combine * @param {FeatureCollection<(Point|LineString|Polygon)>} fc a FeatureCollection of any type * @return {FeatureCollection<(MultiPoint|MultiLineString|MultiPolygon)>} a FeatureCollection of corresponding type to input * @example * var fc = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [19.026432, 47.49134] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [19.074497, 47.509548] * } * } * ] * }; * * var combined = turf.combine(fc); * * //=combined */ module.exports = function (fc) { var groups = { MultiPoint: {coordinates: [], properties: []}, MultiLineString: {coordinates: [], properties: []}, MultiPolygon: {coordinates: [], properties: []} }; var multiMapping = Object.keys(groups).reduce(function (memo, item) { memo[item.replace('Multi', '')] = item; return memo; }, {}); function addToGroup(feature, key, multi) { if (!multi) { groups[key].coordinates.push(feature.geometry.coordinates); } else { groups[key].coordinates = groups[key].coordinates.concat(feature.geometry.coordinates); } groups[key].properties.push(feature.properties); } meta.featureEach(fc, function (feature) { if (!feature.geometry) return; if (groups[feature.geometry.type]) { addToGroup(feature, feature.geometry.type, true); } else if (multiMapping[feature.geometry.type]) { addToGroup(feature, multiMapping[feature.geometry.type], false); } }); return { type: 'FeatureCollection', features: Object.keys(groups) .filter(function (key) { return groups[key].coordinates.length; }) .sort() .map(function (key) { return { type: 'Feature', properties: { collectedProperties: groups[key].properties }, geometry: { type: key, coordinates: groups[key].coordinates } }; }) }; }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var polygon = __webpack_require__(12).polygon; var earcut = __webpack_require__(53); /** * Tesselates a {@link Feature<Polygon>} into a {@link FeatureCollection<Polygon>} of triangles * using [earcut](https://github.com/mapbox/earcut). * * @name tesselate * @param {Feature<Polygon>} poly the polygon to tesselate * @returns {FeatureCollection<Polygon>} a geometrycollection feature * @example * var poly = turf.random('polygon').features[0]; * * var triangles = turf.tesselate(poly); * * //=triangles */ module.exports = function (poly) { if (!poly.geometry || (poly.geometry.type !== 'Polygon' && poly.geometry.type !== 'MultiPolygon')) { throw new Error('input must be a Polygon or MultiPolygon'); } var fc = {type: 'FeatureCollection', features: []}; if (poly.geometry.type === 'Polygon') { fc.features = processPolygon(poly.geometry.coordinates); } else { poly.geometry.coordinates.forEach(function (coordinates) { fc.features = fc.features.concat(processPolygon(coordinates)); }); } return fc; }; function processPolygon(coordinates) { var data = flattenCoords(coordinates); var dim = 2; var result = earcut(data.vertices, data.holes, dim); var features = []; var vertices = []; result.forEach(function (vert, i) { var index = result[i]; vertices.push([data.vertices[index * dim], data.vertices[index * dim + 1]]); }); for (var i = 0; i < vertices.length; i += 3) { var coords = vertices.slice(i, i + 3); coords.push(vertices[i]); features.push(polygon([coords])); } return features; } function flattenCoords(data) { var dim = data[0][0].length, result = {vertices: [], holes: [], dimensions: dim}, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) { for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; } /***/ }, /* 53 */ /***/ function(module, exports) { module.exports = require("earcut"); /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { // depend on jsts for now http://bjornharrtell.github.io/jsts/ var jsts = __webpack_require__(29); /** * Takes two {@link Polygon|polygons} and finds their intersection. If they share a border, returns the border; if they don't intersect, returns undefined. * * @name intersect * @param {Feature<Polygon>} poly1 the first polygon * @param {Feature<Polygon>} poly2 the second polygon * @return {(Feature|undefined)} returns a feature representing the point(s) they share (in case of a {@link Point} or {@link MultiPoint}), the borders they share (in case of a {@link LineString} or a {@link MultiLineString}), the area they share (in case of {@link Polygon} or {@link MultiPolygon}). If they do not share any point, returns `undefined`. * @example * var poly1 = polygon([[ * [-122.801742, 45.48565], * [-122.801742, 45.60491], * [-122.584762, 45.60491], * [-122.584762, 45.48565], * [-122.801742, 45.48565] * ]]); * * var poly2 = polygon([[ * [-122.520217, 45.535693], * [-122.64038, 45.553967], * [-122.720031, 45.526554], * [-122.669906, 45.507309], * [-122.723464, 45.446643], * [-122.532577, 45.408574], * [-122.487258, 45.477466], * [-122.520217, 45.535693] * ]]); * * var intersection = turf.intersect(poly1, poly2); * * //=intersection */ module.exports = function intersect(poly1, poly2) { var geom1, geom2; if (poly1.type === 'Feature') geom1 = poly1.geometry; else geom1 = poly1; if (poly2.type === 'Feature') geom2 = poly2.geometry; else geom2 = poly2; var reader = new jsts.io.GeoJSONReader(); var a = reader.read(JSON.stringify(geom1)); var b = reader.read(JSON.stringify(geom2)); var intersection = a.intersection(b); if (intersection.isEmpty()) { return undefined; } var writer = new jsts.io.GeoJSONWriter(); var geojsonGeometry = writer.write(intersection); return { type: 'Feature', properties: {}, geometry: geojsonGeometry }; }; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var distance = __webpack_require__(18); /** * Takes a reference {@link Point|point} and a FeatureCollection of Features * with Point geometries and returns the * point from the FeatureCollection closest to the reference. This calculation * is geodesic. * * @name nearest * @param {Feature<Point>} targetPoint the reference point * @param {FeatureCollection<Point>} points against input point set * @return {Feature<Point>} the closest point in the set to the reference point * @example * var point = { * "type": "Feature", * "properties": { * "marker-color": "#0f0" * }, * "geometry": { * "type": "Point", * "coordinates": [28.965797, 41.010086] * } * }; * var against = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [28.973865, 41.011122] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [28.948459, 41.024204] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [28.938674, 41.013324] * } * } * ] * }; * * var nearest = turf.nearest(point, against); * nearest.properties['marker-color'] = '#f00'; * * var resultFeatures = against.features.concat(point); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ module.exports = function (targetPoint, points) { var nearestPoint, minDist = Infinity; for (var i = 0; i < points.features.length; i++) { var distanceToPoint = distance(targetPoint, points.features[i], 'miles'); if (distanceToPoint < minDist) { nearestPoint = points.features[i]; minDist = distanceToPoint; } } return nearestPoint; }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var random = __webpack_require__(57); /** * Generates random {@link GeoJSON} data, including {@link Point|Points} and {@link Polygon|Polygons}, for testing * and experimentation. * * @name random * @param {string} [type='point'] type of features desired: 'points' or 'polygons' * @param {number} [count=1] how many geometries should be generated. * @param {Object} options options relevant to the feature desired. Can include: * @param {Array<number>} options.bbox a bounding box inside of which geometries * are placed. In the case of {@link Point} features, they are guaranteed to be within this bounds, * while {@link Polygon} features have their centroid within the bounds. * @param {number} [options.num_vertices=10] options.vertices the number of vertices added * to polygon features. * @param {Number} [options.max_radial_length=10] the total number of decimal * degrees longitude or latitude that a polygon can extent outwards to * from its center. * @return {FeatureCollection} generated random features * @example * var points = turf.random('points', 100, { * bbox: [-70, 40, -60, 60] * }); * * //=points * * var polygons = turf.random('polygons', 4, { * bbox: [-70, 40, -60, 60] * }); * * //=polygons */ module.exports = function (type, count, options) { options = options || {}; count = count || 1; switch (type) { case 'point': case 'points': case undefined: return random.point(count, options.bbox); case 'polygon': case 'polygons': return random.polygon( count, options.num_vertices, options.max_radial_length, options.bbox); default: throw new Error('Unknown type given: valid options are points and polygons'); } }; /***/ }, /* 57 */ /***/ function(module, exports) { module.exports = require("geojson-random"); /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Takes a {@link Polygon|polygon} and returns {@link Point|points} at all self-intersections. * * @name kinks * @param {Feature<Polygon>|Polygon} polygon input polygon * @returns {FeatureCollection<Point>} self-intersections * @example * var poly = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-12.034835, 8.901183], * [-12.060413, 8.899826], * [-12.03638, 8.873199], * [-12.059383, 8.871418], * [-12.034835, 8.901183] * ]] * } * }; * * var kinks = turf.kinks(poly); * * var resultFeatures = kinks.intersections.features.concat(poly); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ var point = __webpack_require__(12).point; module.exports = function (polyIn) { var poly; var results = { type: 'FeatureCollection', features: [] }; if (polyIn.type === 'Feature') { poly = polyIn.geometry; } else { poly = polyIn; } poly.coordinates.forEach(function (ring1) { poly.coordinates.forEach(function (ring2) { for (var i = 0; i < ring1.length - 1; i++) { for (var k = 0; k < ring2.length - 1; k++) { // don't check adjacent sides of a given ring, since of course they intersect in a vertex. if (ring1 === ring2 && (Math.abs(i - k) === 1 || Math.abs(i - k) === ring1.length - 2)) { continue; } var intersection = lineIntersects(ring1[i][0], ring1[i][1], ring1[i + 1][0], ring1[i + 1][1], ring2[k][0], ring2[k][1], ring2[k + 1][0], ring2[k + 1][1]); if (intersection) { results.features.push(point([intersection[0], intersection[1]])); } } } }); }); return results; }; // modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/ function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) { // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point var denominator, a, b, numerator1, numerator2, result = { x: null, y: null, onLine1: false, onLine2: false }; denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY)); if (denominator === 0) { if (result.x !== null && result.y !== null) { return result; } else { return false; } } a = line1StartY - line2StartY; b = line1StartX - line2StartX; numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b); numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b); a = numerator1 / denominator; b = numerator2 / denominator; // if we cast these lines infinitely in both directions, they intersect here: result.x = line1StartX + (a * (line1EndX - line1StartX)); result.y = line1StartY + (a * (line1EndY - line1StartY)); // if line1 is a segment and line2 is infinite, they intersect if: if (a >= 0 && a <= 1) { result.onLine1 = true; } // if line2 is a segment and line1 is infinite, they intersect if: if (b >= 0 && b <= 1) { result.onLine2 = true; } // if line1 and line2 are segments, they intersect if both of the above are true if (result.onLine1 && result.onLine2) { return [result.x, result.y]; } else { return false; } } /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var featureCollection = __webpack_require__(12).featureCollection; var centroid = __webpack_require__(47); var distance = __webpack_require__(18); var inside = __webpack_require__(16); var explode = __webpack_require__(50); /** * Takes a feature and returns a {@link Point} guaranteed to be on the surface of the feature. * * * Given a {@link Polygon}, the point will be in the area of the polygon * * Given a {@link LineString}, the point will be along the string * * Given a {@link Point}, the point will the same as the input * * @param {(Feature|FeatureCollection)} fc any feature or set of features * @returns {Feature} a point on the surface of `input` * @example * // create a random polygon * var polygon = turf.random('polygon'); * * //=polygon * * var pointOnPolygon = turf.pointOnSurface(polygon); * * var resultFeatures = polygon.features.concat(pointOnPolygon); * var result = { * "type": "FeatureCollection", * "features": resultFeatures * }; * * //=result */ function pointOnSurface(fc) { // normalize if (fc.type !== 'FeatureCollection') { if (fc.type !== 'Feature') { fc = { type: 'Feature', geometry: fc, properties: {} }; } fc = featureCollection([fc]); } //get centroid var cent = centroid(fc); // check to see if centroid is on surface var onSurface = false; var i = 0; while (!onSurface && i < fc.features.length) { var geom = fc.features[i].geometry; var x, y, x1, y1, x2, y2, k; var onLine = false; if (geom.type === 'Point') { if (cent.geometry.coordinates[0] === geom.coordinates[0] && cent.geometry.coordinates[1] === geom.coordinates[1]) { onSurface = true; } } else if (geom.type === 'MultiPoint') { var onMultiPoint = false; k = 0; while (!onMultiPoint && k < geom.coordinates.length) { if (cent.geometry.coordinates[0] === geom.coordinates[k][0] && cent.geometry.coordinates[1] === geom.coordinates[k][1]) { onSurface = true; onMultiPoint = true; } k++; } } else if (geom.type === 'LineString') { k = 0; while (!onLine && k < geom.coordinates.length - 1) { x = cent.geometry.coordinates[0]; y = cent.geometry.coordinates[1]; x1 = geom.coordinates[k][0]; y1 = geom.coordinates[k][1]; x2 = geom.coordinates[k + 1][0]; y2 = geom.coordinates[k + 1][1]; if (pointOnSegment(x, y, x1, y1, x2, y2)) { onLine = true; onSurface = true; } k++; } } else if (geom.type === 'MultiLineString') { var j = 0; while (j < geom.coordinates.length) { onLine = false; k = 0; var line = geom.coordinates[j]; while (!onLine && k < line.length - 1) { x = cent.geometry.coordinates[0]; y = cent.geometry.coordinates[1]; x1 = line[k][0]; y1 = line[k][1]; x2 = line[k + 1][0]; y2 = line[k + 1][1]; if (pointOnSegment(x, y, x1, y1, x2, y2)) { onLine = true; onSurface = true; } k++; } j++; } } else if (geom.type === 'Polygon' || geom.type === 'MultiPolygon') { var f = { type: 'Feature', geometry: geom, properties: {} }; if (inside(cent, f)) { onSurface = true; } } i++; } if (onSurface) { return cent; } else { var vertices = featureCollection([]); for (i = 0; i < fc.features.length; i++) { vertices.features = vertices.features.concat(explode(fc.features[i]).features); } var closestVertex; var closestDistance = Infinity; for (i = 0; i < vertices.features.length; i++) { var dist = distance(cent, vertices.features[i], 'miles'); if (dist < closestDistance) { closestDistance = dist; closestVertex = vertices.features[i]; } } return closestVertex; } } function pointOnSegment(x, y, x1, y1, x2, y2) { var ab = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); var ap = Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)); var pb = Math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y)); if (ab === ap + pb) { return true; } } module.exports = pointOnSurface; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var geometryArea = __webpack_require__(61).geometry; /** * Takes one or more features and returns their area * in square meters. * * @param {(Feature|FeatureCollection)} input input features * @return {number} area in square meters * @example * var polygons = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-67.031021, 10.458102], * [-67.031021, 10.53372], * [-66.929397, 10.53372], * [-66.929397, 10.458102], * [-67.031021, 10.458102] * ]] * } * }, { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [-66.919784, 10.397325], * [-66.919784, 10.513467], * [-66.805114, 10.513467], * [-66.805114, 10.397325], * [-66.919784, 10.397325] * ]] * } * } * ] * }; * * var area = turf.area(polygons); * * //=area */ function area(input) { if (input.type === 'FeatureCollection') { for (var i = 0, sum = 0; i < input.features.length; i++) { if (input.features[i].geometry) { sum += geometryArea(input.features[i].geometry); } } return sum; } else if (input.type === 'Feature') { return geometryArea(input.geometry); } else { return geometryArea(input); } } module.exports = area; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var wgs84 = __webpack_require__(62); module.exports.geometry = geometry; module.exports.ring = ringArea; function geometry(_) { var area = 0, i; switch (_.type) { case 'Polygon': return polygonArea(_.coordinates); case 'MultiPolygon': for (i = 0; i < _.coordinates.length; i++) { area += polygonArea(_.coordinates[i]); } return area; case 'Point': case 'MultiPoint': case 'LineString': case 'MultiLineString': return 0; case 'GeometryCollection': for (i = 0; i < _.geometries.length; i++) { area += geometry(_.geometries[i]); } return area; } } function polygonArea(coords) { var area = 0; if (coords && coords.length > 0) { area += Math.abs(ringArea(coords[0])); for (var i = 1; i < coords.length; i++) { area -= Math.abs(ringArea(coords[i])); } } return area; } /** * Calculate the approximate area of the polygon were it projected onto * the earth. Note that this area will be positive if ring is oriented * clockwise, otherwise it will be negative. * * Reference: * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 * * Returns: * {float} The approximate signed geodesic area of the polygon in square * meters. */ function ringArea(coords) { var p1, p2, p3, lowerIndex, middleIndex, upperIndex, i, area = 0, coordsLength = coords.length; if (coordsLength > 2) { for (i = 0; i < coordsLength; i++) { if (i === coordsLength - 2) {// i = N-2 lowerIndex = coordsLength - 2; middleIndex = coordsLength -1; upperIndex = 0; } else if (i === coordsLength - 1) {// i = N-1 lowerIndex = coordsLength - 1; middleIndex = 0; upperIndex = 1; } else { // i = 0 to N-3 lowerIndex = i; middleIndex = i+1; upperIndex = i+2; } p1 = coords[lowerIndex]; p2 = coords[middleIndex]; p3 = coords[upperIndex]; area += ( rad(p3[0]) - rad(p1[0]) ) * Math.sin( rad(p2[1])); } area = area * wgs84.RADIUS * wgs84.RADIUS / 2; } return area; } function rad(_) { return _ * Math.PI / 180; } /***/ }, /* 62 */ /***/ function(module, exports) { module.exports = require("wgs84"); /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var measureDistance = __webpack_require__(18); var point = __webpack_require__(12).point; var bearing = __webpack_require__(44); var destination = __webpack_require__(42); /** * Takes a {@link LineString|line} and returns a {@link Point|point} at a specified distance along the line. * * @name along * @param {Feature<LineString>} line input line * @param {number} distance distance along the line * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @return {Feature<Point>} Point `distance` `units` along the line * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [-77.031669, 38.878605], * [-77.029609, 38.881946], * [-77.020339, 38.884084], * [-77.025661, 38.885821], * [-77.021884, 38.889563], * [-77.019824, 38.892368] * ] * } * }; * * var along = turf.along(line, 1, 'miles'); * * var result = { * "type": "FeatureCollection", * "features": [line, along] * }; * * //=result */ module.exports = function (line, distance, units) { var coords; if (line.type === 'Feature') coords = line.geometry.coordinates; else if (line.type === 'LineString') coords = line.coordinates; else throw new Error('input must be a LineString Feature or Geometry'); var travelled = 0; for (var i = 0; i < coords.length; i++) { if (distance >= travelled && i === coords.length - 1) break; else if (travelled >= distance) { var overshot = distance - travelled; if (!overshot) return point(coords[i]); else { var direction = bearing(coords[i], coords[i - 1]) - 180; var interpolated = destination(coords[i], overshot, direction, units); return interpolated; } } else { travelled += measureDistance(coords[i], coords[i + 1], units); } } return point(coords[coords.length - 1]); }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var distance = __webpack_require__(18); var point = __webpack_require__(12).point; /** * Takes a {@link LineString} or {@link Polygon} and measures its length in the specified units. * * @name lineDistance * @param {Feature<(LineString|Polygon)>|FeatureCollection<(LineString|Polygon)>} line line to measure * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @return {number} length of the input line * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [-77.031669, 38.878605], * [-77.029609, 38.881946], * [-77.020339, 38.884084], * [-77.025661, 38.885821], * [-77.021884, 38.889563], * [-77.019824, 38.892368] * ] * } * }; * * var length = turf.lineDistance(line, 'miles'); * * //=line * * //=length */ module.exports = function lineDistance(line, units) { if (line.type === 'FeatureCollection') { return line.features.reduce(function (memo, feature) { return memo + lineDistance(feature, units); }, 0); } var geometry = line.type === 'Feature' ? line.geometry : line; var d, i; if (geometry.type === 'LineString') { return length(geometry.coordinates, units); } else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') { d = 0; for (i = 0; i < geometry.coordinates.length; i++) { d += length(geometry.coordinates[i], units); } return d; } else if (geometry.type === 'MultiPolygon') { d = 0; for (i = 0; i < geometry.coordinates.length; i++) { for (var j = 0; j < geometry.coordinates[i].length; j++) { d += length(geometry.coordinates[i][j], units); } } return d; } else { throw new Error('input must be a LineString, MultiLineString, ' + 'Polygon, or MultiPolygon Feature or Geometry (or a FeatureCollection ' + 'containing only those types)'); } }; function length(coords, units) { var travelled = 0; var prevCoords = point(coords[0]); var curCoords = point(coords[0]); var temp; for (var i = 1; i < coords.length; i++) { curCoords.geometry.coordinates = coords[i]; travelled += distance(prevCoords, curCoords, units); temp = prevCoords; prevCoords = curCoords; curCoords = temp; } return travelled; } /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var linestring = __webpack_require__(12).lineString; var pointOnLine = __webpack_require__(66); /** * Takes a {@link LineString|line}, a start {@link Point}, and a stop point * and returns a subsection of the line in-between those points. * The start & stop points don't need to fall exactly on the line. * * This can be useful for extracting only the part of a route between waypoints. * * @name lineSlice * @param {Feature<Point>} startPt starting point * @param {Feature<Point>} stopPt stopping point * @param {Feature<LineString>|LineString} line line to slice * @return {Feature<LineString>} sliced line * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [-77.031669, 38.878605], * [-77.029609, 38.881946], * [-77.020339, 38.884084], * [-77.025661, 38.885821], * [-77.021884, 38.889563], * [-77.019824, 38.892368] * ] * } * }; * var start = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-77.029609, 38.881946] * } * }; * var stop = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-77.021884, 38.889563] * } * }; * * var sliced = turf.lineSlice(start, stop, line); * * //=line * * //=sliced */ module.exports = function lineSlice(startPt, stopPt, line) { var coords; if (line.type === 'Feature') { coords = line.geometry.coordinates; } else if (line.type === 'LineString') { coords = line.coordinates; } else { throw new Error('input must be a LineString Feature or Geometry'); } var startVertex = pointOnLine(line, startPt); var stopVertex = pointOnLine(line, stopPt); var ends; if (startVertex.properties.index <= stopVertex.properties.index) { ends = [startVertex, stopVertex]; } else { ends = [stopVertex, startVertex]; } var clipLine = linestring([ends[0].geometry.coordinates], {}); for (var i = ends[0].properties.index + 1; i < ends[1].properties.index + 1; i++) { clipLine.geometry.coordinates.push(coords[i]); } clipLine.geometry.coordinates.push(ends[1].geometry.coordinates); return clipLine; }; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var distance = __webpack_require__(18); var point = __webpack_require__(12).point; var bearing = __webpack_require__(44); var destination = __webpack_require__(42); /** * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the LineString. * * @name pointOnLine * @param {Feature<LineString>} line line to snap to * @param {Feature<Point>} pt point to snap from * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @return {Feature<Point>} closest point on the `line` to `point` * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [-77.031669, 38.878605], * [-77.029609, 38.881946], * [-77.020339, 38.884084], * [-77.025661, 38.885821], * [-77.021884, 38.889563], * [-77.019824, 38.892368] * ] * } * }; * var pt = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [-77.037076, 38.884017] * } * }; * * var snapped = turf.pointOnLine(line, pt, 'miles'); * snapped.properties['marker-color'] = '#00f' * * var result = { * "type": "FeatureCollection", * "features": [line, pt, snapped] * }; * * //=result */ module.exports = function (line, pt, units) { var coords; if (line.type === 'Feature') { coords = line.geometry.coordinates; } else if (line.type === 'LineString') { coords = line.coordinates; } else { throw new Error('input must be a LineString Feature or Geometry'); } var closestPt = point([Infinity, Infinity], { dist: Infinity }); for (var i = 0; i < coords.length - 1; i++) { var start = point(coords[i]); var stop = point(coords[i + 1]); //start start.properties.dist = distance(pt, start, units); //stop stop.properties.dist = distance(pt, stop, units); //perpendicular var heightDistance = Math.max(start.properties.dist, stop.properties.dist); var direction = bearing(start, stop); var perpendicularPt1 = destination(pt, heightDistance, direction + 90, units); var perpendicularPt2 = destination(pt, heightDistance, direction - 90, units); var intersect = lineIntersects( perpendicularPt1.geometry.coordinates[0], perpendicularPt1.geometry.coordinates[1], perpendicularPt2.geometry.coordinates[0], perpendicularPt2.geometry.coordinates[1], start.geometry.coordinates[0], start.geometry.coordinates[1], stop.geometry.coordinates[0], stop.geometry.coordinates[1] ); var intersectPt; if (intersect) { intersectPt = point(intersect); intersectPt.properties.dist = distance(pt, intersectPt, units); } if (start.properties.dist < closestPt.properties.dist) { closestPt = start; closestPt.properties.index = i; } if (stop.properties.dist < closestPt.properties.dist) { closestPt = stop; closestPt.properties.index = i; } if (intersectPt && intersectPt.properties.dist < closestPt.properties.dist) { closestPt = intersectPt; closestPt.properties.index = i; } } return closestPt; }; // modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/ function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) { // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point var denominator, a, b, numerator1, numerator2; var result = { x: null, y: null, onLine1: false, onLine2: false }; denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY)); if (denominator === 0) { if (result.x !== null && result.y !== null) { return result; } else { return false; } } a = line1StartY - line2StartY; b = line1StartX - line2StartX; numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b); numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b); a = numerator1 / denominator; b = numerator2 / denominator; // if we cast these lines infinitely in both directions, they intersect here: result.x = line1StartX + (a * (line1EndX - line1StartX)); result.y = line1StartY + (a * (line1EndY - line1StartY)); // if line1 is a segment and line2 is infinite, they intersect if: if (a > 0 && a < 1) { result.onLine1 = true; } // if line2 is a segment and line1 is infinite, they intersect if: if (b > 0 && b < 1) { result.onLine2 = true; } // if line1 and line2 are segments, they intersect if both of the above are true if (result.onLine1 && result.onLine2) { return [result.x, result.y]; } else { return false; } } /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var bearing = __webpack_require__(44); var distance = __webpack_require__(18); var destination = __webpack_require__(42); var lineString = __webpack_require__(12).lineString; /** * Takes a {@link LineString|line}, a specified distance along the line to a start {@link Point}, * and a specified distance along the line to a stop point * and returns a subsection of the line in-between those points. * * This can be useful for extracting only the part of a route between two distances. * * @name lineSliceAlong * @param {Feature<LineString>|LineString} line input line * @param {number} startDist distance along the line to starting point * @param {number} stopDist distance along the line to ending point * @param {string} [units=kilometers] can be degrees, radians, miles, or kilometers * @return {Feature<LineString>} sliced line * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [ 7.66845703125, 45.058001435398296 ], * [ 9.20654296875, 45.460130637921004 ], * [ 11.348876953125, 44.48866833139467 ], * [ 12.1728515625, 45.43700828867389 ], * [ 12.535400390625, 43.98491011404692 ], * [ 12.425537109375, 41.86956082699455 ], * [ 14.2437744140625, 40.83874913796459 ], * [ 14.765625, 40.681679458715635 ] * ] * } * }; * var start = 12.5; * * var stop = 25; * * var units = 'miles'; * * var sliced = turf.lineSliceAlong(start, stop, line, units); * * //=line * * //=sliced */ module.exports = function lineSliceAlong(line, startDist, stopDist, units) { var coords; var slice = []; if (line.type === 'Feature') coords = line.geometry.coordinates; else if (line.type === 'LineString') coords = line.coordinates; else throw new Error('input must be a LineString Feature or Geometry'); var travelled = 0; var overshot, direction, interpolated; for (var i = 0; i < coords.length; i++) { if (startDist >= travelled && i === coords.length - 1) break; else if (travelled > startDist && slice.length === 0) { overshot = startDist - travelled; if (!overshot) return slice.push(coords[i]); direction = bearing(coords[i], coords[i - 1]) - 180; interpolated = destination(coords[i], overshot, direction, units); slice.push(interpolated.geometry.coordinates); } if (travelled >= stopDist) { overshot = stopDist - travelled; if (!overshot) return slice.push(coords[i]); direction = bearing(coords[i], coords[i - 1]) - 180; interpolated = destination(coords[i], overshot, direction, units); slice.push(interpolated.geometry.coordinates); return lineString(slice); } if (travelled >= startDist) { slice.push(coords[i]); } travelled += distance(coords[i], coords[i + 1], units); } return lineString(coords[coords.length - 1]); }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var featurecollection = __webpack_require__(12).featureCollection; var point = __webpack_require__(12).point; var polygon = __webpack_require__(12).polygon; var distance = __webpack_require__(18); /** * Takes a bounding box and a cell depth and returns a set of square {@link Polygon|polygons} in a grid. * * @name squareGrid * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @param {number} cellSize width of each cell * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers * @return {FeatureCollection<Polygon>} grid a grid of polygons * @example * var bbox = [-96,31,-84,40]; * var cellSize = 10; * var units = 'miles'; * * var squareGrid = turf.squareGrid(bbox, cellSize, units); * * //=squareGrid */ module.exports = function squareGrid(bbox, cellSize, units) { var fc = featurecollection([]); var xFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[2], bbox[1]]), units)); var cellWidth = xFraction * (bbox[2] - bbox[0]); var yFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[0], bbox[3]]), units)); var cellHeight = yFraction * (bbox[3] - bbox[1]); var currentX = bbox[0]; while (currentX <= bbox[2]) { var currentY = bbox[1]; while (currentY <= bbox[3]) { var cellPoly = polygon([[ [currentX, currentY], [currentX, currentY + cellHeight], [currentX + cellWidth, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY] ]]); fc.features.push(cellPoly); currentY += cellHeight; } currentX += cellWidth; } return fc; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var featurecollection = __webpack_require__(12).featureCollection; var polygon = __webpack_require__(12).polygon; var distance = __webpack_require__(18); /** * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid. * * @name triangleGrid * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @param {number} cellSize dimension of each cell * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers * @return {FeatureCollection<Polygon>} grid of polygons * @example * var bbox = [-96,31,-84,40] * var cellSize = 10; * var units = 'miles'; * * var triangleGrid = turf.triangleGrid(extent, cellSize, units); * * //=triangleGrid */ module.exports = function (bbox, cellSize, units) { var fc = featurecollection([]); var xFraction = cellSize / (distance([bbox[0], bbox[1]], [bbox[2], bbox[1]], units)); var cellWidth = xFraction * (bbox[2] - bbox[0]); var yFraction = cellSize / (distance([bbox[0], bbox[1]], [bbox[0], bbox[3]], units)); var cellHeight = yFraction * (bbox[3] - bbox[1]); var xi = 0; var currentX = bbox[0]; while (currentX <= bbox[2]) { var yi = 0; var currentY = bbox[1]; while (currentY <= bbox[3]) { if (xi % 2 === 0 && yi % 2 === 0) { fc.features.push(polygon([[ [currentX, currentY], [currentX, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY] ]]), polygon([[ [currentX, currentY + cellHeight], [currentX + cellWidth, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY + cellHeight] ]])); } else if (xi % 2 === 0 && yi % 2 === 1) { fc.features.push(polygon([[ [currentX, currentY], [currentX + cellWidth, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY] ]]), polygon([[ [currentX, currentY], [currentX, currentY + cellHeight], [currentX + cellWidth, currentY + cellHeight], [currentX, currentY] ]])); } else if (yi % 2 === 0 && xi % 2 === 1) { fc.features.push(polygon([[ [currentX, currentY], [currentX, currentY + cellHeight], [currentX + cellWidth, currentY + cellHeight], [currentX, currentY] ]]), polygon([[ [currentX, currentY], [currentX + cellWidth, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY] ]])); } else if (yi % 2 === 1 && xi % 2 === 1) { fc.features.push(polygon([[ [currentX, currentY], [currentX, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY] ]]), polygon([[ [currentX, currentY + cellHeight], [currentX + cellWidth, currentY + cellHeight], [currentX + cellWidth, currentY], [currentX, currentY + cellHeight] ]])); } currentY += cellHeight; yi++; } xi++; currentX += cellWidth; } return fc; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var point = __webpack_require__(12).point; var polygon = __webpack_require__(12).polygon; var distance = __webpack_require__(18); var featurecollection = __webpack_require__(12).featureCollection; //Precompute cosines and sines of angles used in hexagon creation // for performance gain var cosines = []; var sines = []; for (var i = 0; i < 6; i++) { var angle = 2 * Math.PI / 6 * i; cosines.push(Math.cos(angle)); sines.push(Math.sin(angle)); } /** * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped * hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as * described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). * * @name hexGrid * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @param {number} cellSize dimension of cell in specified units * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers * @param {boolean} [triangles=false] whether to return as triangles instead of hexagons * @return {FeatureCollection<Polygon>} a hexagonal grid * @example * var bbox = [-96,31,-84,40]; * var cellSize = 50; * var units = 'miles'; * * var hexgrid = turf.hexGrid(bbox, cellSize, units); * * //=hexgrid */ module.exports = function hexGrid(bbox, cellSize, units, triangles) { var xFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[2], bbox[1]]), units)); var cellWidth = xFraction * (bbox[2] - bbox[0]); var yFraction = cellSize / (distance(point([bbox[0], bbox[1]]), point([bbox[0], bbox[3]]), units)); var cellHeight = yFraction * (bbox[3] - bbox[1]); var radius = cellWidth / 2; var hex_width = radius * 2; var hex_height = Math.sqrt(3) / 2 * cellHeight; var box_width = bbox[2] - bbox[0]; var box_height = bbox[3] - bbox[1]; var x_interval = 3 / 4 * hex_width; var y_interval = hex_height; var x_span = box_width / (hex_width - radius / 2); var x_count = Math.ceil(x_span); if (Math.round(x_span) === x_count) { x_count++; } var x_adjust = ((x_count * x_interval - radius / 2) - box_width) / 2 - radius / 2; var y_count = Math.ceil(box_height / hex_height); var y_adjust = (box_height - y_count * hex_height) / 2; var hasOffsetY = y_count * hex_height - box_height > hex_height / 2; if (hasOffsetY) { y_adjust -= hex_height / 4; } var fc = featurecollection([]); for (var x = 0; x < x_count; x++) { for (var y = 0; y <= y_count; y++) { var isOdd = x % 2 === 1; if (y === 0 && isOdd) { continue; } if (y === 0 && hasOffsetY) { continue; } var center_x = x * x_interval + bbox[0] - x_adjust; var center_y = y * y_interval + bbox[1] + y_adjust; if (isOdd) { center_y -= hex_height / 2; } if (triangles) { fc.features.push.apply(fc.features, hexTriangles([center_x, center_y], cellWidth / 2, cellHeight / 2)); } else { fc.features.push(hexagon([center_x, center_y], cellWidth / 2, cellHeight / 2)); } } } return fc; }; //Center should be [x, y] function hexagon(center, rx, ry) { var vertices = []; for (var i = 0; i < 6; i++) { var x = center[0] + rx * cosines[i]; var y = center[1] + ry * sines[i]; vertices.push([x, y]); } //first and last vertex must be the same vertices.push(vertices[0]); return polygon([vertices]); } //Center should be [x, y] function hexTriangles(center, rx, ry) { var triangles = []; for (var i = 0; i < 6; i++) { var vertices = []; vertices.push(center); vertices.push([ center[0] + rx * cosines[i], center[1] + ry * sines[i] ]); vertices.push([ center[0] + rx * cosines[(i + 1) % 6], center[1] + ry * sines[(i + 1) % 6] ]); vertices.push(center); triangles.push(polygon([vertices])); } return triangles; } /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var distance = __webpack_require__(18); var squareGrid = __webpack_require__(68); var centroid = __webpack_require__(49); var bbox = __webpack_require__(19); /** * * Takes a FeatureCollection of points with known value, a power parameter, a cell depth, a unit of measurement * and returns a FeatureCollection of polygons in a square-grid with an interpolated value property "IDW" for each grid cell. * It finds application when in need of creating a continuous surface (i.e. rainfall, temperature, chemical dispersion surface...) * from a set of spatially scattered points. * * @param {FeatureCollection<Point>} controlPoints Sampled points with known value * @param {string} valueField GeoJSON field containing the known value to interpolate on * @param {number} b Exponent regulating the distance-decay weighting * @param {number} cellWidth The distance across each cell * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers * @return {FeatureCollection<Polygon>} grid A grid of polygons with a property field "IDW" */ module.exports = function (controlPoints, valueField, b, cellWidth, units) { // check if field containing data exists.. var filtered = controlPoints.features.filter(function (feature) { return feature.properties && feature.properties.hasOwnProperty(valueField); }); if (filtered.length !== 0) { // create a sample square grid // compared to a point grid helps visualizing the output (like a raster..) var samplingGrid = squareGrid(bbox(controlPoints), cellWidth, units); var N = samplingGrid.features.length; for (var i = 0; i < N; i++) { var zw = 0; var sw = 0; // calculate the distance from each control point to cell's centroid for (var j = 0; j < controlPoints.features.length; j++) { var d = distance(centroid(samplingGrid.features[i]), controlPoints.features[j], units); if (d === 0) { zw = controlPoints.features[j].properties[valueField]; } var w = 1.0 / Math.pow(d, b); sw += w; zw += w * controlPoints.features[j].properties[valueField]; } // write IDW value for each grid cell samplingGrid.features[i].properties.z = zw / sw; } return samplingGrid; } else { console.log('Specified Data Field is Missing'); } }; /***/ }, /* 72 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var point = function point(i, w) { return [i / 4 % w, (i / 4 - i / 4 % w) / w]; }; exports.default = point; module.exports = exports["default"]; /***/ }, /* 73 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var matchColor = function matchColor(i, data, color) { var r = data[i], g = data[i + 1], b = data[i + 2]; return color.r === r && color.g === g && color.b === b; }; exports.default = matchColor; module.exports = exports["default"]; /***/ }, /* 74 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var clearColor = function clearColor(i, data) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; }; exports.default = clearColor; module.exports = exports["default"]; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getImageData = undefined; var _promise = __webpack_require__(76); var _promise2 = _interopRequireDefault(_promise); var _fs = __webpack_require__(4); var _fs2 = _interopRequireDefault(_fs); var _canvas = __webpack_require__(140); var _canvas2 = _interopRequireDefault(_canvas); var _ = __webpack_require__(5); var _hexToRGB = __webpack_require__(141); var _hexToRGB2 = _interopRequireDefault(_hexToRGB); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var getImageData = function getImageData(src, hex) { return new _promise2.default(function (resolve, reject) { var vCan = new _canvas2.default(200, 200), vCtx = vCan.getContext('2d'), dMap = new _canvas.Image(); // eslint-disable-line new-parens _fs2.default.readFile(src, function (err, buff) { if (err) reject(err); dMap.src = buff; vCan.width = 800; vCan.height = 800 * (dMap.height / dMap.width); vCtx.drawImage(dMap, 0, 0, vCan.width, vCan.height); console.log('______________' + hex + '___________________'); var imgData = vCtx.getImageData(0, 0, vCan.width, vCan.height), data = imgData.data, color = (0, _hexToRGB2.default)(hex), coods = []; (0, _.isolateDistrict)(data, color); (0, _.expand)(imgData, color, 10); (0, _.contract)(imgData, color, 10); (0, _.contiguousRegions)(imgData, color).forEach(function (region) { (0, _.findEdges)(region, color); coods.push((0, _.getCoords)(region, color)); }); resolve(coods); }); }); }; exports.getImageData = getImageData; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(77), __esModule: true }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(78); __webpack_require__(79); __webpack_require__(122); __webpack_require__(126); module.exports = __webpack_require__(3).Promise; /***/ }, /* 78 */ /***/ function(module, exports) { /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(80)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(83)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(81) , defined = __webpack_require__(82); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 81 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 82 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(84) , $export = __webpack_require__(85) , redefine = __webpack_require__(99) , hide = __webpack_require__(89) , has = __webpack_require__(100) , Iterators = __webpack_require__(101) , $iterCreate = __webpack_require__(102) , setToStringTag = __webpack_require__(118) , getPrototypeOf = __webpack_require__(120) , ITERATOR = __webpack_require__(119)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 84 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(86) , core = __webpack_require__(3) , ctx = __webpack_require__(87) , hide = __webpack_require__(89) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }, /* 86 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(88); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 88 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(90) , createDesc = __webpack_require__(98); module.exports = __webpack_require__(94) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(91) , IE8_DOM_DEFINE = __webpack_require__(93) , toPrimitive = __webpack_require__(97) , dP = Object.defineProperty; exports.f = __webpack_require__(94) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(92); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 92 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(94) && !__webpack_require__(95)(function(){ return Object.defineProperty(__webpack_require__(96)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(95)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 95 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(92) , document = __webpack_require__(86).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(92); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 98 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(89); /***/ }, /* 100 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 101 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var create = __webpack_require__(103) , descriptor = __webpack_require__(98) , setToStringTag = __webpack_require__(118) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(89)(IteratorPrototype, __webpack_require__(119)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(91) , dPs = __webpack_require__(104) , enumBugKeys = __webpack_require__(116) , IE_PROTO = __webpack_require__(113)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(96)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(117).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(90) , anObject = __webpack_require__(91) , getKeys = __webpack_require__(105); module.exports = __webpack_require__(94) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(106) , enumBugKeys = __webpack_require__(116); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(100) , toIObject = __webpack_require__(107) , arrayIndexOf = __webpack_require__(110)(false) , IE_PROTO = __webpack_require__(113)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(108) , defined = __webpack_require__(82); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(109); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 109 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(107) , toLength = __webpack_require__(111) , toIndex = __webpack_require__(112); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(81) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(81) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(114)('keys') , uid = __webpack_require__(115); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(86) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 115 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 116 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(86).document && document.documentElement; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(90).f , has = __webpack_require__(100) , TAG = __webpack_require__(119)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(114)('wks') , uid = __webpack_require__(115) , Symbol = __webpack_require__(86).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(100) , toObject = __webpack_require__(121) , IE_PROTO = __webpack_require__(113)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(82); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(123); var global = __webpack_require__(86) , hide = __webpack_require__(89) , Iterators = __webpack_require__(101) , TO_STRING_TAG = __webpack_require__(119)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(124) , step = __webpack_require__(125) , Iterators = __webpack_require__(101) , toIObject = __webpack_require__(107); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(83)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 124 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 125 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(84) , global = __webpack_require__(86) , ctx = __webpack_require__(87) , classof = __webpack_require__(127) , $export = __webpack_require__(85) , isObject = __webpack_require__(92) , aFunction = __webpack_require__(88) , anInstance = __webpack_require__(128) , forOf = __webpack_require__(129) , speciesConstructor = __webpack_require__(133) , task = __webpack_require__(134).set , microtask = __webpack_require__(136)() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[__webpack_require__(119)('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = 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(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } 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 promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ 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); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(137)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); __webpack_require__(118)($Promise, PROMISE); __webpack_require__(138)(PROMISE); Wrapper = __webpack_require__(3)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), 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 $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(139)(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(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; } }); /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(109) , TAG = __webpack_require__(119)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 128 */ /***/ function(module, exports) { module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(87) , call = __webpack_require__(130) , isArrayIter = __webpack_require__(131) , anObject = __webpack_require__(91) , toLength = __webpack_require__(111) , getIterFn = __webpack_require__(132) , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = call(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(91); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(101) , ITERATOR = __webpack_require__(119)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(127) , ITERATOR = __webpack_require__(119)('iterator') , Iterators = __webpack_require__(101); module.exports = __webpack_require__(3).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(91) , aFunction = __webpack_require__(88) , SPECIES = __webpack_require__(119)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(87) , invoke = __webpack_require__(135) , html = __webpack_require__(117) , cel = __webpack_require__(96) , global = __webpack_require__(86) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(__webpack_require__(109)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 135 */ /***/ function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(86) , macrotask = __webpack_require__(134).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = __webpack_require__(109)(process) == 'process'; module.exports = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode && (parent = process.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var hide = __webpack_require__(89); module.exports = function(target, src, safe){ for(var key in src){ if(safe && target[key])target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(86) , core = __webpack_require__(3) , dP = __webpack_require__(90) , DESCRIPTORS = __webpack_require__(94) , SPECIES = __webpack_require__(119)('species'); module.exports = function(KEY){ var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(119)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 140 */ /***/ function(module, exports) { module.exports = require("canvas"); /***/ }, /* 141 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var hexToRGB = function hexToRGB(hex) { hex = hex.replace(/[#]/, '0x'); return { r: hex >> 16, g: hex >> 8 & 0xFF, b: hex & 0xFF }; }; exports.default = hexToRGB; module.exports = exports['default']; /***/ }, /* 142 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var isolateDistrict = function isolateDistrict(data, color) { for (var i = 0; i < data.length; i += 4) { var r = data[i], g = data[i + 1], b = data[i + 2]; if (color.r !== r || color.g !== g || color.b !== b) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 0; } } return data; }; exports.isolateDistrict = isolateDistrict; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.match = undefined; var _matchColor = __webpack_require__(73); var _matchColor2 = _interopRequireDefault(_matchColor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var match = function match(pos, age, paths, data, color) { if ((0, _matchColor2.default)(pos, data, color)) { paths.unshift({ pos: pos, age: age }); return true; } return false; }; exports.match = match; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.snipRegion = undefined; var _canvas = __webpack_require__(140); var _matchColor = __webpack_require__(73); var _matchColor2 = _interopRequireDefault(_matchColor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var snipRegion = function snipRegion(start, imgData, data, color) { var stack = [start], region = [], w = imgData.width, h = imgData.height, newRegion = data.slice().fill(0), snip = function snip(i) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 0; newRegion[i] = color.r; newRegion[i + 1] = color.g; newRegion[i + 2] = color.b; newRegion[i + 3] = 255; region.push(i); }; while (stack.length) { var newPos = stack.pop(), x = newPos[0]; var y = newPos[1], p = (y * w + x) * 4, reachLeft = void 0, reachRight = void 0; while (y-- >= 0 && (0, _matchColor2.default)(p, data, color)) { p -= w * 4; } p += w * 4; ++y; reachLeft = false; reachRight = false; while (y++ < h - 1 && (0, _matchColor2.default)(p, data, color)) { snip(p); if (x > 0) { if ((0, _matchColor2.default)(p - 4, data, color)) { if (!reachLeft) { stack.push([x - 1, y]); reachLeft = true; } } else if (reachLeft) { reachLeft = false; } } if (x < w - 1) { if ((0, _matchColor2.default)(p + 4, data, color)) { if (!reachRight) { stack.push([x + 1, y]); reachRight = true; } } else if (reachRight) { reachRight = false; } } p += w * 4; } } if (region.length > 200) { return new _canvas.ImageData(newRegion, imgData.width, imgData.height); } return false; }; exports.snipRegion = snipRegion; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.tryToCombine = undefined; var _toConsumableArray2 = __webpack_require__(146); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _distance = __webpack_require__(151); var _distance2 = _interopRequireDefault(_distance); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var tryToCombine = function tryToCombine(coods) { var checking = true; coods = coods.filter(function (v) { return v.length > 20; }); while (coods.length > 1 && checking) { checking = false; for (var i = 0; i < coods.length; i++) { for (var j = 0; j < coods.length; j++) { if (i !== j) { if ((0, _distance2.default)(coods[i][coods[i].length - 1], coods[j][0]) < 20) { var newCood = [].concat((0, _toConsumableArray3.default)(coods[i]), (0, _toConsumableArray3.default)(coods[j])); coods.splice(Math.max(i, j), 1); coods.splice(Math.min(i, j), 1); coods.push(newCood); checking = true; break; } else if ((0, _distance2.default)(coods[i][coods[i].length - 1], coods[j][coods[j].length - 1]) < 20) { coods[j].reverse(); var _newCood = [].concat((0, _toConsumableArray3.default)(coods[i]), (0, _toConsumableArray3.default)(coods[j])); coods.splice(Math.max(i, j), 1); coods.splice(Math.min(i, j), 1); coods.push(_newCood); checking = true; break; } } } if (checking) { break; } } } return coods; }; exports.tryToCombine = tryToCombine; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _from = __webpack_require__(147); var _from2 = _interopRequireDefault(_from); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return (0, _from2.default)(arr); } }; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(148), __esModule: true }; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(79); __webpack_require__(149); module.exports = __webpack_require__(3).Array.from; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(87) , $export = __webpack_require__(85) , toObject = __webpack_require__(121) , call = __webpack_require__(130) , isArrayIter = __webpack_require__(131) , toLength = __webpack_require__(111) , createProperty = __webpack_require__(150) , getIterFn = __webpack_require__(132); $export($export.S + $export.F * !__webpack_require__(139)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $defineProperty = __webpack_require__(90) , createDesc = __webpack_require__(98); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _hypot = __webpack_require__(152); var _hypot2 = _interopRequireDefault(_hypot); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var distance = function distance(a, b) { return (0, _hypot2.default)(a[0] - b[0], a[1] - b[1]); }; exports.default = distance; module.exports = exports["default"]; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(153), __esModule: true }; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(154); module.exports = __webpack_require__(3).Math.hypot; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = __webpack_require__(85) , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , aLen = arguments.length , larg = 0 , arg, div; while(i < aLen){ arg = abs(arguments[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); /***/ } /******/ ]);
app/client/components/utils/ColorPicker.js
jbermudezlobo/lolstats-builder
'use strict' import React from 'react' import ReactCSS from 'reactcss' import { SketchPicker } from 'react-color' class ColorPicker extends ReactCSS.Component { constructor(props) { super(props); this.state = { displayColorPicker: false, color: this.props.defaultColor }; ['handleClick', 'handleClose', 'handleChange', 'handleColor'].forEach(m => { this[m] = this[m].bind(this); return null; }); } handleColor() { this.props.returnColor(this.state.color); } handleClick() { this.setState({ displayColorPicker: !this.state.displayColorPicker }) } handleClose() { this.setState({ displayColorPicker: false }) } handleChange(color){ this.setState({ color: color.rgb }) this.handleColor(); }; render() { const color = { width: '40px', height: '10px', borderRadius: '2px', background: `rgba(${ this.state.color.r }, ${ this.state.color.g }, ${ this.state.color.b }, ${ this.state.color.a })`, }; const swatch = { margin: '0px', padding: '2px', backgroundImage: 'url(http://www.transparenttextures.com/patterns/dark-denim-3.png)', borderRadius: '1px', boxShadow: '0 0 0 1px rgba(0,0,0,.1)', display: 'inline-block', cursor: 'pointer', }; const popover = { position: 'absolute', zIndex: 2, }; const cover = { position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, }; return ( <div> <div style={swatch} onClick={ this.handleClick }> <div style={color} /> </div> { this.state.displayColorPicker ? <div style={popover}> <div style={cover} onClick={ this.handleClose }/> <SketchPicker color={ this.state.color } onChange={ this.handleChange } /> </div> : null } </div> ) } } export default ColorPicker;
ajax/libs/extjs/4.2.1/src/form/field/ComboBox.js
AMoo-Miki/cdnjs
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * @docauthor Jason Johnston <[email protected]> * * A combobox control with support for autocomplete, remote loading, and many other features. * * A ComboBox is like a combination of a traditional HTML text `<input>` field and a `<select>` * field; the user is able to type freely into the field, and/or pick values from a dropdown selection * list. The user can input any value by default, even if it does not appear in the selection list; * to prevent free-form values and restrict them to items in the list, set {@link #forceSelection} to `true`. * * The selection list's options are populated from any {@link Ext.data.Store}, including remote * stores. The data items in the store are mapped to each option's displayed text and backing value via * the {@link #valueField} and {@link #displayField} configurations, respectively. * * If your store is not remote, i.e. it depends only on local data and is loaded up front, you should be * sure to set the {@link #queryMode} to `'local'`, as this will improve responsiveness for the user. * * # Example usage: * * @example * // The data store containing the list of states * var states = Ext.create('Ext.data.Store', { * fields: ['abbr', 'name'], * data : [ * {"abbr":"AL", "name":"Alabama"}, * {"abbr":"AK", "name":"Alaska"}, * {"abbr":"AZ", "name":"Arizona"} * //... * ] * }); * * // Create the combo box, attached to the states data store * Ext.create('Ext.form.ComboBox', { * fieldLabel: 'Choose State', * store: states, * queryMode: 'local', * displayField: 'name', * valueField: 'abbr', * renderTo: Ext.getBody() * }); * * # Events * * To do something when something in ComboBox is selected, configure the select event: * * var cb = Ext.create('Ext.form.ComboBox', { * // all of your config options * listeners:{ * scope: yourScope, * 'select': yourFunction * } * }); * * // Alternatively, you can assign events after the object is created: * var cb = new Ext.form.field.ComboBox(yourOptions); * cb.on('select', yourFunction, yourScope); * * # Multiple Selection * * ComboBox also allows selection of multiple items from the list; to enable multi-selection set the * {@link #multiSelect} config to `true`. * * # Filtered Stores * * If you have a local store that is already filtered, you can use the {@link #lastQuery} config option * to prevent the store from having the filter being cleared on first expand. * * ## Customized combobox * * Both the text shown in dropdown menu and text field can be easily customized: * * @example * var states = Ext.create('Ext.data.Store', { * fields: ['abbr', 'name'], * data : [ * {"abbr":"AL", "name":"Alabama"}, * {"abbr":"AK", "name":"Alaska"}, * {"abbr":"AZ", "name":"Arizona"} * ] * }); * * Ext.create('Ext.form.ComboBox', { * fieldLabel: 'Choose State', * store: states, * queryMode: 'local', * valueField: 'abbr', * renderTo: Ext.getBody(), * // Template for the dropdown menu. * // Note the use of "x-boundlist-item" class, * // this is required to make the items selectable. * tpl: Ext.create('Ext.XTemplate', * '<tpl for=".">', * '<div class="x-boundlist-item">{abbr} - {name}</div>', * '</tpl>' * ), * // template for the content inside text field * displayTpl: Ext.create('Ext.XTemplate', * '<tpl for=".">', * '{abbr} - {name}', * '</tpl>' * ) * }); * * See also the {@link #listConfig} option for additional configuration of the dropdown. * */ Ext.define('Ext.form.field.ComboBox', { extend:'Ext.form.field.Picker', requires: ['Ext.util.DelayedTask', 'Ext.EventObject', 'Ext.view.BoundList', 'Ext.view.BoundListKeyNav', 'Ext.data.StoreManager', 'Ext.layout.component.field.ComboBox'], alternateClassName: 'Ext.form.ComboBox', alias: ['widget.combobox', 'widget.combo'], mixins: { bindable: 'Ext.util.Bindable' }, componentLayout: 'combobox', /** * @cfg {String} [triggerCls='x-form-arrow-trigger'] * An additional CSS class used to style the trigger button. The trigger will always get the {@link #triggerBaseCls} * by default and `triggerCls` will be **appended** if specified. */ triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger', /** * @cfg {String} [hiddenName=""] * The name of an underlying hidden field which will be synchronized with the underlying value of the combo. * This option is useful if the combo is part of a form element doing a regular form post. The hidden field * will not be created unless a hiddenName is specified. */ hiddenName: '', /** * @property {Ext.Element} hiddenDataEl * @private */ /** * @private * @cfg {String} * CSS class used to find the {@link #hiddenDataEl} */ hiddenDataCls: Ext.baseCSSPrefix + 'hide-display ' + Ext.baseCSSPrefix + 'form-data-hidden', /** * @cfg * @inheritdoc */ fieldSubTpl: [ '<div class="{hiddenDataCls}" role="presentation"></div>', '<input id="{id}" type="{type}" {inputAttrTpl} class="{fieldCls} {typeCls} {editableCls}" autocomplete="off"', '<tpl if="value"> value="{[Ext.util.Format.htmlEncode(values.value)]}"</tpl>', '<tpl if="name"> name="{name}"</tpl>', '<tpl if="placeholder"> placeholder="{placeholder}"</tpl>', '<tpl if="size"> size="{size}"</tpl>', '<tpl if="maxLength !== undefined"> maxlength="{maxLength}"</tpl>', '<tpl if="readOnly"> readonly="readonly"</tpl>', '<tpl if="disabled"> disabled="disabled"</tpl>', '<tpl if="tabIdx"> tabIndex="{tabIdx}"</tpl>', '<tpl if="fieldStyle"> style="{fieldStyle}"</tpl>', '/>', { compiled: true, disableFormats: true } ], getSubTplData: function(){ var me = this; Ext.applyIf(me.subTplData, { hiddenDataCls: me.hiddenDataCls }); return me.callParent(arguments); }, afterRender: function(){ var me = this; me.callParent(arguments); me.setHiddenValue(me.value); }, /** * @cfg {Ext.data.Store/String/Array} store * The data source to which this combo is bound. Acceptable values for this property are: * * - **any {@link Ext.data.Store Store} subclass** * - **an {@link Ext.data.Store#storeId ID of a store}** * - **an Array** : Arrays will be converted to a {@link Ext.data.Store} internally, automatically generating * {@link Ext.data.Field#name field names} to work with all data components. * * - **1-dimensional array** : (e.g., `['Foo','Bar']`) * * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo * {@link #valueField} and {@link #displayField}) * * - **2-dimensional array** : (e.g., `[['f','Foo'],['b','Bar']]`) * * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}. * * See also {@link #queryMode}. */ /** * @cfg {Boolean} multiSelect * If set to `true`, allows the combo field to hold more than one value at a time, and allows selecting multiple * items from the dropdown list. The combo's text field will show all selected values separated by the * {@link #delimiter}. */ multiSelect: false, //<locale> /** * @cfg {String} delimiter * The character(s) used to separate the {@link #displayField display values} of multiple selected items when * `{@link #multiSelect} = true`. */ delimiter: ', ', //</locale> /** * @cfg {String} displayField * The underlying {@link Ext.data.Field#name data field name} to bind to this ComboBox. * * See also `{@link #valueField}`. */ displayField: 'text', /** * @cfg {String} valueField (required) * The underlying {@link Ext.data.Field#name data value name} to bind to this ComboBox. * * **Note**: use of a `valueField` requires the user to make a selection in order for a value to be mapped. See also * `{@link #displayField}`. * * Defaults to match the value of the {@link #displayField} config. */ /** * @cfg {String} triggerAction * The action to execute when the trigger is clicked. * * - **`'all'`** : * * {@link #doQuery run the query} specified by the `{@link #allQuery}` config option * * - **`'last'`** : * * {@link #doQuery run the query} using the `{@link #lastQuery last query value}`. * * - **`'query'`** : * * {@link #doQuery run the query} using the {@link Ext.form.field.Base#getRawValue raw value}. * * See also `{@link #queryParam}`. */ triggerAction: 'all', /** * @cfg {String} allQuery * The text query to send to the server to return all records for the list with no filtering */ allQuery: '', /** * @cfg {String} queryParam * Name of the parameter used by the Store to pass the typed string when the ComboBox is configured with * `{@link #queryMode}: 'remote'`. If explicitly set to a falsy value it will not be sent. */ queryParam: 'query', /** * @cfg {String} queryMode * The mode in which the ComboBox uses the configured Store. Acceptable values are: * * - **`'remote'`** : * * In `queryMode: 'remote'`, the ComboBox loads its Store dynamically based upon user interaction. * * This is typically used for "autocomplete" type inputs, and after the user finishes typing, the Store is {@link * Ext.data.Store#method-load load}ed. * * A parameter containing the typed string is sent in the load request. The default parameter name for the input * string is `query`, but this can be configured using the {@link #queryParam} config. * * In `queryMode: 'remote'`, the Store may be configured with `{@link Ext.data.Store#remoteFilter remoteFilter}: * true`, and further filters may be _programatically_ added to the Store which are then passed with every load * request which allows the server to further refine the returned dataset. * * Typically, in an autocomplete situation, {@link #hideTrigger} is configured `true` because it has no meaning for * autocomplete. * * - **`'local'`** : * * ComboBox loads local data * * var combo = new Ext.form.field.ComboBox({ * renderTo: document.body, * queryMode: 'local', * store: new Ext.data.ArrayStore({ * id: 0, * fields: [ * 'myId', // numeric value is the key * 'displayText' * ], * data: [[1, 'item1'], [2, 'item2']] // data is local * }), * valueField: 'myId', * displayField: 'displayText', * triggerAction: 'all' * }); */ queryMode: 'remote', /** * @cfg {Boolean} [queryCaching=true] * When true, this prevents the combo from re-querying (either locally or remotely) when the current query * is the same as the previous query. */ queryCaching: true, /** * @cfg {Number} pageSize * If greater than `0`, a {@link Ext.toolbar.Paging} is displayed in the footer of the dropdown list and the * {@link #doQuery filter queries} will execute with page start and {@link Ext.view.BoundList#pageSize limit} * parameters. Only applies when `{@link #queryMode} = 'remote'`. */ pageSize: 0, /** * @cfg {Number} queryDelay * The length of time in milliseconds to delay between the start of typing and sending the query to filter the * dropdown list. * * Defaults to `500` if `{@link #queryMode} = 'remote'` or `10` if `{@link #queryMode} = 'local'` */ /** * @cfg {Number} minChars * The minimum number of characters the user must type before autocomplete and {@link #typeAhead} activate. * * Defaults to `4` if `{@link #queryMode} = 'remote'` or `0` if `{@link #queryMode} = 'local'`, * does not apply if `{@link Ext.form.field.Trigger#editable editable} = false`. */ /** * @cfg {Boolean} [anyMatch=false] * Configure as `true` to allow match the typed characters at any position in the {@link #valueField}'s value. */ anyMatch: false, /** * @cfg {Boolean} [caseSensitive=false] * Configure as `true` to make the filtering match with exact case matching */ caseSensitive: false, /** * @cfg {Boolean} autoSelect * `true` to automatically highlight the first result gathered by the data store in the dropdown list when it is * opened. A false value would cause nothing in the list to be highlighted automatically, so * the user would have to manually highlight an item before pressing the enter or {@link #selectOnTab tab} key to * select it (unless the value of ({@link #typeAhead}) were true), or use the mouse to select a value. */ autoSelect: true, /** * @cfg {Boolean} typeAhead * `true` to populate and autoselect the remainder of the text being typed after a configurable delay * ({@link #typeAheadDelay}) if it matches a known value. */ typeAhead: false, /** * @cfg {Number} typeAheadDelay * The length of time in milliseconds to wait until the typeahead text is displayed if `{@link #typeAhead} = true` */ typeAheadDelay: 250, /** * @cfg {Boolean} selectOnTab * Whether the Tab key should select the currently highlighted item. */ selectOnTab: true, /** * @cfg {Boolean} forceSelection * `true` to restrict the selected value to one of the values in the list, `false` to allow the user to set * arbitrary text into the field. */ forceSelection: false, /** * @cfg {Boolean} growToLongestValue * `false` to not allow the component to resize itself when its data changes * (and its {@link #grow} property is `true`) */ growToLongestValue: true, /** * @cfg {Boolean} enableRegEx * *When {@link #queryMode} is `'local'` only* * * Set to `true` to have the ComboBox use the typed value as a RegExp source to filter the store to get possible matches. */ /** * @cfg {String} valueNotFoundText * When using a name/value combo, if the value passed to setValue is not found in the store, valueNotFoundText will * be displayed as the field text if defined. If this default text is used, it means there * is no value set and no validation will occur on this field. */ /** * @property {String} lastQuery * The value of the match string used to filter the store. Delete this property to force a requery. Example use: * * var combo = new Ext.form.field.ComboBox({ * ... * queryMode: 'remote', * listeners: { * // delete the previous query in the beforequery event or set * // combo.lastQuery = null (this will reload the store the next time it expands) * beforequery: function(qe){ * delete qe.combo.lastQuery; * } * } * }); * * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used configure the * combo with `lastQuery=''`. Example use: * * var combo = new Ext.form.field.ComboBox({ * ... * queryMode: 'local', * triggerAction: 'all', * lastQuery: '' * }); */ /** * @cfg {Object} defaultListConfig * Set of options that will be used as defaults for the user-configured {@link #listConfig} object. */ defaultListConfig: { loadingHeight: 70, minWidth: 70, maxHeight: 300, shadow: 'sides' }, /** * @cfg {String/HTMLElement/Ext.Element} transform * The id, DOM node or {@link Ext.Element} of an existing HTML `<select>` element to convert into a ComboBox. The * target select's options will be used to build the options in the ComboBox dropdown; a configured {@link #store} * will take precedence over this. */ /** * @cfg {Object} listConfig * An optional set of configuration properties that will be passed to the {@link Ext.view.BoundList}'s constructor. * Any configuration that is valid for BoundList can be included. Some of the more useful ones are: * * - {@link Ext.view.BoundList#cls cls} - defaults to empty * - {@link Ext.view.BoundList#emptyText emptyText} - defaults to empty string * - {@link Ext.view.BoundList#itemSelector itemSelector} - defaults to the value defined in BoundList * - {@link Ext.view.BoundList#loadingText loadingText} - defaults to `'Loading...'` * - {@link Ext.view.BoundList#minWidth minWidth} - defaults to `70` * - {@link Ext.view.BoundList#maxWidth maxWidth} - defaults to `undefined` * - {@link Ext.view.BoundList#maxHeight maxHeight} - defaults to `300` * - {@link Ext.view.BoundList#resizable resizable} - defaults to `false` * - {@link Ext.view.BoundList#shadow shadow} - defaults to `'sides'` * - {@link Ext.view.BoundList#width width} - defaults to `undefined` (automatically set to the width of the ComboBox * field if {@link #matchFieldWidth} is true) * {@link Ext.view.BoundList#getInnerTpl getInnerTpl} A function which returns a template string which renders * the ComboBox's {@link #displayField} value in the dropdown. This defaults to just outputting the raw value, * but may use any {@link Ext.XTemplate XTemplate} methods to produce output. * * The running template is configured with some extra properties that provide some context: * - field {@link Ext.form.field.ComboBox ComboBox} This combobox * - store {@link Ext.data.Store Store} This combobox's data store */ //private ignoreSelection: 0, //private, tells the layout to recalculate its startingWidth when a record is removed from its bound store removingRecords: null, //private helper resizeComboToGrow: function () { var me = this; return me.grow && me.growToLongestValue; }, initComponent: function() { var me = this, isDefined = Ext.isDefined, store = me.store, transform = me.transform, transformSelect, isLocalMode; Ext.applyIf(me.renderSelectors, { hiddenDataEl: '.' + me.hiddenDataCls.split(' ').join('.') }); //<debug> if (me.typeAhead && me.multiSelect) { Ext.Error.raise('typeAhead and multiSelect are mutually exclusive options -- please remove one of them.'); } if (me.typeAhead && !me.editable) { Ext.Error.raise('If typeAhead is enabled the combo must be editable: true -- please change one of those settings.'); } if (me.selectOnFocus && !me.editable) { Ext.Error.raise('If selectOnFocus is enabled the combo must be editable: true -- please change one of those settings.'); } //</debug> this.addEvents( /** * @event beforequery * Fires before all queries are processed. Return false to cancel the query or set the queryPlan's cancel * property to true. * * @param {Object} queryPlan An object containing details about the query to be executed. * @param {Ext.form.field.ComboBox} queryPlan.combo A reference to this ComboBox. * @param {String} queryPlan.query The query value to be used to match against the ComboBox's {@link #valueField}. * @param {Boolean} queryPlan.forceAll If `true`, causes the query to be executed even if the minChars threshold is not met. * @param {Boolean} queryPlan.cancel A boolean value which, if set to `true` upon return, causes the query not to be executed. * @param {Boolean} queryPlan.rawQuery If `true` indicates that the raw input field value is being used, and upon store load, */ 'beforequery', /** * @event select * Fires when at least one list item is selected. * @param {Ext.form.field.ComboBox} combo This combo box * @param {Array} records The selected records */ 'select', /** * @event beforeselect * Fires before the selected item is added to the collection * @param {Ext.form.field.ComboBox} combo This combo box * @param {Ext.data.Record} record The selected record * @param {Number} index The index of the selected record */ 'beforeselect', /** * @event beforedeselect * Fires before the deselected item is removed from the collection * @param {Ext.form.field.ComboBox} combo This combo box * @param {Ext.data.Record} record The deselected record * @param {Number} index The index of the deselected record */ 'beforedeselect' ); // Build store from 'transform' HTML select element's options if (transform) { transformSelect = Ext.getDom(transform); if (transformSelect) { if (!me.store) { store = Ext.Array.map(Ext.Array.from(transformSelect.options), function(option){ return [option.value, option.text]; }); } if (!me.name) { me.name = transformSelect.name; } if (!('value' in me)) { me.value = transformSelect.value; } } } me.bindStore(store || 'ext-empty-store', true); store = me.store; if (store.autoCreated) { me.queryMode = 'local'; me.valueField = me.displayField = 'field1'; if (!store.expanded) { me.displayField = 'field2'; } } if (!isDefined(me.valueField)) { me.valueField = me.displayField; } isLocalMode = me.queryMode === 'local'; if (!isDefined(me.queryDelay)) { me.queryDelay = isLocalMode ? 10 : 500; } if (!isDefined(me.minChars)) { me.minChars = isLocalMode ? 0 : 4; } if (!me.displayTpl) { me.displayTpl = new Ext.XTemplate( '<tpl for=".">' + '{[typeof values === "string" ? values : values["' + me.displayField + '"]]}' + '<tpl if="xindex < xcount">' + me.delimiter + '</tpl>' + '</tpl>' ); } else if (Ext.isString(me.displayTpl)) { me.displayTpl = new Ext.XTemplate(me.displayTpl); } me.callParent(); me.doQueryTask = new Ext.util.DelayedTask(me.doRawQuery, me); // store has already been loaded, setValue if (me.store.getCount() > 0) { me.setValue(me.value); } // render in place of 'transform' select if (transformSelect) { me.render(transformSelect.parentNode, transformSelect); Ext.removeNode(transformSelect); delete me.renderTo; } }, /** * Returns the store associated with this ComboBox. * @return {Ext.data.Store} The store */ getStore : function(){ return this.store; }, beforeBlur: function() { this.doQueryTask.cancel(); this.assertValue(); }, // private assertValue: function() { var me = this, value = me.getRawValue(), rec, currentValue; if (me.forceSelection) { if (me.multiSelect) { // For multiselect, check that the current displayed value matches the current // selection, if it does not then revert to the most recent selection. if (value !== me.getDisplayValue()) { me.setValue(me.lastSelection); } } else { // For single-select, match the displayed value to a record and select it, // if it does not match a record then revert to the most recent selection. rec = me.findRecordByDisplay(value); if (rec) { currentValue = me.value; // Prevent an issue where we have duplicate display values with // different underlying values. if (!me.findRecordByValue(currentValue)) { me.select(rec, true); } } else { me.setValue(me.lastSelection); } } } me.collapse(); }, onTypeAhead: function() { var me = this, displayField = me.displayField, record = me.store.findRecord(displayField, me.getRawValue()), boundList = me.getPicker(), newValue, len, selStart; if (record) { newValue = record.get(displayField); len = newValue.length; selStart = me.getRawValue().length; boundList.highlightItem(boundList.getNode(record)); if (selStart !== 0 && selStart !== len) { me.setRawValue(newValue); me.selectText(selStart, newValue.length); } } }, // invoked when a different store is bound to this combo // than the original resetToDefault: Ext.emptyFn, beforeReset: function() { this.callParent(); // If filtered on typed value, unfilter. if (this.queryFilter && !this.queryFilter.disabled) { this.queryFilter.disabled = true; this.store.filter(); } }, onUnbindStore: function(store) { var me = this, picker = me.picker; // If we'd added a local filter, remove it if (me.queryFilter) { me.store.removeFilter(me.queryFilter); } if (!store && picker) { picker.bindStore(null); } }, onBindStore: function(store, initial) { var picker = this.picker; if (!initial) { this.resetToDefault(); } if (picker) { picker.bindStore(store); } }, getStoreListeners: function() { var me = this; return { beforeload: me.onBeforeLoad, clear: me.onClear, datachanged: me.onDataChanged, load: me.onLoad, exception: me.onException, remove: me.onRemove }; }, onBeforeLoad: function(){ // If we're remote loading, the load mask will show which will trigger a deslectAll. // This selection change will trigger the collapse in onListSelectionChange. As such // we'll veto it for now and restore selection listeners when we've loaded. ++this.ignoreSelection; }, onDataChanged: function() { var me = this; if (me.resizeComboToGrow()) { me.updateLayout(); } }, onClear: function() { var me = this; if (me.resizeComboToGrow()) { me.removingRecords = true; me.onDataChanged(); } }, onRemove: function() { var me = this; if (me.resizeComboToGrow()) { me.removingRecords = true; } }, onException: function(){ if (this.ignoreSelection > 0) { --this.ignoreSelection; } this.collapse(); }, onLoad: function(store, records, success) { var me = this; if (me.ignoreSelection > 0) { --me.ignoreSelection; } // If not querying using the raw field value, we can set the value now we have data if (success && !store.lastOptions.rawQuery) { // Set the value on load // There's no value. if (me.value == null) { // Highlight the first item in the list if autoSelect: true if (me.store.getCount()) { me.doAutoSelect(); } else { // assign whatever empty value we have to prevent change from firing me.setValue(me.value); } } else { me.setValue(me.value); } } }, /** * @private * Execute the query with the raw contents within the textfield. */ doRawQuery: function() { this.doQuery(this.getRawValue(), false, true); }, /** * Executes a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the query * allowing the query action to be canceled if needed. * * @param {String} queryString The string to use to filter available items by matching against the configured {@link #valueField}. * @param {Boolean} [forceAll=false] `true` to force the query to execute even if there are currently fewer characters in * the field than the minimum specified by the `{@link #minChars}` config option. It also clears any filter * previously saved in the current store. * @param {Boolean} [rawQuery=false] Pass as true if the raw typed value is being used as the query string. This causes the * resulting store load to leave the raw value undisturbed. * @return {Boolean} true if the query was permitted to run, false if it was cancelled by a {@link #beforequery} * handler. */ doQuery: function(queryString, forceAll, rawQuery) { var me = this, // Decide if, and how we are going to query the store queryPlan = me.beforeQuery({ query: queryString || '', rawQuery: rawQuery, forceAll: forceAll, combo: me, cancel: false }); // Allow veto. if (queryPlan === false || queryPlan.cancel) { return false; } // If they're using the same value as last time, just show the dropdown if (me.queryCaching && queryPlan.query === me.lastQuery) { me.expand(); } // Otherwise filter or load the store else { me.lastQuery = queryPlan.query; if (me.queryMode === 'local') { me.doLocalQuery(queryPlan); } else { me.doRemoteQuery(queryPlan); } } return true; }, /** * @template * A method which may modify aspects of how the store is to be filtered (if {@link #queryMode} is `"local"`) * of loaded (if {@link #queryMode} is `"remote"`). * * This is called by the {@link #doQuery method, and may be overridden in subclasses to modify * the default behaviour. * * This method is passed an object containing information about the upcoming query operation which it may modify * before returning. * * @param {Object} queryPlan An object containing details about the query to be executed. * @param {String} queryPlan.query The query value to be used to match against the ComboBox's {@link #valueField}. * @param {Boolean} queryPlan.forceAll If `true`, causes the query to be executed even if the minChars threshold is not met. * @param {Boolean} queryPlan.cancel A boolean value which, if set to `true` upon return, causes the query not to be executed. * @param {Boolean} queryPlan.rawQuery If `true` indicates that the raw input field value is being used, and upon store load, * the input field value should **not** be overwritten. * */ beforeQuery: function(queryPlan) { var me = this; // Allow beforequery event to veto by returning false if (me.fireEvent('beforequery', queryPlan) === false) { queryPlan.cancel = true; } // Allow beforequery event to veto by returning setting the cancel flag else if (!queryPlan.cancel) { // If the minChars threshold has not been met, and we're not forcing an "all" query, cancel the query if (queryPlan.query.length < me.minChars && !queryPlan.forceAll) { queryPlan.cancel = true; } } return queryPlan; }, doLocalQuery: function(queryPlan) { var me = this, queryString = queryPlan.query; // Create our filter when first needed if (!me.queryFilter) { // Create the filter that we will use during typing to filter the Store me.queryFilter = new Ext.util.Filter({ id: me.id + '-query-filter', anyMatch: me.anyMatch, caseSensitive: me.caseSensitive, root: 'data', property: me.displayField }); me.store.addFilter(me.queryFilter, false); } // Querying by a string... if (queryString || !queryPlan.forceAll) { me.queryFilter.disabled = false; me.queryFilter.setValue(me.enableRegEx ? new RegExp(queryString) : queryString); } // If forceAll being used, or no query string, disable the filter else { me.queryFilter.disabled = true; } // Filter the Store according to the updated filter me.store.filter(); // Expand after adjusting the filter unless there are no matches if (me.store.getCount()) { me.expand(); } else { me.collapse(); } me.afterQuery(queryPlan); }, doRemoteQuery: function(queryPlan) { var me = this, loadCallback = function() { me.afterQuery(queryPlan); }; // expand before loading so LoadMask can position itself correctly me.expand(); // In queryMode: 'remote', we assume Store filters are added by the developer as remote filters, // and these are automatically passed as params with every load call, so we do *not* call clearFilter. if (me.pageSize) { // if we're paging, we've changed the query so start at page 1. me.loadPage(1, { rawQuery: queryPlan.rawQuery, callback: loadCallback }); } else { me.store.load({ params: me.getParams(queryPlan.query), rawQuery: queryPlan.rawQuery, callback: loadCallback }); } }, /** * @template * A method called when the filtering caused by the {@link #doQuery} call is complete and the store has been * either filtered locally (if {@link #queryMode} is `"local"`), or has been loaded using the specified filtering. * * @param {Object} queryPlan An object containing details about the query was executed. * @param {String} queryPlan.query The query value to be used to match against the ComboBox's {@link #valueField}. * @param {Boolean} queryPlan.forceAll If `true`, causes the query to be executed even if the minChars threshold is not met. * @param {Boolean} queryPlan.cancel A boolean value which, if set to `true` upon return, causes the query not to be executed. * @param {Boolean} queryPlan.rawQuery If `true` indicates that the raw input field value is being used, and upon store load, * the input field value should **not** be overwritten. * */ afterQuery: function(queryPlan) { var me = this; if (me.store.getCount()) { if (me.typeAhead) { me.doTypeAhead(); } // Clear current selection if it does not match the current value in the field if (me.getRawValue() !== me.getDisplayValue()) { me.ignoreSelection++; me.picker.getSelectionModel().deselectAll(); me.ignoreSelection--; } if (queryPlan.rawQuery) { me.syncSelection(); if (me.picker && !me.picker.getSelectionModel().hasSelection()) { me.doAutoSelect(); } } else { me.doAutoSelect(); } } }, loadPage: function(pageNum, options) { this.store.loadPage(pageNum, Ext.apply({ params: this.getParams(this.lastQuery) }, options)); }, onPageChange: function(toolbar, newPage){ /* * Return false here so we can call load ourselves and inject the query param. * We don't want to do this for every store load since the developer may load * the store through some other means so we won't add the query param. */ this.loadPage(newPage); return false; }, // private getParams: function(queryString) { var params = {}, param = this.queryParam; if (param) { params[param] = queryString; } return params; }, /** * @private * If the autoSelect config is true, and the picker is open, highlights the first item. */ doAutoSelect: function() { var me = this, picker = me.picker, lastSelected, itemNode; if (picker && me.autoSelect && me.store.getCount() > 0) { // Highlight the last selected item and scroll it into view lastSelected = picker.getSelectionModel().lastSelected; itemNode = picker.getNode(lastSelected || 0); if (itemNode) { picker.highlightItem(itemNode); picker.listEl.scrollChildIntoView(itemNode, false); } } }, doTypeAhead: function() { if (!this.typeAheadTask) { this.typeAheadTask = new Ext.util.DelayedTask(this.onTypeAhead, this); } if (this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE) { this.typeAheadTask.delay(this.typeAheadDelay); } }, onTriggerClick: function() { var me = this; if (!me.readOnly && !me.disabled) { if (me.isExpanded) { me.collapse(); } else { me.onFocus({}); if (me.triggerAction === 'all') { me.doQuery(me.allQuery, true); } else if (me.triggerAction === 'last') { me.doQuery(me.lastQuery, true); } else { me.doQuery(me.getRawValue(), false, true); } } me.inputEl.focus(); } }, onPaste: function(){ var me = this; if (!me.readOnly && !me.disabled && me.editable) { me.doQueryTask.delay(me.queryDelay); } }, // store the last key and doQuery if relevant onKeyUp: function(e, t) { var me = this, key = e.getKey(); if (!me.readOnly && !me.disabled && me.editable) { me.lastKey = key; // we put this in a task so that we can cancel it if a user is // in and out before the queryDelay elapses // perform query w/ any normal key or backspace or delete if (!e.isSpecialKey() || key == e.BACKSPACE || key == e.DELETE) { me.doQueryTask.delay(me.queryDelay); } } if (me.enableKeyEvents) { me.callParent(arguments); } }, initEvents: function() { var me = this; me.callParent(); /* * Setup keyboard handling. If enableKeyEvents is true, we already have * a listener on the inputEl for keyup, so don't create a second. */ if (!me.enableKeyEvents) { me.mon(me.inputEl, 'keyup', me.onKeyUp, me); } me.mon(me.inputEl, 'paste', me.onPaste, me); }, onDestroy: function() { Ext.destroy(this.listKeyNav); this.bindStore(null); this.callParent(); }, // The picker (the dropdown) must have its zIndex managed by the same ZIndexManager which is // providing the zIndex of our Container. onAdded: function() { var me = this; me.callParent(arguments); if (me.picker) { me.picker.ownerCt = me.up('[floating]'); me.picker.registerWithOwnerCt(); } }, createPicker: function() { var me = this, picker, pickerCfg = Ext.apply({ xtype: 'boundlist', pickerField: me, selModel: { mode: me.multiSelect ? 'SIMPLE' : 'SINGLE' }, floating: true, hidden: true, store: me.store, displayField: me.displayField, focusOnToFront: false, pageSize: me.pageSize, tpl: me.tpl }, me.listConfig, me.defaultListConfig); picker = me.picker = Ext.widget(pickerCfg); if (me.pageSize) { picker.pagingToolbar.on('beforechange', me.onPageChange, me); } me.mon(picker, { itemclick: me.onItemClick, refresh: me.onListRefresh, scope: me }); me.mon(picker.getSelectionModel(), { beforeselect: me.onBeforeSelect, beforedeselect: me.onBeforeDeselect, selectionchange: me.onListSelectionChange, scope: me }); return picker; }, alignPicker: function(){ var me = this, picker = me.getPicker(), heightAbove = me.getPosition()[1] - Ext.getBody().getScroll().top, heightBelow = Ext.Element.getViewHeight() - heightAbove - me.getHeight(), space = Math.max(heightAbove, heightBelow); // Allow the picker to height itself naturally. if (picker.height) { delete picker.height; picker.updateLayout(); } // Then ensure that vertically, the dropdown will fit into the space either above or below the inputEl. if (picker.getHeight() > space - 5) { picker.setHeight(space - 5); // have some leeway so we aren't flush against } me.callParent(); }, onListRefresh: function() { // Picker will be aligned during the expand call if (!this.expanding) { this.alignPicker(); } this.syncSelection(); }, onItemClick: function(picker, record){ /* * If we're doing single selection, the selection change events won't fire when * clicking on the selected element. Detect it here. */ var me = this, selection = me.picker.getSelectionModel().getSelection(), valueField = me.valueField; if (!me.multiSelect && selection.length) { if (record.get(valueField) === selection[0].get(valueField)) { // Make sure we also update the display value if it's only partial me.displayTplData = [record.data]; me.setRawValue(me.getDisplayValue()); me.collapse(); } } }, onBeforeSelect: function(list, record) { return this.fireEvent('beforeselect', this, record, record.index); }, onBeforeDeselect: function(list, record) { return this.fireEvent('beforedeselect', this, record, record.index); }, onListSelectionChange: function(list, selectedRecords) { var me = this, isMulti = me.multiSelect, hasRecords = selectedRecords.length > 0; // Only react to selection if it is not called from setValue, and if our list is // expanded (ignores changes to the selection model triggered elsewhere) if (!me.ignoreSelection && me.isExpanded) { if (!isMulti) { Ext.defer(me.collapse, 1, me); } /* * Only set the value here if we're in multi selection mode or we have * a selection. Otherwise setValue will be called with an empty value * which will cause the change event to fire twice. */ if (isMulti || hasRecords) { me.setValue(selectedRecords, false); } if (hasRecords) { me.fireEvent('select', me, selectedRecords); } me.inputEl.focus(); } }, /** * @private * Enables the key nav for the BoundList when it is expanded. */ onExpand: function() { var me = this, keyNav = me.listKeyNav, selectOnTab = me.selectOnTab, picker = me.getPicker(); // Handle BoundList navigation from the input field. Insert a tab listener specially to enable selectOnTab. if (keyNav) { keyNav.enable(); } else { keyNav = me.listKeyNav = new Ext.view.BoundListKeyNav(this.inputEl, { boundList: picker, forceKeyDown: true, tab: function(e) { if (selectOnTab) { this.selectHighlighted(e); me.triggerBlur(); } // Tab key event is allowed to propagate to field return true; }, enter: function(e){ var selModel = picker.getSelectionModel(), count = selModel.getCount(); this.selectHighlighted(e); // Handle the case where the highlighted item is already selected // In this case, the change event won't fire, so just collapse if (!me.multiSelect && count === selModel.getCount()) { me.collapse(); } } }); } // While list is expanded, stop tab monitoring from Ext.form.field.Trigger so it doesn't short-circuit selectOnTab if (selectOnTab) { me.ignoreMonitorTab = true; } Ext.defer(keyNav.enable, 1, keyNav); //wait a bit so it doesn't react to the down arrow opening the picker me.inputEl.focus(); }, /** * @private * Disables the key nav for the BoundList when it is collapsed. */ onCollapse: function() { var me = this, keyNav = me.listKeyNav; if (keyNav) { keyNav.disable(); me.ignoreMonitorTab = false; } }, /** * Selects an item by a {@link Ext.data.Model Model}, or by a key value. * @param {Object} r */ select: function(r, /* private */ assert) { var me = this, picker = me.picker, doSelect = true, fireSelect; if (r && r.isModel && assert === true && picker) { fireSelect = !picker.getSelectionModel().isSelected(r); } me.setValue(r, true); // Select needs to be fired after setValue, so that when we call getValue // in select it returns the correct value if (fireSelect) { me.fireEvent('select', me, r); } }, /** * Finds the record by searching for a specific field/value combination. * @param {String} field The name of the field to test. * @param {Object} value The value to match the field against. * @return {Ext.data.Model} The matched record or false. */ findRecord: function(field, value) { var ds = this.store, idx = ds.findExact(field, value); return idx !== -1 ? ds.getAt(idx) : false; }, /** * Finds the record by searching values in the {@link #valueField}. * @param {Object} value The value to match the field against. * @return {Ext.data.Model} The matched record or false. */ findRecordByValue: function(value) { return this.findRecord(this.valueField, value); }, /** * Finds the record by searching values in the {@link #displayField}. * @param {Object} value The value to match the field against. * @return {Ext.data.Model} The matched record or false. */ findRecordByDisplay: function(value) { return this.findRecord(this.displayField, value); }, /** * Sets the specified value(s) into the field. For each value, if a record is found in the {@link #store} that * matches based on the {@link #valueField}, then that record's {@link #displayField} will be displayed in the * field. If no match is found, and the {@link #valueNotFoundText} config option is defined, then that will be * displayed as the default field text. Otherwise a blank value will be shown, although the value will still be set. * @param {String/String[]} value The value(s) to be set. Can be either a single String or {@link Ext.data.Model}, * or an Array of Strings or Models. * @return {Ext.form.field.Field} this */ setValue: function(value, doSelect) { var me = this, valueNotFoundText = me.valueNotFoundText, inputEl = me.inputEl, i, len, record, dataObj, matchedRecords = [], displayTplData = [], processedValue = []; if (me.store.loading) { // Called while the Store is loading. Ensure it is processed by the onLoad method. me.value = value; me.setHiddenValue(me.value); return me; } // This method processes multi-values, so ensure value is an array. value = Ext.Array.from(value); // Loop through values, matching each from the Store, and collecting matched records for (i = 0, len = value.length; i < len; i++) { record = value[i]; if (!record || !record.isModel) { record = me.findRecordByValue(record); } // record found, select it. if (record) { matchedRecords.push(record); displayTplData.push(record.data); processedValue.push(record.get(me.valueField)); } // record was not found, this could happen because // store is not loaded or they set a value not in the store else { // If we are allowing insertion of values not represented in the Store, then push the value and // create a fake record data object to push as a display value for use by the displayTpl if (!me.forceSelection) { processedValue.push(value[i]); dataObj = {}; dataObj[me.displayField] = value[i]; displayTplData.push(dataObj); // TODO: Add config to create new records on selection of a value that has no match in the Store } // Else, if valueNotFoundText is defined, display it, otherwise display nothing for this value else if (Ext.isDefined(valueNotFoundText)) { displayTplData.push(valueNotFoundText); } } } // Set the value of this field. If we are multiselecting, then that is an array. me.setHiddenValue(processedValue); me.value = me.multiSelect ? processedValue : processedValue[0]; if (!Ext.isDefined(me.value)) { me.value = null; } me.displayTplData = displayTplData; //store for getDisplayValue method me.lastSelection = me.valueModels = matchedRecords; if (inputEl && me.emptyText && !Ext.isEmpty(value)) { inputEl.removeCls(me.emptyCls); } // Calculate raw value from the collection of Model data me.setRawValue(me.getDisplayValue()); me.checkChange(); if (doSelect !== false) { me.syncSelection(); } me.applyEmptyText(); return me; }, /** * @private * Set the value of {@link #hiddenDataEl} * Dynamically adds and removes input[type=hidden] elements */ setHiddenValue: function(values){ var me = this, name = me.hiddenName, i, dom, childNodes, input, valueCount, childrenCount; if (!me.hiddenDataEl || !name) { return; } values = Ext.Array.from(values); dom = me.hiddenDataEl.dom; childNodes = dom.childNodes; input = childNodes[0]; valueCount = values.length; childrenCount = childNodes.length; if (!input && valueCount > 0) { me.hiddenDataEl.update(Ext.DomHelper.markup({ tag: 'input', type: 'hidden', name: name })); childrenCount = 1; input = dom.firstChild; } while (childrenCount > valueCount) { dom.removeChild(childNodes[0]); -- childrenCount; } while (childrenCount < valueCount) { dom.appendChild(input.cloneNode(true)); ++ childrenCount; } for (i = 0; i < valueCount; i++) { childNodes[i].value = values[i]; } }, /** * @private Generates the string value to be displayed in the text field for the currently stored value */ getDisplayValue: function() { return this.displayTpl.apply(this.displayTplData); }, getValue: function() { // If the user has not changed the raw field value since a value was selected from the list, // then return the structured value from the selection. If the raw field value is different // than what would be displayed due to selection, return that raw value. var me = this, picker = me.picker, rawValue = me.getRawValue(), //current value of text field value = me.value; //stored value from last selection or setValue() call if (me.getDisplayValue() !== rawValue) { value = rawValue; me.value = me.displayTplData = me.valueModels = null; if (picker) { me.ignoreSelection++; picker.getSelectionModel().deselectAll(); me.ignoreSelection--; } } return value; }, getSubmitValue: function() { var value = this.getValue(); // If the value is null/undefined, we still return an empty string. If we // don't, the field will never get posted to the server since nulls are ignored. if (Ext.isEmpty(value)) { value = ''; } return value; }, isEqual: function(v1, v2) { var fromArray = Ext.Array.from, i, len; v1 = fromArray(v1); v2 = fromArray(v2); len = v1.length; if (len !== v2.length) { return false; } for(i = 0; i < len; i++) { if (v2[i] !== v1[i]) { return false; } } return true; }, /** * Clears any value currently set in the ComboBox. */ clearValue: function() { this.setValue([]); }, /** * @private Synchronizes the selection in the picker to match the current value of the combobox. */ syncSelection: function() { var me = this, picker = me.picker, selection, selModel, values = me.valueModels || [], vLen = values.length, v, value; if (picker) { // From the value, find the Models that are in the store's current data selection = []; for (v = 0; v < vLen; v++) { value = values[v]; if (value && value.isModel && me.store.indexOf(value) >= 0) { selection.push(value); } } // Update the selection to match me.ignoreSelection++; selModel = picker.getSelectionModel(); selModel.deselectAll(); if (selection.length) { selModel.select(selection, undefined, true); } me.ignoreSelection--; } }, onEditorTab: function(e){ var keyNav = this.listKeyNav; if (this.selectOnTab && keyNav) { keyNav.selectHighlighted(e); } } });
ajax/libs/yui/3.9.1/scrollview-base/scrollview-base-coverage.js
carlsednaoui/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/scrollview-base/scrollview-base.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/scrollview-base/scrollview-base.js", code: [] }; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].code=["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});"]; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].lines = {"1":0,"11":0,"50":0,"62":0,"63":0,"66":0,"169":0,"172":0,"173":0,"176":0,"177":0,"178":0,"179":0,"180":0,"190":0,"193":0,"194":0,"195":0,"198":0,"201":0,"202":0,"206":0,"207":0,"210":0,"211":0,"214":0,"215":0,"218":0,"219":0,"222":0,"223":0,"238":0,"243":0,"266":0,"270":0,"272":0,"273":0,"286":0,"290":0,"292":0,"293":0,"296":0,"309":0,"314":0,"317":0,"319":0,"331":0,"339":0,"342":0,"347":0,"351":0,"354":0,"357":0,"360":0,"361":0,"375":0,"388":0,"389":0,"390":0,"393":0,"394":0,"396":0,"397":0,"403":0,"405":0,"407":0,"418":0,"432":0,"433":0,"436":0,"437":0,"440":0,"460":0,"464":0,"465":0,"466":0,"467":0,"477":0,"479":0,"501":0,"502":0,"505":0,"515":0,"516":0,"517":0,"519":0,"520":0,"521":0,"524":0,"525":0,"526":0,"529":0,"531":0,"533":0,"537":0,"538":0,"539":0,"544":0,"545":0,"547":0,"548":0,"555":0,"556":0,"558":0,"559":0,"562":0,"563":0,"566":0,"581":0,"583":0,"584":0,"587":0,"600":0,"601":0,"603":0,"604":0,"617":0,"620":0,"621":0,"630":0,"643":0,"644":0,"647":0,"654":0,"655":0,"659":0,"660":0,"661":0,"665":0,"668":0,"708":0,"720":0,"721":0,"724":0,"725":0,"729":0,"730":0,"734":0,"735":0,"737":0,"738":0,"750":0,"757":0,"758":0,"762":0,"763":0,"766":0,"767":0,"770":0,"776":0,"778":0,"781":0,"782":0,"789":0,"790":0,"805":0,"806":0,"809":0,"818":0,"819":0,"823":0,"824":0,"839":0,"867":0,"868":0,"872":0,"875":0,"877":0,"878":0,"882":0,"883":0,"888":0,"895":0,"896":0,"901":0,"903":0,"905":0,"908":0,"921":0,"929":0,"935":0,"938":0,"941":0,"945":0,"947":0,"948":0,"954":0,"957":0,"971":0,"983":0,"994":0,"1007":0,"1008":0,"1010":0,"1011":0,"1014":0,"1026":0,"1027":0,"1030":0,"1037":0,"1040":0,"1041":0,"1042":0,"1045":0,"1046":0,"1049":0,"1050":0,"1052":0,"1063":0,"1075":0,"1086":0,"1097":0,"1108":0,"1119":0,"1121":0,"1122":0,"1143":0,"1144":0,"1164":0,"1165":0,"1168":0,"1180":0,"1192":0}; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].functions = {"_constrain:49":0,"ScrollView:62":0,"initializer:168":0,"bindUI:189":0,"_bindAttrs:237":0,"_bindDrag:265":0,"_bindFlick:285":0,"_bindMousewheel:308":0,"syncUI:330":0,"_getScrollDims:374":0,"_uiDimensionsChange:417":0,"_setBounds:459":0,"_getBounds:476":0,"scrollTo:499":0,"_transform:579":0,"_moveTo:599":0,"_onTransEnd:616":0,"_onGestureMoveStart:641":0,"_onGestureMove:707":0,"_onGestureMoveEnd:749":0,"_flick:804":0,"_flickFrame:837":0,"_cancelFlick:900":0,"_mousewheel:920":0,"_isOutOfBounds:970":0,"_snapBack:993":0,"_afterScrollChange:1025":0,"_afterFlickChange:1062":0,"_afterDisabledChange:1073":0,"_afterAxisChange:1085":0,"_afterDragChange:1096":0,"_afterDimChange:1107":0,"_afterScrollEnd:1118":0,"_axisSetter:1140":0,"_setScroll:1161":0,"_setScrollX:1179":0,"_setScrollY:1191":0,"(anonymous 1):1":0}; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].coveredLines = 223; _yuitest_coverage["build/scrollview-base/scrollview-base.js"].coveredFunctions = 38; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "(anonymous 1)", 1); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 11); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_constrain", 49); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 50); 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 */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 62); function ScrollView() { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "ScrollView", 62); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 63); ScrollView.superclass.constructor.apply(this, arguments); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 66); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "initializer", 168); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 169); var sv = this; // Cache these values, since they aren't going to change. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 172); sv._bb = sv.get(BOUNDING_BOX); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 173); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes _yuitest_coverline("build/scrollview-base/scrollview-base.js", 176); sv._cAxis = sv.get(AXIS); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 177); sv._cBounce = sv.get(BOUNCE); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 178); sv._cBounceRange = sv.get(BOUNCE_RANGE); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 179); sv._cDeceleration = sv.get(DECELERATION); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 180); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "bindUI", 189); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 190); var sv = this; // Bind interaction listers _yuitest_coverline("build/scrollview-base/scrollview-base.js", 193); sv._bindFlick(sv.get(FLICK)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 194); sv._bindDrag(sv.get(DRAG)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 195); sv._bindMousewheel(true); // Bind change events _yuitest_coverline("build/scrollview-base/scrollview-base.js", 198); sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 201); if (IE) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 202); sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties _yuitest_coverline("build/scrollview-base/scrollview-base.js", 206); if (ScrollView.SNAP_DURATION) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 207); sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 210); if (ScrollView.SNAP_EASING) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 211); sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 214); if (ScrollView.EASING) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 215); sv.set(EASING, ScrollView.EASING); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 218); if (ScrollView.FRAME_STEP) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 219); sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 222); if (ScrollView.BOUNCE_RANGE) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 223); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindAttrs", 237); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 238); var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 243); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindDrag", 265); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 266); var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 270); bb.detach(DRAG + '|*'); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 272); if (drag) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 273); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindFlick", 285); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 286); var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners _yuitest_coverline("build/scrollview-base/scrollview-base.js", 290); bb.detach(FLICK + '|*'); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 292); if (flick) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 293); bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick _yuitest_coverline("build/scrollview-base/scrollview-base.js", 296); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_bindMousewheel", 308); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 309); var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 314); bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews _yuitest_coverline("build/scrollview-base/scrollview-base.js", 317); if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 319); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "syncUI", 330); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 331); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 339); if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes _yuitest_coverline("build/scrollview-base/scrollview-base.js", 342); sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 347); sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node _yuitest_coverline("build/scrollview-base/scrollview-base.js", 351); sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value _yuitest_coverline("build/scrollview-base/scrollview-base.js", 354); sv._cDisabled = sv.get(DISABLED); // Run this to set initial values _yuitest_coverline("build/scrollview-base/scrollview-base.js", 357); sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 360); if (sv._isOutOfBounds()) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 361); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_getScrollDims", 374); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 375); 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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 388); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 389); cb.setStyle(TRANS.DURATION, ZERO); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 390); cb.setStyle(TRANS.PROPERTY, EMPTY); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 393); origHWTransform = sv._forceHWTransforms; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 394); sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 396); sv._moveTo(cb, 0, 0); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 397); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 403); sv._moveTo(cb, -(origX), -(origY)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 405); sv._forceHWTransforms = origHWTransform; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 407); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_uiDimensionsChange", 417); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 418); 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); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 432); if (svAxis && svAxis.x) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 433); bb.addClass(CLASS_NAMES.horizontal); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 436); if (svAxis && svAxis.y) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 437); bb.addClass(CLASS_NAMES.vertical); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 440); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setBounds", 459); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 460); var sv = this; // TODO: Do a check to log if the bounds are invalid _yuitest_coverline("build/scrollview-base/scrollview-base.js", 464); sv._minScrollX = bounds.minScrollX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 465); sv._maxScrollX = bounds.maxScrollX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 466); sv._minScrollY = bounds.minScrollY; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 467); sv._maxScrollY = bounds.maxScrollY; }, /** * Get the bounding dimensions of the ScrollView * * @method _getBounds * @protected */ _getBounds: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_getBounds", 476); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 477); var sv = this; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 479); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "scrollTo", 499); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 501); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 502); return; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 505); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 515); duration = duration || 0; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 516); easing = easing || sv.get(EASING); // @TODO: Cache this _yuitest_coverline("build/scrollview-base/scrollview-base.js", 517); node = node || cb; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 519); if (x !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 520); sv.set(SCROLL_X, x, {src:UI}); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 521); newX = -(x); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 524); if (y !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 525); sv.set(SCROLL_Y, y, {src:UI}); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 526); newY = -(y); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 529); transform = sv._transform(newX, newY); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 531); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 533); node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move _yuitest_coverline("build/scrollview-base/scrollview-base.js", 537); if (duration === 0) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 538); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 539); 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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 544); if (x !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 545); node.setStyle(LEFT, newX + PX); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 547); if (y !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 548); node.setStyle(TOP, newY + PX); } } } // Animate else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 555); transition.easing = easing; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 556); transition.duration = duration / 1000; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 558); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 559); transition.transform = transform; } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 562); transition.left = newX + PX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 563); transition.top = newY + PX; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 566); 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? _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_transform", 579); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 581); var prop = 'translate(' + x + 'px, ' + y + 'px)'; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 583); if (this._forceHWTransforms) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 584); prop += ' translateZ(0)'; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 587); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_moveTo", 599); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 600); if (NATIVE_TRANSITIONS) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 601); node.setStyle('transform', this._transform(x, y)); } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 603); node.setStyle(LEFT, x + PX); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 604); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onTransEnd", 616); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 617); var sv = this; // If for some reason we're OOB, snapback _yuitest_coverline("build/scrollview-base/scrollview-base.js", 620); if (sv._isOutOfBounds()) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 621); sv._snapBack(); } else { /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ _yuitest_coverline("build/scrollview-base/scrollview-base.js", 630); sv.fire(EV_SCROLL_END); } }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMoveStart", 641); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 643); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 644); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 647); var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 654); if (sv._prevent.start) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 655); e.preventDefault(); } // if a flick animation is in progress, cancel it _yuitest_coverline("build/scrollview-base/scrollview-base.js", 659); if (sv._flickAnim) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 660); sv._cancelFlick(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 661); sv._onTransEnd(); } // Reset lastScrolledAmt _yuitest_coverline("build/scrollview-base/scrollview-base.js", 665); sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later _yuitest_coverline("build/scrollview-base/scrollview-base.js", 668); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMove", 707); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 708); 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; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 720); if (sv._prevent.move) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 721); e.preventDefault(); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 724); gesture.deltaX = startClientX - clientX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 725); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 729); if (gesture.axis === null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 730); gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 734); if (gesture.axis === DIM_X && svAxisX) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 735); sv.set(SCROLL_X, startX + gesture.deltaX); } else {_yuitest_coverline("build/scrollview-base/scrollview-base.js", 737); if (gesture.axis === DIM_Y && svAxisY) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 738); sv.set(SCROLL_Y, startY + gesture.deltaY); }} }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_onGestureMoveEnd", 749); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 750); var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY, isOOB; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 757); if (sv._prevent.end) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 758); e.preventDefault(); } // Store the end X/Y coordinates _yuitest_coverline("build/scrollview-base/scrollview-base.js", 762); gesture.endClientX = clientX; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 763); gesture.endClientY = clientY; // Cleanup the event handlers _yuitest_coverline("build/scrollview-base/scrollview-base.js", 766); gesture.onGestureMove.detach(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 767); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle _yuitest_coverline("build/scrollview-base/scrollview-base.js", 770); 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) _yuitest_coverline("build/scrollview-base/scrollview-base.js", 776); if (gesture.deltaX !== null && gesture.deltaY !== null) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 778); isOOB = sv._isOutOfBounds(); // If we're out-out-bounds, then snapback _yuitest_coverline("build/scrollview-base/scrollview-base.js", 781); if (isOOB) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 782); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 789); if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 790); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_flick", 804); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 805); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 806); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 809); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 818); if (sv._gesture) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 819); sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis _yuitest_coverline("build/scrollview-base/scrollview-base.js", 823); if (svAxis[flickAxis]) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 824); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_flickFrame", 837); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 839); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 867); if (withinMinRange || withinMaxRange) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 868); newVelocity *= bounce; } // Is the velocity too slow to bother? _yuitest_coverline("build/scrollview-base/scrollview-base.js", 872); tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range _yuitest_coverline("build/scrollview-base/scrollview-base.js", 875); if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim _yuitest_coverline("build/scrollview-base/scrollview-base.js", 877); if (sv._flickAnim) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 878); sv._cancelFlick(); } // If we're inside the scroll area, just end _yuitest_coverline("build/scrollview-base/scrollview-base.js", 882); if (aboveMin && belowMax) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 883); sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 888); sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead _yuitest_coverline("build/scrollview-base/scrollview-base.js", 895); sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 896); sv.set(axisAttr, newPosition); } }, _cancelFlick: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_cancelFlick", 900); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 901); var sv = this; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 903); if (sv._flickAnim) { // Cancel the flick (if it exists) _yuitest_coverline("build/scrollview-base/scrollview-base.js", 905); sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking _yuitest_coverline("build/scrollview-base/scrollview-base.js", 908); delete sv._flickAnim; } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_mousewheel", 920); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 921); 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); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 929); 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. _yuitest_coverline("build/scrollview-base/scrollview-base.js", 935); if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt _yuitest_coverline("build/scrollview-base/scrollview-base.js", 938); sv.lastScrolledAmt = 0; // Jump to the new offset _yuitest_coverline("build/scrollview-base/scrollview-base.js", 941); 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 _yuitest_coverline("build/scrollview-base/scrollview-base.js", 945); if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves _yuitest_coverline("build/scrollview-base/scrollview-base.js", 947); sv.scrollbars._update(); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 948); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event _yuitest_coverline("build/scrollview-base/scrollview-base.js", 954); sv._onTransEnd(); // prevent browser default behavior on mouse scroll _yuitest_coverline("build/scrollview-base/scrollview-base.js", 957); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_isOutOfBounds", 970); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 971); 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; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 983); 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 () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_snapBack", 993); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 994); 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); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1007); if (newX !== currentX) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1008); sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else {_yuitest_coverline("build/scrollview-base/scrollview-base.js", 1010); if (newY !== currentY) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1011); sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1014); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterScrollChange", 1025); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1026); if (e.src === ScrollView.UI_SRC) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1027); return false; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1030); var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1037); sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1040); if (e.attrName === SCROLL_X) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1041); scrollToArgs.push(val); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1042); scrollToArgs.push(sv.get(SCROLL_Y)); } else { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1045); scrollToArgs.push(sv.get(SCROLL_X)); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1046); scrollToArgs.push(val); } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1049); scrollToArgs.push(duration); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1050); scrollToArgs.push(easing); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1052); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterFlickChange", 1062); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1063); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDisabledChange", 1073); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1075); this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterAxisChange", 1085); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1086); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDragChange", 1096); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1097); this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterDimChange", 1107); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1108); this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_afterScrollEnd", 1118); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1119); var sv = this; _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1121); if (sv._flickAnim) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1122); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_axisSetter", 1140); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1143); if (Y.Lang.isString(val)) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1144); 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 _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScroll", 1161); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1164); if (this._cDisabled) { _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1165); val = Y.Attribute.INVALID_VALUE; } _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1168); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScrollX", 1179); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1180); 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) { _yuitest_coverfunc("build/scrollview-base/scrollview-base.js", "_setScrollY", 1191); _yuitest_coverline("build/scrollview-base/scrollview-base.js", 1192); 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});
Examples/UIExplorer/UIExplorerListBase.js
marlonandrade/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; var React = require('react-native'); var { ListView, PixelRatio, StyleSheet, Text, TextInput, TouchableHighlight, View, } = React; var createExamplePage = require('./createExamplePage'); var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2, sectionHeaderHasChanged: (h1, h2) => h1 !== h2, }); class UIExplorerListBase extends React.Component { constructor(props: any) { super(props); this.state = { dataSource: ds.cloneWithRowsAndSections({ components: [], apis: [], }), searchText: this.props.searchText, }; } componentDidMount(): void { this.search(this.state.searchText); } render() { var topView = this.props.renderAdditionalView && this.props.renderAdditionalView(this.renderRow.bind(this), this.renderTextInput.bind(this)); return ( <View style={styles.listContainer}> {topView} <ListView style={styles.list} dataSource={this.state.dataSource} renderRow={this.renderRow.bind(this)} renderSectionHeader={this._renderSectionHeader} keyboardShouldPersistTaps={true} automaticallyAdjustContentInsets={false} keyboardDismissMode="on-drag" /> </View> ); } renderTextInput(searchTextInputStyle: any) { return ( <View style={styles.searchRow}> <TextInput autoCapitalize="none" autoCorrect={false} clearButtonMode="always" onChangeText={this.search.bind(this)} placeholder="Search..." style={[styles.searchTextInput, searchTextInputStyle]} testID="explorer_search" value={this.state.searchText} /> </View> ); } _renderSectionHeader(data: any, section: string) { return ( <View style={styles.sectionHeader}> <Text style={styles.sectionHeaderTitle}> {section.toUpperCase()} </Text> </View> ); } renderRow(example: any, i: number) { return ( <View key={i}> <TouchableHighlight onPress={() => this.onPressRow(example)}> <View style={styles.row}> <Text style={styles.rowTitleText}> {example.title} </Text> <Text style={styles.rowDetailText}> {example.description} </Text> </View> </TouchableHighlight> <View style={styles.separator} /> </View> ); } search(text: mixed): void { this.props.search && this.props.search(text); var regex = new RegExp(text, 'i'); var filter = (component) => regex.test(component.title); this.setState({ dataSource: ds.cloneWithRowsAndSections({ components: this.props.components.filter(filter), apis: this.props.apis.filter(filter), }), searchText: text, }); } onPressRow(example: any): void { this.props.onPressRow && this.props.onPressRow(example); } static makeRenderable(example: any): ReactClass<any, any, any> { return example.examples ? createExamplePage(null, example) : example; } } var styles = StyleSheet.create({ listContainer: { flex: 1, }, list: { backgroundColor: '#eeeeee', }, sectionHeader: { padding: 5, }, group: { backgroundColor: 'white', }, sectionHeaderTitle: { fontWeight: '500', fontSize: 11, }, row: { backgroundColor: 'white', justifyContent: 'center', paddingHorizontal: 15, paddingVertical: 8, }, separator: { height: 1 / PixelRatio.get(), backgroundColor: '#bbbbbb', marginLeft: 15, }, rowTitleText: { fontSize: 17, fontWeight: '500', }, rowDetailText: { fontSize: 15, color: '#888888', lineHeight: 20, }, searchRow: { backgroundColor: '#eeeeee', paddingTop: 75, paddingLeft: 10, paddingRight: 10, paddingBottom: 10, }, searchTextInput: { backgroundColor: 'white', borderColor: '#cccccc', borderRadius: 3, borderWidth: 1, paddingLeft: 8, }, }); module.exports = UIExplorerListBase;
apps/customer/assets/static/js/components/SuggestedItemList/index.js
tsurupin/job_search
import React from 'react'; import { Wrapper, Item } from './styles'; const SuggestedItemList = ({ name, suggestedItems, handleSelect }) => ( <Wrapper> {suggestedItems.map(suggestedItem => ( <Item key={suggestedItem} > <div onMouseDown={() => { handleSelect(name, suggestedItem); }} > {suggestedItem} </div> </Item> )) } </Wrapper> ); export default SuggestedItemList;
ajax/libs/react-bootstrap-typeahead/0.8.3/react-bootstrap-typeahead.js
him2him2/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrapTypeahead"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTypeahead"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Typeahead = __webpack_require__(28); module.exports = Typeahead; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 3 */ /***/ function(module, exports) { "use strict"; /** * KeyCode * * Map of common (non-printable) keycodes for the `keydown` and `keyup` events. * Note that `keypress` handles things differently and may not return the same * values. */ module.exports = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(60); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to search. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 7 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(16); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = Object.keys; /** * The base implementation of `_.keys` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ var baseKeys = overArg(nativeKeys, Object); module.exports = baseKeys; /***/ }, /* 9 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 10 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } module.exports = baseGetTag; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } module.exports = listCacheClear; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(4); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } module.exports = listCacheDelete; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(4); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(4); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(4); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 16 */ /***/ function(module, exports) { /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(54), isFunction = __webpack_require__(19), isLength = __webpack_require__(67); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(44); /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, * else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } module.exports = isEqual; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(20); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 21 */ /***/ function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(39), baseFlatten = __webpack_require__(42), basePick = __webpack_require__(46), baseRest = __webpack_require__(49), toKey = __webpack_require__(59); /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property identifiers to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = baseRest(function(object, props) { return object == null ? {} : basePick(object, arrayMap(baseFlatten(props, 1), toKey)); }); module.exports = pick; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** * A higher-order-component for handling onClickOutside for React components. */ (function(root) { "use strict"; // administrative var registeredComponents = []; var handlers = []; var IGNORE_CLASS = 'ignore-react-onclickoutside'; var DEFAULT_EVENTS = ['mousedown', 'touchstart']; /** * Check whether some DOM node is our Component's node. */ var isNodeFound = function(current, componentNode, ignoreClass) { if (current === componentNode) { return true; } // SVG <use/> elements do not technically reside in the rendered DOM, so // they do not have classList directly, but they offer a link to their // corresponding element, which can have classList. This extra check is for // that case. // See: http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGUseElement // Discussion: https://github.com/Pomax/react-onclickoutside/pull/17 if (current.correspondingElement) { return current.correspondingElement.classList.contains(ignoreClass); } return current.classList.contains(ignoreClass); }; /** * Generate the event handler that checks whether a clicked DOM node * is inside of, or lives outside of, our Component's node tree. */ var generateOutsideCheck = function(componentNode, componentInstance, ignoreClass, preventDefault, stopPropagation) { return function(evt) { if (preventDefault) { evt.preventDefault(); } if (stopPropagation) { evt.stopPropagation(); } var current = evt.target; var found = false; // If source=local then this event came from "somewhere" // inside and should be ignored. We could handle this with // a layered approach, too, but that requires going back to // thinking in terms of Dom node nesting, running counter // to React's "you shouldn't care about the DOM" philosophy. while(current.parentNode) { found = isNodeFound(current, componentNode, ignoreClass); if(found) return; current = current.parentNode; } // If element is in a detached DOM, consider it "not clicked // outside", as it cannot be known whether it was outside. if(current !== document) return; componentInstance.handleClickOutside.bind(componentInstance, evt)(); } }; /** * This function generates the HOC function that you'll use * in order to impart onOutsideClick listening to an * arbitrary component. */ function setupHOC(root, React, ReactDOM) { // The actual Component-wrapping HOC: return function(Component) { var wrapComponentWithOnClickOutsideHandling = React.createClass({ statics: { /** * Access the wrapped Component's class. */ getClass: function() { if (Component.getClass) { return Component.getClass(); } return Component; } }, /** * Access the wrapped Component's instance. */ getInstance: function() { return this.refs.instance; }, // this is given meaning in componentDidMount __outsideClickHandler: function(evt) {}, /** * Add click listeners to the current document, * linked to this component's state. */ componentDidMount: function() { var instance = this.getInstance(); if(typeof instance.handleClickOutside !== "function") { throw new Error("Component lacks a handleClickOutside(event) function for processing outside click events."); } var fn = this.__outsideClickHandler = generateOutsideCheck( ReactDOM.findDOMNode(instance), instance, this.props.outsideClickIgnoreClass || IGNORE_CLASS, this.props.preventDefault || false, this.props.stopPropagation || false ); var pos = registeredComponents.length; registeredComponents.push(this); handlers[pos] = fn; // If there is a truthy disableOnClickOutside property for this // component, don't immediately start listening for outside events. if (!this.props.disableOnClickOutside) { this.enableOnClickOutside(); } }, /** * Track for disableOnClickOutside props changes and enable/disable click outside */ componentWillReceiveProps: function(nextProps) { if (this.props.disableOnClickOutside && !nextProps.disableOnClickOutside) { this.enableOnClickOutside(); } else if (!this.props.disableOnClickOutside && nextProps.disableOnClickOutside) { this.disableOnClickOutside(); } }, /** * Remove the document's event listeners */ componentWillUnmount: function() { this.disableOnClickOutside(); this.__outsideClickHandler = false; var pos = registeredComponents.indexOf(this); if( pos>-1) { // clean up so we don't leak memory if (handlers[pos]) { handlers.splice(pos, 1); } registeredComponents.splice(pos, 1); } }, /** * Can be called to explicitly enable event listening * for clicks and touches outside of this element. */ enableOnClickOutside: function() { var fn = this.__outsideClickHandler; if (typeof document !== "undefined") { var events = this.props.eventTypes || DEFAULT_EVENTS; if (!events.forEach) { events = [events] }; events.forEach(function (eventName) { document.addEventListener(eventName, fn); }); } }, /** * Can be called to explicitly disable event listening * for clicks and touches outside of this element. */ disableOnClickOutside: function() { var fn = this.__outsideClickHandler; if (typeof document !== "undefined") { var events = this.props.eventTypes || DEFAULT_EVENTS; if (!events.forEach) { events = [events] }; events.forEach(function (eventName) { document.removeEventListener(eventName, fn); }); } }, /** * Pass-through render */ render: function() { var passedProps = this.props; var props = { ref: 'instance' }; Object.keys(this.props).forEach(function(key) { props[key] = passedProps[key]; }); return React.createElement(Component, props); } }); // Add display name for React devtools (function bindWrappedComponentName(c, wrapper) { var componentName = c.displayName || c.name || 'Component' wrapper.displayName = 'OnClickOutside(' + componentName + ')'; }(Component, wrapComponentWithOnClickOutsideHandling)); return wrapComponentWithOnClickOutsideHandling; }; } /** * This function sets up the library in ways that * work with the various modulde loading solutions * used in JavaScript land today. */ function setupBinding(root, factory) { if (true) { // AMD. Register as an anonymous module. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(1),__webpack_require__(5)], __WEBPACK_AMD_DEFINE_RESULT__ = function(React, ReactDom) { return factory(root, React, ReactDom); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === 'object') { // Node. Note that this does not work with strict // CommonJS, but only CommonJS-like environments // that support module.exports module.exports = factory(root, require('react'), require('react-dom')); } else { // Browser globals (root is window) root.onClickOutside = factory(root, React, ReactDOM); } } // Make it all happen setupBinding(root, setupHOC); }(this)); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Menu = function Menu(props) { return _react2.default.createElement( 'ul', _extends({}, props, { className: (0, _classnames2.default)('dropdown-menu', props.className) }), props.children ); }; exports.default = Menu; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _noop2 = __webpack_require__(21); var _noop3 = _interopRequireDefault(_noop2); var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _scrollIntoViewIfNeeded = __webpack_require__(32); var _scrollIntoViewIfNeeded2 = _interopRequireDefault(_scrollIntoViewIfNeeded); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MenuItem = _react2.default.createClass({ displayName: 'MenuItem', getDefaultProps: function getDefaultProps() { return { onClick: _noop3.default }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.active) { // Ensures that if the menu items exceed the bounds of the menu, the // menu will scroll up or down as the user hits the arrow keys. (0, _scrollIntoViewIfNeeded2.default)((0, _reactDom.findDOMNode)(this)); } }, render: function render() { var _props = this.props; var active = _props.active; var children = _props.children; var className = _props.className; var disabled = _props.disabled; return _react2.default.createElement( 'li', { className: (0, _classnames2.default)({ 'active': active, 'disabled': disabled }, className) }, _react2.default.createElement( 'a', { href: '#', onClick: this._handleClick }, children ) ); }, _handleClick: function _handleClick(e) { var _props2 = this.props; var disabled = _props2.disabled; var onClick = _props2.onClick; e.preventDefault(); !disabled && onClick(e); } }); exports.default = MenuItem; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _keyCode = __webpack_require__(3); var _keyCode2 = _interopRequireDefault(_keyCode); var _reactOnclickoutside = __webpack_require__(23); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Token * * Individual token component, generally displayed within the TokenizerInput * component, but can also be rendered on its own. */ var Token = _react2.default.createClass({ displayName: 'Token', propTypes: { /** * Handler for removing/deleting the token. If not defined, the token will * be rendered in a read-only state. */ onRemove: _react.PropTypes.func }, getInitialState: function getInitialState() { return { selected: false }; }, render: function render() { return this.props.onRemove && !this.props.disabled ? this._renderRemoveableToken() : this._renderToken(); }, _renderRemoveableToken: function _renderRemoveableToken() { return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('token', 'token-removeable', { 'token-selected': this.state.selected }, this.props.className), onBlur: this._handleBlur, onClick: this._handleSelect, onFocus: this._handleSelect, onKeyDown: this._handleKeyDown, tabIndex: 0 }, this.props.children, _react2.default.createElement( 'span', { className: 'close-button', onClick: this._handleRemove, role: 'button' }, '×' ) ); }, _renderToken: function _renderToken() { var _props = this.props; var className = _props.className; var disabled = _props.disabled; var href = _props.href; var classnames = (0, _classnames2.default)('token', className); if (href) { return _react2.default.createElement( 'a', { className: classnames, disabled: disabled, href: href }, this.props.children ); } return _react2.default.createElement( 'div', { className: classnames, disabled: disabled }, this.props.children ); }, _handleBlur: function _handleBlur(e) { (0, _reactDom.findDOMNode)(this).blur(); this.setState({ selected: false }); }, _handleKeyDown: function _handleKeyDown(e) { switch (e.keyCode) { case _keyCode2.default.BACKSPACE: if (this.state.selected) { // Prevent backspace keypress from triggering the browser "back" // action. e.preventDefault(); this._handleRemove(); } break; } }, /** * From `onClickOutside` mixin. */ handleClickOutside: function handleClickOutside(e) { this._handleBlur(); }, _handleRemove: function _handleRemove(e) { this.props.onRemove && this.props.onRemove(); }, _handleSelect: function _handleSelect(e) { e.stopPropagation(); this.setState({ selected: true }); } }); exports.default = (0, _reactOnclickoutside2.default)(Token); /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reactInputAutosize = __webpack_require__(75); var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Token = __webpack_require__(26); var _Token2 = _interopRequireDefault(_Token); var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _reactDom = __webpack_require__(5); var _keyCode = __webpack_require__(3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * TokenizerInput * * Accepts multiple selections from a Typeahead component and renders them as * tokens within an input. */ var TokenizerInput = _react2.default.createClass({ displayName: 'TokenizerInput', propTypes: { disabled: _react.PropTypes.bool, labelKey: _react.PropTypes.string, placeholder: _react.PropTypes.string, selected: _react.PropTypes.array }, getInitialState: function getInitialState() { return { isFocused: false }; }, render: function render() { var _props = this.props; var disabled = _props.disabled; var placeholder = _props.placeholder; var selected = _props.selected; var text = _props.text; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('bootstrap-tokenizer', 'clearfix', 'form-control', { 'focus': this.state.isFocused }), disabled: disabled, onClick: this._handleInputFocus, onFocus: this._handleInputFocus, style: { cursor: 'text', height: 'auto' }, tabIndex: -1 }, selected.map(this._renderToken), _react2.default.createElement(_reactInputAutosize2.default, { className: 'bootstrap-tokenizer-input', disabled: disabled, inputStyle: { backgroundColor: 'inherit', border: 0, boxShadow: 'none', cursor: 'inherit', outline: 'none', padding: 0 }, onBlur: this._handleBlur, onChange: this._handleChange, onFocus: this.props.onFocus, onKeyDown: this._handleKeydown, placeholder: selected.length ? null : placeholder, ref: 'input', type: 'text', value: text }) ); }, blur: function blur() { this.refs.input.blur(); }, focus: function focus() { this._handleInputFocus(); }, _renderToken: function _renderToken(option, idx) { var _props2 = this.props; var disabled = _props2.disabled; var labelKey = _props2.labelKey; var _onRemove = _props2.onRemove; return _react2.default.createElement( _Token2.default, { disabled: disabled, key: idx, onRemove: function onRemove() { return _onRemove(option); } }, option[labelKey] ); }, _handleBlur: function _handleBlur(e) { this.setState({ isFocused: false }); this.props.onBlur(e); }, _handleChange: function _handleChange(e) { this.props.onChange(e.target.value); }, _handleKeydown: function _handleKeydown(e) { switch (e.keyCode) { case _keyCode.BACKSPACE: var inputNode = (0, _reactDom.findDOMNode)(this.refs.input); if (inputNode && inputNode.contains(document.activeElement) && !this.props.text) { // If the input is selected and there is no text, select the last // token when the user hits backspace. var sibling = inputNode.previousSibling; sibling && sibling.focus(); } break; } this.props.onKeyDown(e); }, _handleInputFocus: function _handleInputFocus(e) { if (this.props.disabled) { e.target.blur(); return; } // If the user clicks anywhere inside the tokenizer besides a token, // focus the input. this.refs.input.focus(); this.setState({ isFocused: true }); } }); exports.default = TokenizerInput; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(22); var _pick3 = _interopRequireDefault(_pick2); var _noop2 = __webpack_require__(21); var _noop3 = _interopRequireDefault(_noop2); var _isEqual2 = __webpack_require__(18); var _isEqual3 = _interopRequireDefault(_isEqual2); var _isEmpty2 = __webpack_require__(66); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _TokenizerInput = __webpack_require__(27); var _TokenizerInput2 = _interopRequireDefault(_TokenizerInput); var _TypeaheadInput = __webpack_require__(29); var _TypeaheadInput2 = _interopRequireDefault(_TypeaheadInput); var _TypeaheadMenu = __webpack_require__(30); var _TypeaheadMenu2 = _interopRequireDefault(_TypeaheadMenu); var _getFilteredOptions = __webpack_require__(31); var _getFilteredOptions2 = _interopRequireDefault(_getFilteredOptions); var _reactOnclickoutside = __webpack_require__(23); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); var _keyCode = __webpack_require__(3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /** * Typeahead */ var Typeahead = _react2.default.createClass({ displayName: 'Typeahead', propTypes: { /** * Specify menu alignment. The default value is `justify`, which makes the * menu as wide as the input and truncates long values. Specifying `left` * or `right` will align the menu to that side and the width will be * determined by the length of menu item values. */ align: _react.PropTypes.oneOf(['justify', 'left', 'right']), /** * Allows the creation of new selections on the fly. Note that any new items * will be added to the list of selections, but not the list of original * options unless handled as such by `Typeahead`'s parent. */ allowNew: _react.PropTypes.bool, /** * Specify any pre-selected options. Use only if you want the component to * be uncontrolled. */ defaultSelected: _react.PropTypes.array, /** * Whether to disable the input. Will also disable selections when * `multiple={true}`. */ disabled: _react.PropTypes.bool, /** * Message to display in the menu if there are no valid results. */ emptyLabel: _react.PropTypes.string, /** * Specify which option key to use for display. By default, the selector * will use the `label` key. */ labelKey: _react.PropTypes.string, /** * Maximum height of the dropdown menu, in px. */ maxHeight: _react.PropTypes.number, /** * Number of input characters that must be entered before showing results. */ minLength: _react.PropTypes.number, /** * Whether or not multiple selections are allowed. */ multiple: _react.PropTypes.bool, /** * Provides the ability to specify a prefix before the user-entered text to * indicate that the selection will be new. No-op unless `allowNew={true}`. */ newSelectionPrefix: _react.PropTypes.string, /** * Callback fired when the input is blurred. Receives an event. */ onBlur: _react.PropTypes.func, /** * Callback fired whenever items are added or removed. Receives an array of * the selected options. */ onChange: _react.PropTypes.func, /** * Callback for handling changes to the user-input text. */ onInputChange: _react.PropTypes.func, /** * Full set of options, including pre-selected options. */ options: _react.PropTypes.array.isRequired, /** * For large option sets, initially display a subset of results for improved * performance. If users scroll to the end, the last item will be a link to * display the next set of results. Value represents the number of results * to display. `0` will display all results. */ paginateResults: _react.PropTypes.number, /** * Prompt displayed when large data sets are paginated. */ paginationText: _react.PropTypes.string, /** * Placeholder text for the input. */ placeholder: _react.PropTypes.string, /** * Provides a hook for customized rendering of menu item contents. */ renderMenuItemChildren: _react.PropTypes.func, /** * The selected option(s) displayed in the input. Use this prop if you want * to control the component via its parent. */ selected: _react.PropTypes.array }, getDefaultProps: function getDefaultProps() { return { allowNew: false, defaultSelected: [], labelKey: 'label', onBlur: _noop3.default, onChange: _noop3.default, onInputChange: _noop3.default, minLength: 0, multiple: false, selected: [] }; }, getInitialState: function getInitialState() { var defaultSelected = this.props.defaultSelected; var selected = this.props.selected.slice(); if (!(0, _isEmpty3.default)(defaultSelected)) { selected = defaultSelected; } return { activeIndex: -1, selected: selected, showMenu: false, text: '' }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var multiple = nextProps.multiple; var selected = nextProps.selected; if (!(0, _isEqual3.default)(selected, this.props.selected)) { // If new selections are passed in via props, treat the component as a // controlled input. this.setState({ selected: selected }); } if (multiple !== this.props.multiple) { this.setState({ text: '' }); } }, render: function render() { var _props = this.props; var options = _props.options; var props = _objectWithoutProperties(_props, ['options']); var _state = this.state; var selected = _state.selected; var text = _state.text; var filteredOptions = (0, _getFilteredOptions2.default)(options, text, selected, props); return _react2.default.createElement( 'div', { className: 'bootstrap-typeahead open', style: { position: 'relative' } }, this._renderInput(filteredOptions), this._renderMenu(filteredOptions) ); }, blur: function blur() { this.refs.input.blur(); }, /** * Public method to allow external clearing of the input. Clears both text * and selection(s). */ clear: function clear() { var _getInitialState = this.getInitialState(); var activeIndex = _getInitialState.activeIndex; var showMenu = _getInitialState.showMenu; var selected = []; var text = ''; this.setState({ activeIndex: activeIndex, selected: selected, showMenu: showMenu, text: text }); this.props.onChange(selected); this.props.onInputChange(text); }, focus: function focus() { this.refs.input.focus(); }, _renderInput: function _renderInput(filteredOptions) { var _this = this; var _props2 = this.props; var labelKey = _props2.labelKey; var multiple = _props2.multiple; var _state2 = this.state; var activeIndex = _state2.activeIndex; var selected = _state2.selected; var text = _state2.text; var Input = multiple ? _TokenizerInput2.default : _TypeaheadInput2.default; var inputProps = (0, _pick3.default)(this.props, ['disabled', 'placeholder']); return _react2.default.createElement(Input, _extends({}, inputProps, { activeIndex: activeIndex, labelKey: labelKey, onAdd: this._handleAddOption, onBlur: this._handleBlur, onChange: this._handleTextChange, onFocus: this._handleFocus, onKeyDown: function onKeyDown(e) { return _this._handleKeydown(filteredOptions, e); }, onRemove: this._handleRemoveOption, options: filteredOptions, ref: 'input', selected: selected.slice(), text: text })); }, _renderMenu: function _renderMenu(filteredOptions) { var _props3 = this.props; var labelKey = _props3.labelKey; var minLength = _props3.minLength; var _state3 = this.state; var activeIndex = _state3.activeIndex; var showMenu = _state3.showMenu; var text = _state3.text; if (!(showMenu && text.length >= minLength)) { return null; } var menuProps = (0, _pick3.default)(this.props, ['align', 'emptyLabel', 'maxHeight', 'newSelectionPrefix', 'paginationText', 'renderMenuItemChildren']); return _react2.default.createElement(_TypeaheadMenu2.default, _extends({}, menuProps, { activeIndex: activeIndex, initialResultCount: this.props.paginateResults, labelKey: labelKey, onClick: this._handleAddOption, options: filteredOptions, text: text })); }, _handleBlur: function _handleBlur(e) { // Note: Don't hide the menu here, since that interferes with other actions // like making a selection by clicking on a menu item. this.props.onBlur(e); }, _handleFocus: function _handleFocus() { this.setState({ showMenu: true }); }, _handleTextChange: function _handleTextChange(text) { var _getInitialState2 = this.getInitialState(); var activeIndex = _getInitialState2.activeIndex; this.setState({ activeIndex: activeIndex, showMenu: true, text: text }); this.props.onInputChange(text); }, _handleKeydown: function _handleKeydown(options, e) { var activeIndex = this.state.activeIndex; switch (e.keyCode) { case _keyCode.UP: case _keyCode.DOWN: // Don't cycle through the options if the menu is hidden. if (!this.state.showMenu) { return; } // Prevents input cursor from going to the beginning when pressing up. e.preventDefault(); // Increment or decrement index based on user keystroke. activeIndex += e.keyCode === _keyCode.UP ? -1 : 1; // If we've reached the end, go back to the beginning or vice-versa. if (activeIndex === options.length) { activeIndex = -1; } else if (activeIndex === -2) { activeIndex = options.length - 1; } this.setState({ activeIndex: activeIndex }); break; case _keyCode.ESC: case _keyCode.TAB: // Prevent closing dialogs. e.keyCode === _keyCode.ESC && e.preventDefault(); this._hideDropdown(); break; case _keyCode.RETURN: // Prevent submitting forms. e.preventDefault(); if (this.state.showMenu) { var selected = options[activeIndex]; selected && this._handleAddOption(selected); } break; } }, _handleAddOption: function _handleAddOption(selectedOption) { var _props4 = this.props; var multiple = _props4.multiple; var labelKey = _props4.labelKey; var onChange = _props4.onChange; var onInputChange = _props4.onInputChange; var selected = void 0; var text = void 0; if (multiple) { // If multiple selections are allowed, add the new selection to the // existing selections. selected = this.state.selected.concat(selectedOption); text = ''; } else { // If only a single selection is allowed, replace the existing selection // with the new one. selected = [selectedOption]; text = selectedOption[labelKey]; } this.setState({ selected: selected, text: text }); this._hideDropdown(); onChange(selected); onInputChange(text); }, _handleRemoveOption: function _handleRemoveOption(removedOption) { var selected = this.state.selected.slice(); selected = selected.filter(function (option) { return !(0, _isEqual3.default)(option, removedOption); }); this.setState({ selected: selected }); this._hideDropdown(); this.props.onChange(selected); }, /** * From `listensToClickOutside` HOC. */ handleClickOutside: function handleClickOutside(e) { this._hideDropdown(); }, _hideDropdown: function _hideDropdown() { var _getInitialState3 = this.getInitialState(); var activeIndex = _getInitialState3.activeIndex; var showMenu = _getInitialState3.showMenu; this.setState({ activeIndex: activeIndex, showMenu: showMenu }); } }); exports.default = (0, _reactOnclickoutside2.default)(Typeahead); /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(22); var _pick3 = _interopRequireDefault(_pick2); var _head2 = __webpack_require__(63); var _head3 = _interopRequireDefault(_head2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _keyCode = __webpack_require__(3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * TypeaheadInput * * Handles a single selection from the Typeahead component. */ var TypeaheadInput = _react2.default.createClass({ displayName: 'TypeaheadInput', propTypes: { disabled: _react.PropTypes.bool, labelKey: _react.PropTypes.string, onBlur: _react.PropTypes.func, onChange: _react.PropTypes.func, onFocus: _react.PropTypes.func, options: _react.PropTypes.array, placeholder: _react.PropTypes.string, selected: _react.PropTypes.array, text: _react.PropTypes.string }, getInitialState: function getInitialState() { return { isFocused: false }; }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { if (this.props.activeIndex !== prevProps.activeIndex) { var inputText = this._getInputText(); this.refs.input.selectionStart = inputText.length; } }, render: function render() { var _props = this.props; var className = _props.className; var disabled = _props.disabled; var selected = _props.selected; var inputProps = (0, _pick3.default)(this.props, ['disabled', 'onFocus', 'placeholder']); return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('bootstrap-typeahead-input', className), onClick: this._handleInputFocus, onFocus: this._handleInputFocus, style: { outline: 'none' }, tabIndex: -1 }, _react2.default.createElement('input', _extends({}, inputProps, { className: (0, _classnames2.default)('bootstrap-typeahead-input-main', 'form-control', { 'has-selection': !!selected.length }), onBlur: this._handleBlur, onChange: this._handleChange, onKeyDown: this._handleKeydown, ref: 'input', style: { backgroundColor: !disabled && 'transparent', display: 'block', position: 'relative', zIndex: 1 }, type: 'text', value: this._getInputText() })), _react2.default.createElement('input', { className: 'bootstrap-typeahead-input-hint form-control', style: { borderColor: 'transparent', bottom: 0, boxShadow: 'none', display: 'block', opacity: 0.6, position: 'absolute', top: 0, width: '100%', zIndex: 0 }, tabIndex: -1, type: 'text', value: this._getHintText() }) ); }, blur: function blur() { this.refs.input.blur(); }, focus: function focus() { this._handleInputFocus(); }, _getHintText: function _getHintText() { var _props2 = this.props; var activeIndex = _props2.activeIndex; var options = _props2.options; var labelKey = _props2.labelKey; var selected = _props2.selected; var text = _props2.text; var firstOption = (0, _head3.default)(options); var firstOptionString = firstOption && firstOption[labelKey]; // Only show the hint if: if ( // The input is focused. this.state.isFocused && // The input contains text. text && // None of the menu options are focused. activeIndex === -1 && // There are no current selections. !selected.length && // The input text corresponds to the beginning of the first option. firstOptionString && firstOptionString.toLowerCase().indexOf(text.toLowerCase()) === 0) { // Text matching is case-insensitive, so to display the hint correctly, // splice the input text with the rest of the actual string. return text + firstOptionString.slice(text.length, firstOptionString.length); } return ''; }, _getInputText: function _getInputText() { var _props3 = this.props; var activeIndex = _props3.activeIndex; var labelKey = _props3.labelKey; var options = _props3.options; var selected = _props3.selected; var text = _props3.text; var selectedItem = !!selected.length && (0, _head3.default)(selected); if (selectedItem) { return selectedItem[labelKey]; } if (activeIndex >= 0) { return options[activeIndex][labelKey]; } return text; }, _handleBlur: function _handleBlur(e) { this.setState({ isFocused: false }); this.props.onBlur(e); }, _handleChange: function _handleChange(e) { // Clear any selections when text is entered. var _props4 = this.props; var onRemove = _props4.onRemove; var selected = _props4.selected; !!selected.length && onRemove((0, _head3.default)(selected)); this.props.onChange(e.target.value); }, /** * If the containing parent div is focused or clicked, focus the input. */ _handleInputFocus: function _handleInputFocus(e) { this.setState({ isFocused: true }); this.refs.input.focus(); }, _handleKeydown: function _handleKeydown(e) { var _props5 = this.props; var activeIndex = _props5.activeIndex; var options = _props5.options; var onAdd = _props5.onAdd; var selected = _props5.selected; var text = _props5.text; switch (e.keyCode) { case _keyCode.RIGHT: case _keyCode.TAB: var cursorPos = this.refs.input.selectionStart; var hasHintText = !!this._getHintText(); // Autocomplete the selection if all of the following are true: if ( // There's a hint or a menu item is highlighted. (hasHintText || activeIndex !== -1) && // There's no current selection. !selected.length && // The input cursor is at the end of the text string when the user // hits the right arrow key. !(e.keyCode === _keyCode.RIGHT && cursorPos !== text.length)) { e.preventDefault(); var selectedOption = hasHintText ? (0, _head3.default)(options) : options[activeIndex]; onAdd && onAdd(selectedOption); } break; } this.props.onKeyDown(e); } }); exports.default = TypeaheadInput; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classnames = __webpack_require__(2); var _classnames2 = _interopRequireDefault(_classnames); var _reactHighlighter = __webpack_require__(73); var _reactHighlighter2 = _interopRequireDefault(_reactHighlighter); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Menu = __webpack_require__(24); var _Menu2 = _interopRequireDefault(_Menu); var _MenuItem = __webpack_require__(25); var _MenuItem2 = _interopRequireDefault(_MenuItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TypeaheadMenu = _react2.default.createClass({ displayName: 'TypeaheadMenu', propTypes: { activeIndex: _react.PropTypes.number, align: _react.PropTypes.oneOf(['justify', 'left', 'right']), emptyLabel: _react.PropTypes.string, initialResultCount: _react.PropTypes.number, labelKey: _react.PropTypes.string.isRequired, maxHeight: _react.PropTypes.number, newSelectionPrefix: _react.PropTypes.string, options: _react.PropTypes.array, paginationText: _react.PropTypes.string, renderMenuItemChildren: _react.PropTypes.func, text: _react.PropTypes.string.isRequired }, getDefaultProps: function getDefaultProps() { return { align: 'justify', emptyLabel: 'No matches found.', initialResultCount: 100, maxHeight: 300, newSelectionPrefix: 'New selection:', paginationText: 'Display additional results...' }; }, getInitialState: function getInitialState() { return { /** * Max number of results to display, for performance reasons. If this * number is less than the number of available results, the user will see * an option to display more results. */ resultCount: this.props.initialResultCount }; }, render: function render() { var _props = this.props; var align = _props.align; var emptyLabel = _props.emptyLabel; var maxHeight = _props.maxHeight; var options = _props.options; // Render the max number of results or all results. var results = options.slice(0, this.state.resultCount || options.length); var menuItems = results.length ? results.map(this._renderMenuItem) : _react2.default.createElement( _MenuItem2.default, { disabled: true }, emptyLabel ); return _react2.default.createElement( _Menu2.default, { className: (0, _classnames2.default)('bootstrap-typeahead-menu', { 'dropdown-menu-justify': align === 'justify', 'dropdown-menu-right': align === 'right' }), style: { maxHeight: maxHeight + 'px', overflow: 'auto' } }, menuItems, this._renderPaginationMenuItem(results) ); }, _renderMenuItem: function _renderMenuItem(option, idx) { var _props2 = this.props; var activeIndex = _props2.activeIndex; var labelKey = _props2.labelKey; var newSelectionPrefix = _props2.newSelectionPrefix; var _onClick = _props2.onClick; var renderMenuItemChildren = _props2.renderMenuItemChildren; var text = _props2.text; var menuItemProps = { active: idx === activeIndex, key: idx, onClick: function onClick() { return _onClick(option); } }; return renderMenuItemChildren ? _react2.default.createElement( _MenuItem2.default, menuItemProps, renderMenuItemChildren(this.props, option, idx) ) : _react2.default.createElement( _MenuItem2.default, menuItemProps, option.customOption && newSelectionPrefix + ' ', _react2.default.createElement( _reactHighlighter2.default, { search: text }, option[labelKey] ) ); }, /** * Allow user to see more results, if available. */ _renderPaginationMenuItem: function _renderPaginationMenuItem(results) { var _props3 = this.props; var options = _props3.options; var paginationText = _props3.paginationText; if (results.length < options.length) { return [_react2.default.createElement('li', { className: 'divider', key: 'pagination-item-divider', role: 'separator' }), _react2.default.createElement( _MenuItem2.default, { className: 'bootstrap-typeahead-menu-paginator', key: 'pagination-item', onClick: this._handlePagination }, paginationText )]; } }, _handlePagination: function _handlePagination(e) { var resultCount = this.state.resultCount + this.props.initialResultCount; this.setState({ resultCount: resultCount }); } }); exports.default = TypeaheadMenu; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _uniqueId2 = __webpack_require__(72); var _uniqueId3 = _interopRequireDefault(_uniqueId2); var _isEqual2 = __webpack_require__(18); var _isEqual3 = _interopRequireDefault(_isEqual2); var _find2 = __webpack_require__(61); var _find3 = _interopRequireDefault(_find2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ function getFilteredOptions() { var options = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; var text = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1]; var selected = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; var props = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; var allowNew = props.allowNew; var labelKey = props.labelKey; var minLength = props.minLength; var multiple = props.multiple; if (text.length < minLength) { return []; } var filteredOptions = options.filter(function (option) { var labelString = option[labelKey]; if (!labelString || typeof labelString !== 'string') { throw new Error('One or more options does not have a valid label string. Please ' + 'check the `labelKey` prop to ensure that it matches the correct ' + 'option key and provides a string for filtering and display.'); } return !(labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && (0, _find3.default)(selected, function (o) { return (0, _isEqual3.default)(o, option); })); }); if (!filteredOptions.length && allowNew && !!text.trim()) { var newOption = { id: (0, _uniqueId3.default)('new-id-'), customOption: true }; newOption[labelKey] = text; filteredOptions = [newOption]; } return filteredOptions; } exports.default = getFilteredOptions; /***/ }, /* 32 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Partial polyfill for webkit `scrollIntoViewIfNeeded()` method. Addresses * vertical scrolling only. * * Inspired by https://gist.github.com/hsablonniere/2581101, but uses * `getBoundingClientRect`. */ function scrollIntoViewIfNeeded(node) { // Webkit browsers if (Element.prototype.scrollIntoViewIfNeeded) { node.scrollIntoViewIfNeeded(); return; } // FF, IE, etc. var rect = node.getBoundingClientRect(); var parent = node.parentNode; var parentRect = parent.getBoundingClientRect(); var parentComputedStyle = window.getComputedStyle(parent, null); var parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')); if (rect.top < parentRect.top || rect.bottom > parentRect.bottom) { parent.scrollTop = node.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + node.clientHeight / 2; } } exports.default = scrollIntoViewIfNeeded; /***/ }, /* 33 */ /***/ function(module, exports) { module.exports = function blacklist (src) { var copy = {} var filter = arguments[1] if (typeof filter === 'string') { filter = {} for (var i = 1; i < arguments.length; i++) { filter[arguments[i]] = true } } for (var key in src) { // blacklist? if (filter[key]) continue copy[key] = src[key] } return copy } /***/ }, /* 34 */ /***/ function(module, exports) { 'use strict'; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; module.exports = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(11), listCacheDelete = __webpack_require__(12), listCacheGet = __webpack_require__(13), listCacheHas = __webpack_require__(14), listCacheSet = __webpack_require__(15); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(35), setCacheAdd = __webpack_require__(57), setCacheHas = __webpack_require__(58); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(11), listCacheDelete = __webpack_require__(12), listCacheGet = __webpack_require__(13), listCacheHas = __webpack_require__(14), listCacheSet = __webpack_require__(15); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 38 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 39 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 40 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 41 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 42 */ /***/ function(module, exports) { /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } module.exports = head; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(55); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, // that are composed entirely of index properties, return `false` for // `hasOwnProperty` checks of them. return object != null && (hasOwnProperty.call(object, key) || (typeof object == 'object' && key in object && getPrototype(object) === null)); } module.exports = baseHas; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(45), isObject = __webpack_require__(20), isObjectLike = __webpack_require__(7); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } module.exports = baseIsEqual; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(37), equalArrays = __webpack_require__(51), equalByTag = __webpack_require__(52), equalObjects = __webpack_require__(53), getTag = __webpack_require__(10), isArray = __webpack_require__(6), isHostObject = __webpack_require__(56), isTypedArray = __webpack_require__(69); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(47); /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} props The property identifiers to pick. * @returns {Object} Returns the new object. */ function basePick(object, props) { object = Object(object); return basePickBy(object, props, function(value, key) { return key in object; }); } module.exports = basePick; /***/ }, /* 47 */ /***/ function(module, exports) { /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} props The property identifiers to pick from. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, props, predicate) { var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (predicate(value, key)) { result[key] = value; } } return result; } module.exports = basePickBy; /***/ }, /* 48 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(38); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } module.exports = baseRest; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(9), isArrayLike = __webpack_require__(17), keys = __webpack_require__(8); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } module.exports = createFind; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(36), arraySome = __webpack_require__(40); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }, /* 52 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(43), keys = __webpack_require__(8); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : baseHas(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(48); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects * Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(16); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetPrototype = Object.getPrototypeOf; /** * Gets the `[[Prototype]]` of `value`. * * @private * @param {*} value The value to query. * @returns {null|Object} Returns the `[[Prototype]]`. */ var getPrototype = overArg(nativeGetPrototype, Object); module.exports = getPrototype; /***/ }, /* 56 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 57 */ /***/ function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }, /* 58 */ /***/ function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }, /* 59 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 60 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var createFind = __webpack_require__(50), findIndex = __webpack_require__(62); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to search. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); module.exports = find; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(41), baseIteratee = __webpack_require__(9), toInteger = __webpack_require__(70); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to search. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } module.exports = findIndex; /***/ }, /* 63 */ /***/ function(module, exports) { /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } module.exports = head; /***/ }, /* 64 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 65 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var getTag = __webpack_require__(10), isArguments = __webpack_require__(64), isArray = __webpack_require__(6), isArrayLike = __webpack_require__(17), isBuffer = __webpack_require__(65), isFunction = __webpack_require__(19), isObjectLike = __webpack_require__(7), isString = __webpack_require__(68), keys = __webpack_require__(8); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf'); /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value) || isBuffer(value))) { return !value.length; } if (isObjectLike(value)) { var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return !(nonEnumShadows && keys(value).length); } module.exports = isEmpty; /***/ }, /* 67 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, * else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(6), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); } module.exports = isString; /***/ }, /* 69 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 70 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 71 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(71); /** Used to generate unique IDs. */ var idCounter = 0; /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } module.exports = uniqueId; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { var React = __webpack_require__(1); var RegExpPropType = __webpack_require__(74); var escapeStringRegexp = __webpack_require__(34); var blacklist = __webpack_require__(33); var Highlighter = React.createClass({displayName: "Highlighter", count: 0, propTypes: { search: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.bool, RegExpPropType ]).isRequired, caseSensitive: React.PropTypes.bool, matchElement: React.PropTypes.string, matchClass: React.PropTypes.string, matchStyle: React.PropTypes.object }, getDefaultProps: function() { return { caseSensitive: false, matchElement: 'strong', matchClass: 'highlight', matchStyle: {} } }, render: function() { var props = blacklist(this.props, 'search', 'caseSensitive', 'matchElement', 'matchClass', 'matchStyle'); return React.createElement('span', props, this.renderElement(this.props.children)); }, /** * A wrapper to the highlight method to determine when the highlighting * process should occur. * * @param {string} subject * The body of text that will be searched for highlighted words. * * @return {Array} * An array of ReactElements */ renderElement: function(subject) { if (this.isScalar() && this.hasSearch()) { var search = this.getSearch(); return this.highlightChildren(subject, search); } return this.props.children; }, /** * Determine if props are valid types for processing. * * @return {Boolean} */ isScalar: function() { return (/string|number|boolean/).test(typeof this.props.children); }, /** * Determine if required search prop is defined and valid. * * @return {Boolean} */ hasSearch: function() { return (typeof this.props.search !== 'undefined') && this.props.search; }, /** * Get the search prop, but always in the form of a regular expression. Use * this as a proxy to this.props.search for consistency. * * @return {RegExp} */ getSearch: function() { if (this.props.search instanceof RegExp) { return this.props.search; } var flags = ''; if (!this.props.caseSensitive) { flags +='i'; } var search = this.props.search; if (typeof this.props.search === 'string') { search = escapeStringRegexp(search); } return new RegExp(search, flags); }, /** * Get the indexes of the first and last characters of the matched string. * * @param {string} subject * The string to search against. * * @param {RegExp} search * The regex search query. * * @return {Object} * An object consisting of "first" and "last" properties representing the * indexes of the first and last characters of a matching string. */ getMatchBoundaries: function(subject, search) { var matches = search.exec(subject); if (matches) { return { first: matches.index, last: matches.index + matches[0].length }; } }, /** * Determines which strings of text should be highlighted or not. * * @param {string} subject * The body of text that will be searched for highlighted words. * @param {string} search * The search used to search for highlighted words. * * @return {Array} * An array of ReactElements */ highlightChildren: function(subject, search) { var children = []; var matchElement = this.props.matchElement; var remaining = subject; while (remaining) { if (!search.test(remaining)) { children.push(this.renderPlain(remaining)); return children; } var boundaries = this.getMatchBoundaries(remaining, search); // Capture the string that leads up to a match... var nonMatch = remaining.slice(0, boundaries.first); if (nonMatch) { children.push(this.renderPlain(nonMatch)); } // Now, capture the matching string... var match = remaining.slice(boundaries.first, boundaries.last); if (match) { children.push(this.renderHighlight(match, matchElement)); } // And if there's anything left over, recursively run this method again. remaining = remaining.slice(boundaries.last); } return children; }, /** * Responsible for rending a non-highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderPlain: function(string) { this.count++; return React.DOM.span({'key': this.count}, string); }, /** * Responsible for rending a highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderHighlight: function(string) { this.count++; return React.DOM[this.props.matchElement]({ key: this.count, className: this.props.matchClass, style: this.props.matchStyle }, string); } }); module.exports = Highlighter; /***/ }, /* 74 */ /***/ function(module, exports) { var regExpPropType = function (props, propName, componentName, location) { if (!(props[propName] instanceof RegExp)) { var propType = typeof props[propName]; return new Error( ("Invalid " + location + " `" + propName + "` of type `" + propType + "` ") + ("supplied to `" + componentName + "`, expected `RegExp`.") ); } }; module.exports = regExpPropType; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(1); var sizerStyle = { position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }; var AutosizeInput = React.createClass({ displayName: 'AutosizeInput', propTypes: { className: React.PropTypes.string, // className for the outer element defaultValue: React.PropTypes.any, // default field value inputClassName: React.PropTypes.string, // className for the input element inputStyle: React.PropTypes.object, // css styles for the input element minWidth: React.PropTypes.oneOfType([// minimum width for input element React.PropTypes.number, React.PropTypes.string]), onChange: React.PropTypes.func, // onChange handler: function(newValue) {} placeholder: React.PropTypes.string, // placeholder text placeholderIsMinWidth: React.PropTypes.bool, // don't collapse size to less than the placeholder style: React.PropTypes.object, // css styles for the outer element value: React.PropTypes.any }, // field value getDefaultProps: function getDefaultProps() { return { minWidth: 1 }; }, getInitialState: function getInitialState() { return { inputWidth: this.props.minWidth }; }, componentDidMount: function componentDidMount() { this.copyInputStyles(); this.updateInputWidth(); }, componentDidUpdate: function componentDidUpdate() { this.updateInputWidth(); }, copyInputStyles: function copyInputStyles() { if (!this.isMounted() || !window.getComputedStyle) { return; } var inputStyle = window.getComputedStyle(this.refs.input); if (!inputStyle) { return; } var widthNode = this.refs.sizer; widthNode.style.fontSize = inputStyle.fontSize; widthNode.style.fontFamily = inputStyle.fontFamily; widthNode.style.fontWeight = inputStyle.fontWeight; widthNode.style.fontStyle = inputStyle.fontStyle; widthNode.style.letterSpacing = inputStyle.letterSpacing; if (this.props.placeholder) { var placeholderNode = this.refs.placeholderSizer; placeholderNode.style.fontSize = inputStyle.fontSize; placeholderNode.style.fontFamily = inputStyle.fontFamily; placeholderNode.style.fontWeight = inputStyle.fontWeight; placeholderNode.style.fontStyle = inputStyle.fontStyle; placeholderNode.style.letterSpacing = inputStyle.letterSpacing; } }, updateInputWidth: function updateInputWidth() { if (!this.isMounted() || typeof this.refs.sizer.scrollWidth === 'undefined') { return; } var newInputWidth = undefined; if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) { newInputWidth = Math.max(this.refs.sizer.scrollWidth, this.refs.placeholderSizer.scrollWidth) + 2; } else { newInputWidth = this.refs.sizer.scrollWidth + 2; } if (newInputWidth < this.props.minWidth) { newInputWidth = this.props.minWidth; } if (newInputWidth !== this.state.inputWidth) { this.setState({ inputWidth: newInputWidth }); } }, getInput: function getInput() { return this.refs.input; }, focus: function focus() { this.refs.input.focus(); }, blur: function blur() { this.refs.input.blur(); }, select: function select() { this.refs.input.select(); }, render: function render() { var sizerValue = this.props.defaultValue || this.props.value || ''; var wrapperStyle = this.props.style || {}; if (!wrapperStyle.display) wrapperStyle.display = 'inline-block'; var inputStyle = _extends({}, this.props.inputStyle); inputStyle.width = this.state.inputWidth + 'px'; inputStyle.boxSizing = 'content-box'; var inputProps = _extends({}, this.props); inputProps.className = this.props.inputClassName; inputProps.style = inputStyle; // ensure props meant for `AutosizeInput` don't end up on the `input` delete inputProps.inputClassName; delete inputProps.inputStyle; delete inputProps.minWidth; delete inputProps.placeholderIsMinWidth; return React.createElement( 'div', { className: this.props.className, style: wrapperStyle }, React.createElement('input', _extends({}, inputProps, { ref: 'input' })), React.createElement( 'div', { ref: 'sizer', style: sizerStyle }, sizerValue ), this.props.placeholder ? React.createElement( 'div', { ref: 'placeholderSizer', style: sizerStyle }, this.props.placeholder ) : null ); } }); module.exports = AutosizeInput; /***/ } /******/ ]) }); ;
node_modules/react-icons/md/code.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdCode = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m24.3 27.7l7.7-7.7-7.7-7.7 2.3-2.3 10 10-10 10z m-8.6 0l-2.3 2.3-10-10 10-10 2.3 2.3-7.7 7.7z"/></g> </Icon> ) export default MdCode
examples/js/remote/remote-store-export-csv.js
echaouchna/react-bootstrap-tab
import React from 'react'; import RemoteExportCSV from './remote-export-csv'; function getProducts() { const products = []; const startId = products.length; for (let i = 0; i < 12; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: Math.floor((Math.random() * 2000) + 1) }); } return products; } export default class RemoteStoreExportCSV extends React.Component { constructor(props) { super(props); this.products = getProducts(); this.state = { data: this.products }; } onExportToCSV() { return this.products; } render() { return ( <RemoteExportCSV onExportToCSV={ this.onExportToCSV.bind(this) } { ...this.state } /> ); } }
example/components/test_named_export_es5.js
RinconStrategies/inspectr
import React from 'react'; class TestComponent extends React.Component { render() { return <div></div>; } } module.exports = { TestComponent: TestComponent };
src/components/iconButton/IconButton.js
sk-iv/iva-app
import React from 'react'; import PropTypes from 'prop-types'; import type { Node } from 'react'; import classNames from 'classnames'; import Clickable from '../Clickable'; import Icon from '../Icon'; import { isMuiElement } from '../utils/reactHelpers'; if(process.env.WEBPACK) require('./IconButton.css'); /** * Refer to the [Icons](/style/icons) section of the documentation * regarding the available icon options. */ function IconButton(props: Props) { const { children, className, color, disabled, rootRef, ...other } = props; return ( <Clickable className={classNames( className, )} centerRipple disabled={disabled} ref={rootRef} {...other} > <span className={''}> {typeof children === 'string' ? ( <Icon className='icon'>{children}</Icon> ) : ( React.Children.map(children, child => { if (isMuiElement(child, ['Icon', 'SvgIcon'])) { return React.cloneElement(child, { className: classNames('icon', child.props.className), }); } return child; }) )} </span> </Clickable> ); } IconButton.propTypes = { /** * The icon element. */ children: PropTypes.node, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']), /** * If `true`, the button will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the ripple will be disabled. */ disableRipple: PropTypes.bool, }; IconButton.defaultProps = { color: 'default', disabled: false, disableRipple: false, }; export default IconButton;
frontend/src/System/Status/DiskSpace/DiskSpaceConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { fetchDiskSpace } from 'Store/Actions/systemActions'; import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; import DiskSpace from './DiskSpace'; function createMapStateToProps() { return createSelector( (state) => state.system.diskSpace, createDimensionsSelector(), (diskSpace, dimensions) => { const { isFetching, items } = diskSpace; return { isFetching, items, isSmallScreen: dimensions.isSmallScreen }; } ); } const mapDispatchToProps = { fetchDiskSpace }; class DiskSpaceConnector extends Component { // // Lifecycle componentDidMount() { this.props.fetchDiskSpace(); } // // Render render() { return ( <DiskSpace {...this.props} /> ); } } DiskSpaceConnector.propTypes = { fetchDiskSpace: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(DiskSpaceConnector);
profiles/bear/modules/contrib/jquery_update/replace/jquery/1.7/jquery.js
sk33lz/bearinstalltest
/*! * jQuery JavaScript Library v1.7.1 * 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: Mon Nov 21 21:11:03 2011 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * 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( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( 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, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { 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 ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, 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 !!memory; } }; return self; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, marginDiv, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = marginDiv = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, conMarginTop, ptlm, vb, style, html, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; vb = "visibility:hidden;border:0;"; style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; html = "<div " + style + "><div></div></div>" + "<table " + style + " cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Figure out if the W3C box model works as expected div.innerHTML = ""; div.style.width = div.style.paddingLeft = "1px"; jQuery.boxModel = support.boxModel = div.offsetWidth === 2; if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.style.cssText = ptlm + vb; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); body.removeChild( container ); div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // 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] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = 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; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, attr, name, data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { attr = this[0].attributes; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } jQuery._data( this[0], "parsedAttrs", true ); } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var self = jQuery( this ), args = [ parts[0], value ]; self.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var 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; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; // See #9699 for explanation of this approach (setting first, then removal) jQuery.attr( elem, name, "" ); elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /\bhover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Determine handlers that should run if there are delegated events // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // 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 && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { // If form was submitted by the user, bubble the event up the tree if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, 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; 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 ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, 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.call( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var 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 ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret === null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ( ret || 0 ); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight, i = 0, len = which.length; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i++ ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i++ ) { val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } } } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css(elem, "display") === "none" ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; 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 ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // 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( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; 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(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Adds width/height step functions // Do not set anything below 0 jQuery.each([ "width", "height" ], function( i, prop ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
stories/textbox.stories.js
socialtables/ST-UI-Toolkit
import React from "react"; import { action } from "@storybook/addon-actions"; import { TextBox } from "../src/index"; import Code from "./lib/Code"; import { propertyNameStyle, propertyDescriptionStyle, storyStyle } from "./style"; import "./css/normalize.css"; import "./css/style.css"; const basicCodeExample = `<TextBox placeholder="Placeholder Text"></TextBox>`; const disabledTextBoxCodeExample = `<TextBox disabled placeholder="Placeholder Text"></TextBox>`; const radiumStylesCodeExample = `<TextBox style={{ base: {background: "orange", color: "black", borderColor: "black"} }}></TextBox>`; export default { title: "TextBox", component: TextBox }; export const TextBoxStory = () => ( <div style={storyStyle}> <h2 style={ {marginTop: 0, marginBottom: 40} }>TextBox</h2> <TextBox placeholder="Placeholder Text"></TextBox> <Code value={ basicCodeExample } style={ {marginTop: 40} } /> <h3>Properties</h3> <table><tbody> <tr> <td style={ propertyNameStyle }> disabled </td> </tr> <tr> <td style={ propertyDescriptionStyle }> <p > <i>Boolean</i> <br /> <b>default:</b> false </p> <p>If true, the button will appear disabled and click handlers will not work</p> </td> </tr> <tr> <td style={ propertyNameStyle }> type </td> </tr> <tr> <td style={ propertyDescriptionStyle }> <ul> <li> <i>String</i>, </li> <li> <b>default:</b> "text", </li> <li> <b>Potential Values:</b> <ul> <li>"datetime"</li> <li>"email"</li> <li>"hidden"</li> <li>"month"</li> <li>"number"</li> <li>"password"</li> <li>"reset"</li> <li>"search"</li> <li>"submit"</li> <li>"tel"</li> <li>"text"</li> <li>"time"</li> <li>"url"</li> <li>"week"</li> </ul> </li> </ul> <p>If an invalid type is passed in, React will throw a warning</p> </td> </tr> <tr> <td style={ propertyNameStyle }> style </td> </tr> <tr> <td style={ propertyDescriptionStyle }> <p> <i>Object</i> <br /> <b>default:</b> See <b>/src/components/TextBox/styles.js</b> file </p> <p>Radium-based inline-style</p> </td> </tr> </tbody></table> <p>Any other property valid for a HTML input like <b>className</b>, …</p> <h3>More Examples</h3> <ul> <li> <h4>Disabled input</h4> <TextBox disabled placeholder="Placeholder Text"></TextBox> <Code value={ disabledTextBoxCodeExample } style={ {marginTop: 20} } /> </li> <li> <h4>Override default Radium styles</h4> <TextBox style={{ base: {background: "orange", color: "black", borderColor: "black"} }}></TextBox> <Code value={ radiumStylesCodeExample } /> </li> </ul> </div> ); TextBoxStory.story = { name: "TextBoxStory" };
src/dir/Contador.js
marcotterra/reactseries
import React from 'react'; export default class Contador extends React.Component { constructor() { super(); this.state = { contador: 0, }; } decrementar() { this.setState({ contador: this.state.contador -1, }); } incrementar() { this.setState({ contador: this.state.contador +1, }); } render() { return ( <div> <h1>{this.state.contador}</h1> <div> <button onClick={this.decrementar.bind(this)}>-</button> <button onClick={this.incrementar.bind(this)}>+</button> </div> </div> ) } }
src/index.js
TarikHuber/react-redux-material-starter-kit
import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import Root from './containers/Root/Root.js' import configureStore from './store/configureStore.js'; var injectTapEventPlugin = require('react-tap-event-plugin'); injectTapEventPlugin(); const store = configureStore(); import '../static/main.css'; import '../node_modules/react-grid-layout/css/styles.css'; import '../node_modules/react-resizable/css/styles.css'; import '../static/favicon.ico'; render(< Root store = { store } history = { history } />, document.getElementById('root'))
docs/app/Examples/collections/Table/Variations/TableExampleSelectableCell.js
shengnian/shengnian-ui-react
import React from 'react' import { Table } from 'shengnian-ui-react' const TableExampleSelectableCell = () => ( <Table celled> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>No Action</Table.Cell> <Table.Cell selectable> <a href='#'>Edit</a> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell selectable> <a href='#'>Edit</a> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell selectable> <a href='#'>Edit</a> </Table.Cell> </Table.Row> <Table.Row warning> <Table.Cell>John</Table.Cell> <Table.Cell>No Action</Table.Cell> <Table.Cell selectable warning> <a href='#'>Requires change</a> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell positive>Approved</Table.Cell> <Table.Cell selectable positive> <a href='#'>Approve</a> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell negative>Denied</Table.Cell> <Table.Cell selectable negative> <a href='#'>Remove</a> </Table.Cell> </Table.Row> </Table.Body> </Table> ) export default TableExampleSelectableCell
step03/App/src/components/Main/index.js
grokbot/intro-to-react-native
import React, { Component } from 'react'; import { Text, View, ScrollView, Image, TouchableHighlight } from 'react-native'; import { Theme } from '../../theme'; import { Loader } from '../Loader'; import Questions from '../Questions'; import Config from "../../config/questions.json"; export default class Main extends Component { constructor(props) { super(props); this.state = { loading: true } } componentDidMount() { setTimeout(()=>{ this.setState({loading: false}); }, 2000); } render() { return ( <View style={[Theme.container, Theme.main]}> <ScrollView style={[Theme.scrollView]}> { this.state.loading ? <View style={[Theme.container, {padding: 40}]}> <Loader /> </View> : <View style={[Theme.container, {paddingTop: 40}]}> <Image source={require("../../assets/strangerthings-title.jpg")} resizeMode="contain" style={[Theme.centered, {height: 250}]} /> <View style={[Theme.content, Theme.centered]}> <Text style={[Theme.text, Theme.title]}>WHICH <Text style={Theme.emphasized}>STRANGER THINGS</Text> CHARACTER ARE YOU?</Text> </View> <View style={[Theme.content, Theme.centered]}> <TouchableHighlight onPress={()=>{this.props.navigator.push({ component: Questions, passProps: { questions: Config.questions, results: Config.results, step: 1, value: 0} }) }} style={Theme.button}> <Text style={Theme.buttonText}>START</Text> </TouchableHighlight> </View> </View> } </ScrollView> </View> ); } }
app/components/shared/Autocomplete/Field/index.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import SearchField from 'app/components/shared/SearchField'; import Suggestion from './suggestion'; import ErrorMessage from 'app/components/shared/Autocomplete/error-message'; const KEYCODE_UP = 38; const KEYCODE_DOWN = 40; const KEYCODE_ENTER = 13; class AutocompleteField extends React.PureComponent { static propTypes = { onSelect: PropTypes.func.isRequired, onSearch: PropTypes.func.isRequired, placeholder: PropTypes.string, items: PropTypes.array }; state = { searching: false, visible: false }; UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.items) { let found = false; if (this.state.selected) { // See if the currently selected value is in the list of new props, but // making sure to skip error message components, since they have no // item id. nextProps.items.forEach((item) => { if (!this.isErrorMessageComponent(item) && item[1].id === this.state.selected.id) { found = true; } }); } // Ah, not found! Then we should just select the first one (if there is // one of course) if (!found && nextProps.items[0]) { this.setState({ selected: nextProps.items[0][1] }); } // We can turn off searching now since we've got some items if (this.state.searching) { this.setState({ searching: false }); } } else { this.setState({ selected: null }); } } clear() { this._searchField.clear(); } focus() { this._searchField.focus(); } selectItem(item) { this.setState({ visible: false }); this._searchField.blur(); this.props.onSelect(item); } isErrorMessageComponent(node) { return node && node.type && node.type.displayName === ErrorMessage.displayName; } render() { return ( <div className="relative"> <SearchField ref={(_searchField) => this._searchField = _searchField} onChange={this.handleSearchChange} onKeyDown={this.handleKeyDown} onFocus={this.handleFocus} onBlur={this.handleBlur} placeholder={this.props.placeholder} searching={this.state.searching} /> {this.renderSuggestions()} </div> ); } renderSuggestions() { const style = { display: this.state.visible ? "block" : "none", marginTop: 3, zIndex: 999, width: "100%", lineHeight: 1.4 }; const items = this.props.items; const suggestions = items.map((item, index) => { if (this.isErrorMessageComponent(item)) { return ( <div key={index}> {item} </div> ); } const isSelected = item[1] && this.state.selected && (item[1].id === this.state.selected.id); // `selected` needs to always return a boolean as it's a requirement of // the Suggestion component return ( <Suggestion key={index} className="rounded" selected={!!isSelected} suggestion={item[1]} onMouseOver={this.handleSuggestionMouseOver} onMouseDown={this.handleSuggestionMouseDown} > {item[0]} </Suggestion> ); }); return ( <div className="bg-white border border-silver rounded shadow absolute" style={style} > <ul className="list-reset m0 p0"> {suggestions} </ul> </div> ); } handleSuggestionMouseDown = (suggestion) => { this.selectItem(suggestion); }; handleSuggestionMouseOver = (suggestion) => { this.setState({ selected: suggestion }); }; handleKeyDown = (evt) => { // Do nothing if the list isn't visible if (!this.state.visible) { return false; } // Do nothing if there are no items if (this.props.items.length === 0) { return false; } // Find the index of the currently selected item let index; for (let itemIndex = 0; itemIndex < this.props.items.length; itemIndex++) { const item = this.props.items[itemIndex]; // Ensure we skip error message nodes since they have no associated // suggestion data if (this.isErrorMessageComponent(item)) { continue; } if (this.state.selected && item[1].id === this.state.selected.id) { index = itemIndex; break; } } // If they've pressed the down key, progress to the next item in the list. if (evt.keyCode === KEYCODE_DOWN) { evt.preventDefault(); let next; if (index == null) { // If there wasn't already a selection, go to the first next = 0; } else { // If the next index doesn't exist, go to the first next = index + 1; if (this.props.items.length === next) { next = 0; } } // Select the next item in the list this.setState({ selected: this.props.items[next][1] }); return; } // If they've pressed the up key, progress to the next item in the list. if (evt.keyCode === KEYCODE_UP) { evt.preventDefault(); let previous; if (index == null) { // If there wasn't already a selection, go to the last previous = this.props.items.length - 1; } else { // If the previous index doesn't exist, go to the last previous = index - 1; if (previous === -1) { previous = this.props.items.length - 1; } } // Select the previous item in the list this.setState({ selected: this.props.items[previous][1] }); return; } // If they've hit enter, select the item if (evt.keyCode === KEYCODE_ENTER) { evt.preventDefault(); this.selectItem(this.state.selected); return; } }; handleFocus = () => { // Only re-show the list if there's something to show if (this.props.items && this.props.items.length > 0) { this.setState({ visible: true }); } }; handleBlur = () => { // Hide the input in a few ms so that the user has time to click a value. // This could probably be done a bit better setTimeout(() => { this.setState({ visible: false }); }, 50); }; handleSearchChange = (value) => { this.props.onSearch(value); this.setState({ searching: true }); }; } AutocompleteField.ErrorMessage = ErrorMessage; export default AutocompleteField;
src/views/components/MediaServiceDetails.js
physiii/home-gateway
import React from 'react'; import PropTypes from 'prop-types'; import {Switch, Redirect, withRouter} from 'react-router-dom'; import {compose} from 'redux'; import {connect} from 'react-redux'; import {doServiceAction} from '../../state/ducks/services-list/operations.js'; import SliderControl from './SliderControl.js'; import {Route} from './Route.js'; import SettingsScreenContainer from './SettingsScreenContainer.js'; import ServiceSettingsScreen from './ServiceSettingsScreen.js'; import './ServiceDetails.css'; export class MediaServiceDetails extends React.Component { constructor (props) { super(props); const volume = this.props.service.state.get('volumeLevel') ? this.props.service.state.get('volumeLevel') : 0; this.state = { coords: [0, 0], diffCoords: [0, 0], prevCoords: [0, 0], startCoords: [0, 0], clickCoords: [0, 0], slider_value: volume }; this.setState(this.state); } handleSliderInput (value) { this.setState({ slider_value: value, is_changing: true }); this.setLevel(value); } setLevel (value) { if (!this.props.service.state.get('connected')) return; this.props.doAction(this.props.service.id, { property: 'setLevel', value }); } handlePress () { this.state.clickCoords = [this.state.clickCoords[0], this.state.clickCoords[1]]; this.setState(this.state); this.sendClickCoordinates(this.state.clickCoords); } handleTouchStart (event) { const xCoord = event.touches[0].clientX, yCoord = event.touches[0].clientY; this.state.prevCoords = [xCoord, yCoord]; this.state.coords = [xCoord, yCoord]; this.setState(this.state); } handleTouchMove (event) { const xCoord = event.touches[0].clientX, yCoord = event.touches[0].clientY; this.state.diffCoords = [parseInt(xCoord - this.state.prevCoords[0]), parseInt(yCoord - this.state.prevCoords[1])]; this.state.prevCoords = this.state.coords; this.state.coords = [xCoord, yCoord]; this.setState(this.state); this.sendCoordinates(this.state.diffCoords); } handleMouseStart (event) { const xCoord = event.touches[0].clientX, yCoord = event.touches[0].clientY; this.state.coords = [xCoord, yCoord]; this.state.prevCoords = [xCoord, yCoord]; this.setState(this.state); } handleMouse (event) { const xCoord = event.clientX - this.state.startCoords[0], yCoord = event.clientY - this.state.startCoords[1]; this.state.diffCoords = [xCoord - this.state.prevCoords[0], yCoord - this.state.prevCoords[1]]; this.state.prevCoords = this.state.coords; this.state.coords = [parseInt(xCoord), parseInt(yCoord)]; // this.sendCoordinates(this.state.coords); this.setState(this.state); } getCoords () { const xCoord = this.state.diffCoords[0], yCoord = this.state.diffCoords[1]; return xCoord + ', ' + yCoord; } sendCoordinates (coords) { // return; if (!this.props.service.state.get('connected')) return; this.props.doAction(this.props.service.id, { property: 'setCoords', value: coords }); } sendClickCoordinates (coords) { // return; if (!this.props.service.state.get('connected')) return; this.props.doAction(this.props.service.id, { property: 'setClickCoords', value: coords }); } render () { const isConnected = this.props.service.state.get('connected'), currentLevel = this.state.slider_value; return ( <Switch> <Route exact path={this.props.match.url} render={() => ( <SettingsScreenContainer section={true}> <div styleName="mousePad" onClick={this.handlePress.bind(this)} onTouchMove={this.handleTouchMove.bind(this)} onTouchStart={this.handleTouchStart.bind(this)} onMouseMove={this.handleMouse.bind(this)} > Mouse Pad </div> <div styleName="sliderMediaDetailsWrapper"> <SliderControl value={currentLevel} onInput={this.handleSliderInput.bind(this)} disabled={!isConnected} /> </div> </SettingsScreenContainer> )} /> <ServiceSettingsScreen service={this.props.service} path={this.props.match.path + MediaServiceDetails.settingsPath} /> <Route render={() => <Redirect to={this.props.match.url} />} /> </Switch> ); } } MediaServiceDetails.settingsPath = '/service-settings'; MediaServiceDetails.propTypes = { service: PropTypes.object.isRequired, children: PropTypes.node, shouldShowSettingsButton: PropTypes.bool, shouldShowRoomField: PropTypes.bool, serviceType: PropTypes.string, match: PropTypes.object, doAction: PropTypes.func }; const mapDispatchToProps = (stateProps, {dispatch}, ownProps) => ({ ...ownProps, ...stateProps, doAction: (serviceId, action) => dispatch(doServiceAction(serviceId, action)) }); export default compose( connect(null, null, mapDispatchToProps), withRouter )(MediaServiceDetails);
client/views/room/Header/DirectRoomHeader.js
VoiSmart/Rocket.Chat
import React from 'react'; import { useUserId } from '../../../contexts/UserContext'; import { useUserData } from '../../../hooks/useUserData'; import RoomHeader from './RoomHeader'; const DirectRoomHeader = ({ room }) => { const userId = useUserId(); const directUserId = room.uids.filter((uid) => uid !== userId).shift(); const directUserData = useUserData(directUserId); return <RoomHeader room={room} topic={directUserData?.statusText} />; }; export default DirectRoomHeader;
examples/async/index.js
koistya/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
poc/src/js/components/Home.js
clplain/poc
import React from 'react'; class Home extends React.Component { render() { return ( <div className='login-form'> <div className='login-content'> <div className='form-login-error'> <h3>DashBoard Login</h3> <p>Enter <strong>Test</strong>/<strong>Test</strong> as login and password.</p> </div> <form method='post' role='form' id='form_login' action='index.html'> <div className='form-group'> <div className='input-group'> <div className='input-group-addon'> <i className='fa fa-user'>username</i> </div> <input type='text' className='form-control' name='username' id='username' placeholder='Username'/> </div> </div> <div className='form-group'> <div className='input-group'> <div className='input-group-addon'> <i className='fa fa-key'>password</i> </div> <input type='password' className='form-control' name='password' id='password' placeholder='Password'/> </div> </div> <div className='form-group'> <button type='button' className='btn btn-primary btn-block btn-login'> <i className='fa fa-sign-in'></i> Login In </button> </div> </form> </div> </div> ); } } export default Home;
internal/EnhancedSwitch.js
myfintech/material-ui
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _simpleAssign = require('simple-assign'); var _simpleAssign2 = _interopRequireDefault(_simpleAssign); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactEventListener = require('react-event-listener'); var _reactEventListener2 = _interopRequireDefault(_reactEventListener); var _keycode = require('keycode'); var _keycode2 = _interopRequireDefault(_keycode); var _transitions = require('../styles/transitions'); var _transitions2 = _interopRequireDefault(_transitions); var _FocusRipple = require('./FocusRipple'); var _FocusRipple2 = _interopRequireDefault(_FocusRipple); var _TouchRipple = require('./TouchRipple'); var _TouchRipple2 = _interopRequireDefault(_TouchRipple); var _Paper = require('./../Paper'); var _Paper2 = _interopRequireDefault(_Paper); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function getStyles(props, context) { var baseTheme = context.muiTheme.baseTheme; return { root: { position: 'relative', cursor: props.disabled ? 'default' : 'pointer', overflow: 'visible', display: 'table', height: 'auto', width: '100%' }, input: { position: 'absolute', cursor: props.disabled ? 'default' : 'pointer', pointerEvents: 'all', opacity: 0, width: '100%', height: '100%', zIndex: 2, left: 0, boxSizing: 'border-box', padding: 0, margin: 0 }, controls: { display: 'flex', width: '100%', height: '100%' }, label: { float: 'left', position: 'relative', display: 'block', width: 'calc(100% - 60px)', lineHeight: '24px', color: baseTheme.palette.textColor, fontFamily: baseTheme.fontFamily }, wrap: { transition: _transitions2.default.easeOut(), float: 'left', position: 'relative', display: 'block', flexShrink: 0, width: 60 - baseTheme.spacing.desktopGutterLess, marginRight: props.labelPosition === 'right' ? baseTheme.spacing.desktopGutterLess : 0, marginLeft: props.labelPosition === 'left' ? baseTheme.spacing.desktopGutterLess : 0 }, ripple: { color: props.rippleColor || baseTheme.palette.primary1Color, height: '200%', width: '200%', top: -12, left: -12 } }; } var EnhancedSwitch = function (_Component) { _inherits(EnhancedSwitch, _Component); function EnhancedSwitch() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, EnhancedSwitch); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(EnhancedSwitch)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { isKeyboardFocused: false }, _this.handleChange = function (event) { _this.tabPressed = false; _this.setState({ isKeyboardFocused: false }); var isInputChecked = _this.refs.checkbox.checked; if (!_this.props.hasOwnProperty('checked') && _this.props.onParentShouldUpdate) { _this.props.onParentShouldUpdate(isInputChecked); } if (_this.props.onSwitch) { _this.props.onSwitch(event, isInputChecked); } }, _this.handleKeyDown = function (event) { var code = (0, _keycode2.default)(event); if (code === 'tab') { _this.tabPressed = true; } if (_this.state.isKeyboardFocused && code === 'space') { _this.handleChange(event); } }, _this.handleKeyUp = function (event) { if (_this.state.isKeyboardFocused && (0, _keycode2.default)(event) === 'space') { _this.handleChange(event); } }, _this.handleMouseDown = function (event) { // only listen to left clicks if (event.button === 0) { _this.refs.touchRipple.start(event); } }, _this.handleMouseUp = function () { _this.refs.touchRipple.end(); }, _this.handleMouseLeave = function () { _this.refs.touchRipple.end(); }, _this.handleTouchStart = function (event) { _this.refs.touchRipple.start(event); }, _this.handleTouchEnd = function () { _this.refs.touchRipple.end(); }, _this.handleBlur = function (event) { _this.setState({ isKeyboardFocused: false }); if (_this.props.onBlur) { _this.props.onBlur(event); } }, _this.handleFocus = function (event) { // setTimeout is needed becuase the focus event fires first // Wait so that we can capture if this was a keyboard focus // or touch focus setTimeout(function () { if (_this.tabPressed) { _this.setState({ isKeyboardFocused: true }); } }, 150); if (_this.props.onFocus) { _this.props.onFocus(event); } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(EnhancedSwitch, [{ key: 'componentDidMount', value: function componentDidMount() { var inputNode = this.refs.checkbox; if ((!this.props.switched || inputNode.checked !== this.props.switched) && this.props.onParentShouldUpdate) { this.props.onParentShouldUpdate(inputNode.checked); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var hasCheckedProp = nextProps.hasOwnProperty('checked'); var hasToggledProp = nextProps.hasOwnProperty('toggled'); var hasNewDefaultProp = nextProps.hasOwnProperty('defaultChecked') && nextProps.defaultChecked !== this.props.defaultChecked; if (hasCheckedProp || hasToggledProp || hasNewDefaultProp) { var switched = nextProps.checked || nextProps.toggled || nextProps.defaultChecked || false; this.setState({ switched: switched }); if (this.props.onParentShouldUpdate && switched !== this.props.switched) { this.props.onParentShouldUpdate(switched); } } } }, { key: 'isSwitched', value: function isSwitched() { return this.refs.checkbox.checked; } // no callback here because there is no event }, { key: 'setSwitched', value: function setSwitched(newSwitchedValue) { if (!this.props.hasOwnProperty('checked') || this.props.checked === false) { if (this.props.onParentShouldUpdate) { this.props.onParentShouldUpdate(newSwitchedValue); } this.refs.checkbox.checked = newSwitchedValue; } else { process.env.NODE_ENV !== "production" ? (0, _warning2.default)(false, 'Cannot call set method while checked is defined as a property.') : void 0; } } }, { key: 'getValue', value: function getValue() { return this.refs.checkbox.value; } // Checkbox inputs only use SPACE to change their state. Using ENTER will // update the ui but not the input. /** * Because both the ripples and the checkbox input cannot share pointer * events, the checkbox input takes control of pointer events and calls * ripple animations manually. */ }, { key: 'render', value: function render() { var _props = this.props; var name = _props.name; var value = _props.value; var iconStyle = _props.iconStyle; var inputStyle = _props.inputStyle; var inputType = _props.inputType; var label = _props.label; var labelStyle = _props.labelStyle; var labelPosition = _props.labelPosition; var onSwitch = _props.onSwitch; var // eslint-disable-line no-unused-vars onBlur = _props.onBlur; var // eslint-disable-line no-unused-vars onFocus = _props.onFocus; var // eslint-disable-line no-unused-vars onMouseUp = _props.onMouseUp; var // eslint-disable-line no-unused-vars onMouseDown = _props.onMouseDown; var // eslint-disable-line no-unused-vars onMouseLeave = _props.onMouseLeave; var // eslint-disable-line no-unused-vars onTouchStart = _props.onTouchStart; var // eslint-disable-line no-unused-vars onTouchEnd = _props.onTouchEnd; var // eslint-disable-line no-unused-vars disabled = _props.disabled; var disableTouchRipple = _props.disableTouchRipple; var disableFocusRipple = _props.disableFocusRipple; var className = _props.className; var rippleStyle = _props.rippleStyle; var style = _props.style; var switched = _props.switched; var // eslint-disable-line no-unused-vars switchElement = _props.switchElement; var thumbStyle = _props.thumbStyle; var trackStyle = _props.trackStyle; var other = _objectWithoutProperties(_props, ['name', 'value', 'iconStyle', 'inputStyle', 'inputType', 'label', 'labelStyle', 'labelPosition', 'onSwitch', 'onBlur', 'onFocus', 'onMouseUp', 'onMouseDown', 'onMouseLeave', 'onTouchStart', 'onTouchEnd', 'disabled', 'disableTouchRipple', 'disableFocusRipple', 'className', 'rippleStyle', 'style', 'switched', 'switchElement', 'thumbStyle', 'trackStyle']); var prepareStyles = this.context.muiTheme.prepareStyles; var styles = getStyles(this.props, this.context); var wrapStyles = (0, _simpleAssign2.default)(styles.wrap, iconStyle); var mergedRippleStyle = (0, _simpleAssign2.default)(styles.ripple, rippleStyle); if (thumbStyle) { wrapStyles.marginLeft /= 2; wrapStyles.marginRight /= 2; } var labelElement = label && _react2.default.createElement( 'label', { style: prepareStyles((0, _simpleAssign2.default)(styles.label, labelStyle)) }, label ); var showTouchRipple = !disabled && !disableTouchRipple; var showFocusRipple = !disabled && !disableFocusRipple; var touchRipple = _react2.default.createElement(_TouchRipple2.default, { ref: 'touchRipple', key: 'touchRipple', style: mergedRippleStyle, color: mergedRippleStyle.color, muiTheme: this.context.muiTheme, centerRipple: true }); var focusRipple = _react2.default.createElement(_FocusRipple2.default, { key: 'focusRipple', innerStyle: mergedRippleStyle, color: mergedRippleStyle.color, muiTheme: this.context.muiTheme, show: this.state.isKeyboardFocused }); var ripples = [showTouchRipple ? touchRipple : null, showFocusRipple ? focusRipple : null]; var inputElement = _react2.default.createElement('input', _extends({}, other, { ref: 'checkbox', type: inputType, style: prepareStyles((0, _simpleAssign2.default)(styles.input, inputStyle)), name: name, value: value, disabled: disabled, onBlur: this.handleBlur, onFocus: this.handleFocus, onChange: this.handleChange, onMouseUp: showTouchRipple && this.handleMouseUp, onMouseDown: showTouchRipple && this.handleMouseDown, onMouseLeave: showTouchRipple && this.handleMouseLeave, onTouchStart: showTouchRipple && this.handleTouchStart, onTouchEnd: showTouchRipple && this.handleTouchEnd })); // If toggle component (indicated by whether the style includes thumb) manually lay out // elements in order to nest ripple elements var switchOrThumbElement = !thumbStyle ? _react2.default.createElement( 'div', { style: prepareStyles(wrapStyles) }, switchElement, ripples ) : _react2.default.createElement( 'div', { style: prepareStyles(wrapStyles) }, _react2.default.createElement('div', { style: prepareStyles((0, _simpleAssign2.default)({}, trackStyle)) }), _react2.default.createElement( _Paper2.default, { style: thumbStyle, zDepth: 1, circle: true }, ' ', ripples, ' ' ) ); var elementsInOrder = labelPosition === 'right' ? _react2.default.createElement( 'div', { style: styles.controls }, switchOrThumbElement, labelElement ) : _react2.default.createElement( 'div', { style: styles.controls }, labelElement, switchOrThumbElement ); return _react2.default.createElement( 'div', { ref: 'root', className: className, style: prepareStyles((0, _simpleAssign2.default)(styles.root, style)) }, _react2.default.createElement(_reactEventListener2.default, { elementName: 'window', onKeyDown: this.handleKeyDown, onKeyUp: this.handleKeyUp }), inputElement, elementsInOrder ); } }]); return EnhancedSwitch; }(_react.Component); EnhancedSwitch.propTypes = { checked: _react.PropTypes.bool, className: _react.PropTypes.string, defaultChecked: _react.PropTypes.bool, disableFocusRipple: _react.PropTypes.bool, disableTouchRipple: _react.PropTypes.bool, disabled: _react.PropTypes.bool, iconStyle: _react.PropTypes.object, inputStyle: _react.PropTypes.object, inputType: _react.PropTypes.string.isRequired, label: _react.PropTypes.node, labelPosition: _react.PropTypes.oneOf(['left', 'right']), labelStyle: _react.PropTypes.object, name: _react.PropTypes.string, onBlur: _react.PropTypes.func, onFocus: _react.PropTypes.func, onMouseDown: _react.PropTypes.func, onMouseLeave: _react.PropTypes.func, onMouseUp: _react.PropTypes.func, onParentShouldUpdate: _react.PropTypes.func, onSwitch: _react.PropTypes.func, onTouchEnd: _react.PropTypes.func, onTouchStart: _react.PropTypes.func, rippleColor: _react.PropTypes.string, rippleStyle: _react.PropTypes.object, style: _react.PropTypes.object, switchElement: _react.PropTypes.element.isRequired, switched: _react.PropTypes.bool.isRequired, thumbStyle: _react.PropTypes.object, trackStyle: _react.PropTypes.object, value: _react.PropTypes.string }; EnhancedSwitch.contextTypes = { muiTheme: _react.PropTypes.object.isRequired }; exports.default = EnhancedSwitch;
consoles/my-joy-instances/src/components/instances/description.js
yldio/joyent-portal
import React from 'react'; import { P as BaseP } from 'joyent-ui-toolkit'; import { Row, Col } from 'joyent-react-styled-flexboxgrid'; import styled from 'styled-components'; const P = styled(BaseP)` font-weight: 200; `; export default ({ href = '', children }) => ( <Row> <Col xs="12" sm="7"> <P> {children}{' '} {href ? ( <a target="__blank" href={href} rel="noopener noreferrer"> Read the docs </a> ) : null} </P> </Col> </Row> );
node_modules/react-icons/io/android-checkbox-outline.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoAndroidCheckboxOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m13.2 16.8l5.2 5.2 14.3-14.3 2.3 2.3-16.6 16.6-7.5-7.5z m18.4 14.8v-13.2h3.4v13.2c0 1.8-1.6 3.4-3.4 3.4h-23.2c-1.8 0-3.4-1.6-3.4-3.4v-23.2c0-1.8 1.6-3.4 3.4-3.4h16.6v3.4h-16.6v23.2h23.2z"/></g> </Icon> ) export default IoAndroidCheckboxOutline
ajax/libs/mobx-react/3.0.3/index.min.js
wout/cdnjs
!function(){function e(e,t,n){function o(e){return n?n.findDOMNode(e):null}function r(e){var t=o(e);t&&p.set(t,e),d.emit({event:"render",renderTime:e.__$mobRenderEnd-e.__$mobRenderStart,totalTime:Date.now()-e.__$mobRenderStart,component:e,node:t})}function i(e,t){var n=e[t],o=u[t];e[t]=function(){n&&n.apply(this,arguments),o.apply(this,arguments)}}function a(e){if("function"==typeof e&&!e.prototype.render&&!e.isReactClass&&!t.Component.isPrototypeOf(e))return a(t.createClass({displayName:e.displayName||e.name,propTypes:e.propTypes,contextTypes:e.contextTypes,getDefaultProps:function(){return e.defaultProps},render:function(){return e.call(this,this.props,this.context)}}));if(!e)throw new Error("Please pass a valid component to 'observer'");var n=e.prototype||e;return["componentWillMount","componentWillUnmount","componentDidMount","componentDidUpdate"].forEach(function(e){i(n,e)}),n.shouldComponentUpdate||(n.shouldComponentUpdate=u.shouldComponentUpdate),e.isMobXReactObserver=!0,e}function s(){if("undefined"==typeof WeakMap)throw new Error("[mobx-react] tracking components is not supported in this browser.");c||(c=!0)}if(!e)throw new Error("mobx-react requires the MobX package");if(!t)throw new Error("mobx-react requires React to be available");var c=!1,p="undefined"!=typeof WeakMap?new WeakMap:void 0,d=new e.SimpleEventEmitter,u={componentWillMount:function(){function n(){return s=new e.Reaction(r,function(){p||(p=!0,t.Component.prototype.forceUpdate.call(a))}),o.$mobx=s,a.render=o,o()}function o(){p=!1;var t;return s.track(function(){c&&(a.__$mobRenderStart=Date.now()),t=e.extras.allowStateChanges(!1,i),c&&(a.__$mobRenderEnd=Date.now())}),t}var r=[this.displayName||this.name||this.constructor&&this.constructor.name||"<component>","#",this._reactInternalInstance&&this._reactInternalInstance._rootNodeID,".render()"].join(""),i=this.render.bind(this),a=this,s=null,p=!1;this.render=n},componentWillUnmount:function(){if(this.render.$mobx&&this.render.$mobx.dispose(),c){var e=o(this);e&&p.delete(e),d.emit({event:"destroy",component:this,node:e})}},componentDidMount:function(){c&&r(this)},componentDidUpdate:function(){c&&r(this)},shouldComponentUpdate:function(t,n){if(this.render.$mobx&&this.render.$mobx.isScheduled()===!0)return!1;if(this.state!==n)return!0;var o,r=Object.keys(this.props);if(r.length!==Object.keys(t).length)return!0;for(var i=r.length-1;o=r[i];i--){var a=t[o];if(a!==this.props[o])return!0;if(a&&"object"==typeof a&&!e.isObservable(a))return!0}return!1}};return{observer:a,reactiveComponent:function(){return console.warn("[mobx-react] `reactiveComponent` has been renamed to `observer` and will be removed in 1.1."),a.apply(null,arguments)},renderReporter:d,componentByNodeRegistery:p,trackComponents:s}}"function"==typeof define&&define.amd?define("mobx-react",["mobx","react","react-dom"],e):"object"==typeof exports?module.exports=e(require("mobx"),require("react"),require("react-dom")):this.mobxReact=e(this.mobx,this.React,this.ReactDOM)}(); //# sourceMappingURL=index.min.js.map
cms/react-static/src/containers/Post.js
fishjar/gabe-study-notes
import React from 'react' import { withRouteData, Link } from 'react-static' // export default withRouteData(({ post }) => ( <div> <Link to="/blog/">{'<'} Back</Link> <br /> <h3>{post.title}</h3> <p>{post.body}</p> </div> ))
node_modules/react-icons/fa/copy.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const FaCopy = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m37.9 8.6q0.9 0 1.5 0.6t0.6 1.5v27.2q0 0.9-0.6 1.5t-1.5 0.6h-21.5q-0.9 0-1.5-0.6t-0.6-1.5v-6.5h-12.2q-0.9 0-1.5-0.6t-0.6-1.5v-15q0-0.9 0.4-2t1.1-1.7l9.1-9.1q0.6-0.6 1.7-1.1t2-0.4h9.3q0.9 0 1.5 0.6t0.6 1.5v7.4q1.5-0.9 2.9-0.9h9.3z m-12.2 4.7l-6.7 6.7h6.7v-6.7z m-14.3-8.5l-6.6 6.6h6.6v-6.6z m4.4 14.4l7.1-7.1v-9.2h-8.6v9.2q0 0.9-0.6 1.6t-1.6 0.6h-9.2v14.3h11.4v-5.7q0-0.9 0.4-2t1.1-1.7z m21.3 17.9v-25.7h-8.5v9.3q0 0.9-0.7 1.5t-1.5 0.7h-9.3v14.2h20z"/></g> </Icon> ) export default FaCopy
docs/app/Examples/elements/Button/GroupVariations/ButtonExampleGroupVertical.js
koenvg/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleGroupVertical = () => ( <Button.Group attached='top' vertical> <Button>Feed</Button> <Button>Messages</Button> <Button>Events</Button> <Button>Photos</Button> </Button.Group> ) export default ButtonExampleGroupVertical
packages/material-ui/src/Stepper/StepLabel.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; import StepIcon from './StepIcon'; export const styles = theme => ({ root: { display: 'flex', alignItems: 'center', '&$alternativeLabel': { flexDirection: 'column', }, '&$disabled': { cursor: 'default', }, }, horizontal: {}, vertical: {}, active: {}, completed: {}, alternativeLabel: {}, error: {}, disabled: {}, label: { color: theme.palette.text.secondary, '&$active': { color: theme.palette.text.primary, fontWeight: 500, }, '&$completed': { color: theme.palette.text.primary, fontWeight: 500, }, '&$alternativeLabel': { textAlign: 'center', marginTop: theme.spacing.unit * 2, }, '&$error': { color: theme.palette.error.main, }, }, iconContainer: { paddingRight: theme.spacing.unit, '&$alternativeLabel': { paddingRight: 0, }, }, labelContainer: { width: '100%', }, }); function StepLabel(props) { const { active, alternativeLabel, children, classes, className: classNameProp, completed, disabled, error, icon, last, optional, orientation, ...other } = props; return ( <span className={classNames( classes.root, classes[orientation], { [classes.disabled]: disabled, [classes.alternativeLabel]: alternativeLabel, [classes.error]: error, }, classNameProp, )} {...other} > {icon && ( <span className={classNames(classes.iconContainer, { [classes.alternativeLabel]: alternativeLabel, })} > <StepIcon completed={completed} active={active} error={error} icon={icon} alternativeLabel={alternativeLabel} /> </span> )} <span className={classes.labelContainer}> <Typography variant="body1" component="span" className={classNames(classes.label, { [classes.alternativeLabel]: alternativeLabel, [classes.completed]: completed, [classes.active]: active, [classes.error]: error, })} > {children} </Typography> {optional} </span> </span> ); } StepLabel.propTypes = { /** * @ignore * Sets the step as active. Is passed to child components. */ active: PropTypes.bool, /** * @ignore * Set internally by Stepper when it's supplied with the alternativeLabel property. */ alternativeLabel: PropTypes.bool, /** * In most cases will simply be a string containing a title for the label. */ children: PropTypes.node, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * @ignore * Mark the step as completed. Is passed to child components. */ completed: PropTypes.bool, /** * Mark the step as disabled, will also disable the button if * `StepLabelButton` is a child of `StepLabel`. Is passed to child components. */ disabled: PropTypes.bool, /** * Mark the step as failed. */ error: PropTypes.bool, /** * Override the default icon. */ icon: PropTypes.node, /** * @ignore */ last: PropTypes.bool, /** * The optional node to display. */ optional: PropTypes.node, /** * @ignore */ orientation: PropTypes.oneOf(['horizontal', 'vertical']), }; StepLabel.defaultProps = { active: false, alternativeLabel: false, completed: false, disabled: false, error: false, last: false, orientation: 'horizontal', }; StepLabel.muiName = 'StepLabel'; export default withStyles(styles, { name: 'MuiStepLabel' })(StepLabel);
bootstrap/1.基本使用/js/jquery.min.js
highmind/Study
/*! jQuery v1.11.2 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.2",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=hb(),z=hb(),A=hb(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},eb=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fb){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function gb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+rb(o[l]);w=ab.test(a)&&pb(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function hb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ib(a){return a[u]=!0,a}function jb(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function kb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function lb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function nb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function ob(a){return ib(function(b){return b=+b,ib(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pb(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=gb.support={},f=gb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=gb.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",eb,!1):e.attachEvent&&e.attachEvent("onunload",eb)),p=!f(g),c.attributes=jb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=jb(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=jb(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(jb(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),jb(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&jb(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return lb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?lb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},gb.matches=function(a,b){return gb(a,null,null,b)},gb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return gb(b,n,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},gb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=gb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=gb.selectors={cacheLength:50,createPseudo:ib,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&gb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=gb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||gb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ib(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ib(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ib(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ib(function(a){return function(b){return gb(a,b).length>0}}),contains:ib(function(a){return a=a.replace(cb,db),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ib(function(a){return W.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:ob(function(){return[0]}),last:ob(function(a,b){return[b-1]}),eq:ob(function(a,b,c){return[0>c?c+b:c]}),even:ob(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:ob(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:ob(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:ob(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=mb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=nb(b);function qb(){}qb.prototype=d.filters=d.pseudos,d.setFilters=new qb,g=gb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?gb.error(a):z(a,i).slice(0)};function rb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function tb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ub(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function vb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wb(a,b,c,d,e,f){return d&&!d[u]&&(d=wb(d)),e&&!e[u]&&(e=wb(e,f)),ib(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ub(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:vb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=vb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=vb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sb(function(a){return a===b},h,!0),l=sb(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sb(tb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wb(i>1&&tb(m),i>1&&rb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xb(a.slice(i,e)),f>e&&xb(a=a.slice(e)),f>e&&rb(a))}m.push(c)}return tb(m)}function yb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=vb(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&gb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ib(f):f}return h=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,yb(e,d)),f.selector=a}return f},i=gb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&pb(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&rb(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&pb(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=jb(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),jb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||kb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&jb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||kb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),jb(function(a){return null==a.getAttribute("disabled")})||kb(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),gb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e) }m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); //# sourceMappingURL=jquery.min.map
node_modules/react-router/es6/Lifecycle.js
HK8383/react_project_imooc
import warning from './routerWarning'; import React from 'react'; import invariant from 'invariant'; var object = React.PropTypes.object; /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ var Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount: function componentDidMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : void 0; !this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : void 0; var route = this.props.route || this.context.route; !route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : void 0; this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave); }, componentWillUnmount: function componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute(); } }; export default Lifecycle;
packages/material-ui-shell/cra-template-material-ui/template/src/pages/FilterDemo/index.js
TarikHuber/react-most-wanted
import AutoSizer from 'react-virtualized-auto-sizer' import { Divider, IconButton, List, ListItem, ListItemText, Toolbar, Typography, } from '@mui/material' import { FilterList } from '@mui/icons-material' import FilterDrawer from 'material-ui-shell/lib/components/FilterDrawer' import Page from 'material-ui-shell/lib/containers/Page' import React, { useEffect, useCallback } from 'react' import SearchField from 'material-ui-shell/lib/components/SearchField' import source from './data.json' import { FixedSizeList } from 'react-window' import { Scrollbars } from 'react-custom-scrollbars-2' import { useFilter } from 'material-ui-shell/lib/providers/Filter' import { useIntl } from 'react-intl' import { useTheme as useAppTheme } from 'material-ui-shell/lib/providers/Theme' const filterName = 'test_filter' const CustomScrollbars = ({ onScroll, forwardedRef, style, children }) => { const { isRTL } = useAppTheme() const refSetter = useCallback((scrollbarsRef) => { if (scrollbarsRef) { forwardedRef(scrollbarsRef.view) } else { forwardedRef(null) } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) return ( <Scrollbars ref={refSetter} renderView={(props) => isRTL ? ( <div {...props} style={{ ...props.style, marginLeft: props.style.marginRight, marginRight: 0, }} /> ) : ( <div {...props} style={{ ...props.style, }} /> ) } // style={{ ...style, overflow: 'hidden' }} style={{ ...style, overflow: 'hidden', direction: isRTL ? 'rtl' : 'ltr' }} //james - test code should fix native scrollbars in demofilter and maybe in RMW demos, onScroll={onScroll} > {children} </Scrollbars> ) } const CustomScrollbarsVirtualList = React.forwardRef((props, ref) => ( <CustomScrollbars {...props} forwardedRef={ref} /> )) const FilterDemo = () => { const intl = useIntl() const { openFilter, getList, getFilter, setSearch } = useFilter() const { queries = [], search = {} } = getFilter(filterName) const { value: searchValue = '' } = search const fields = [ { name: 'name', label: 'Name', }, { name: 'email', label: 'E-Mail', }, { name: 'amount', label: 'Amount', type: 'number', }, { name: 'isActive', label: 'Active', type: 'bool', }, { name: 'registered', label: 'Registered', type: 'date', }, { name: 'registrationTime', label: 'Registration time', type: 'time', }, ] const list = getList(filterName, source, fields) const listRef = React.createRef() useEffect(() => { if (listRef.current) { listRef.current.scrollToItem(1500, 'center') } }, [listRef]) const Row = ({ index, style }) => { const { name, amount = '', registered, email } = list[index] return ( <div key={`${name}_${index}`} style={style}> <ListItem alignItems="flex-start"> <ListItemText primary={`${name} ${index}`} secondary={ <React.Fragment> <Typography component="span" variant="body2" color="textSecondary" > {email} </Typography> <br /> <Typography component="span" variant="body2" color="textSecondary" > {`${amount} ${registered}`} </Typography> </React.Fragment> } /> </ListItem> <Divider /> </div> ) } return ( <Page pageTitle={intl.formatMessage( { id: 'filter_demo', defaultMessage: 'Filter demo with {count} rows', }, { count: list.length } )} contentStyle={{ overflow: 'hidden' }} appBarContent={ <Toolbar disableGutters> <SearchField initialValue={searchValue} onChange={(v) => { setSearch(filterName, v) }} /> <IconButton color="inherit" onClick={() => openFilter(filterName)}> <FilterList color={queries.length > 0 ? 'secondary' : undefined} /> </IconButton> </Toolbar> } > <AutoSizer style={{ height: '100%', width: '100%' }}> {({ height, width }) => { return ( <List disablePadding={true}> <FixedSizeList className="List" ref={listRef} height={height} itemCount={list.length} itemSize={91} width={width} outerElementType={CustomScrollbarsVirtualList} > {Row} </FixedSizeList> </List> ) }} </AutoSizer> <FilterDrawer fields={fields} name={filterName} /> </Page> ) } export default FilterDemo
react/features/video-quality/components/Slider.js
gpolitis/jitsi-meet
// @flow import { makeStyles } from '@material-ui/core/styles'; import clsx from 'clsx'; import React from 'react'; import { commonClassName } from '../../base/ui/constants'; type Props = { /** * The 'aria-label' text. */ ariaLabel: string, /** * The maximum value for slider value. */ max: number, /** * The minimum value for slider value. */ min: number, /** * Callback invoked on change. */ onChange: Function, /** * The granularity that the value must adhere to. */ step: number, /** * The current value where the knob is positioned. */ value: number } const useStyles = makeStyles(theme => { // keep the same hight for all elements: // input, input track & fake track(div) const height = 6; const inputTrack = { background: 'transparent', height }; const inputThumb = { background: theme.palette.text01, border: 0, borderRadius: '50%', height: 24, width: 24 }; const focused = { outline: `1px solid ${theme.palette.action03Focus}` }; return { sliderContainer: { cursor: 'pointer', width: '100%', position: 'relative', textAlign: 'center' }, knobContainer: { display: 'flex', justifyContent: 'space-between', marginLeft: 2, marginRight: 2, position: 'absolute', width: '100%' }, knob: { background: theme.palette.text01, borderRadius: '50%', display: 'inline-block', height, width: 6 }, track: { background: theme.palette.ui02, borderRadius: theme.shape.borderRadius / 2, height }, slider: { // Use an additional class here to override global CSS specificity '&.custom-slider': { '-webkit-appearance': 'none', background: 'transparent', height, left: 0, position: 'absolute', top: 0, width: '100%', '&:focus': { // override global styles in order to use our own color outline: 'none !important', '&::-webkit-slider-runnable-track': focused, '&::ms-track': focused, '&::-moz-range-track': focused }, '&::-webkit-slider-runnable-track': { '-webkit-appearance': 'none', ...inputTrack }, '&::-webkit-slider-thumb': { '-webkit-appearance': 'none', position: 'relative', top: -6, ...inputThumb }, '&::ms-track': { ...inputTrack }, '&::-ms-thumb': { ...inputThumb }, '&::-moz-range-track': { ...inputTrack }, '&::-moz-range-thumb': { ...inputThumb } } } }; }); /** * Custom slider. * * @returns {ReactElement} */ function Slider({ ariaLabel, max, min, onChange, step, value }: Props) { const classes = useStyles(); const knobs = [ ...Array(Math.floor((max - min) / step) + 1) ]; return ( <div className = { classes.sliderContainer }> <ul className = { clsx(commonClassName.emptyList, classes.knobContainer) }> {knobs.map((_, i) => ( <li className = { classes.knob } key = { `knob-${i}` } />))} </ul> <div className = { classes.track } /> <input aria-label = { ariaLabel } className = { clsx(classes.slider, 'custom-slider') } max = { max } min = { min } onChange = { onChange } step = { step } type = 'range' value = { value } /> </div> ); } export default Slider;
app/addons/activetasks/components/controller.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import ActiveTasksFilterTabs from './filtertabs'; import ActiveTaskTable from './table'; export default class ActiveTasksController extends React.Component { componentDidMount() { this.props.init(); } setNewSearchTerm = (searchTerm) => { this.props.setSearchTerm(searchTerm); }; switchTab = (newRadioButton) => { //tabs buttons this.props.switchTab(newRadioButton); }; tableHeaderOnClick = (headerClicked) => { this.props.sortByColumnHeader(headerClicked); }; render() { const {isLoading, tasks, searchTerm, selectedRadio, sortByHeader, headerIsAscending} = this.props; const setSearchTerm = this.setNewSearchTerm; const onTableHeaderClick = this.tableHeaderOnClick; return ( <div id="active-tasks-page" className="scrollable"> <div className="inner"> <ActiveTasksFilterTabs searchTerm={searchTerm} selectedRadio={selectedRadio} onSearch={setSearchTerm} onRadioClick={this.switchTab}/> <ActiveTaskTable isLoading={isLoading} tasks={tasks} searchTerm={searchTerm} selectedRadio={selectedRadio} onTableHeaderClick={onTableHeaderClick} sortByHeader={sortByHeader} headerIsAscending={headerIsAscending} /> </div> </div> ); } }
20161122/src/js/routes.js
fengnovo/fengnovo-react-test
import React from 'react'; import { Router, Route, IndexRoute, browserHistory} from 'react-router'; import App from './pages/app.jsx'; import Home from './pages/home.jsx'; import Detail from './pages/detail.jsx'; import NotFound from './pages/notFound.jsx'; const historyOptions = { queryKey : false }; const routes = ( <Router history={browserHistory}> <Route path='/' component={ App }> <IndexRoute component={ Home }/> <Route path='detail' component={ Detail } /> <Route path='home' component={ Home } /> <Route path='*' component={NotFound}/> </Route> </Router> ); export default routes;
frontend/src/components/dialog/dismiss-group-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; import { gettext } from '../../utils/constants'; import { seafileAPI } from '../../utils/seafile-api'; import { Utils } from '../../utils/utils'; import toaster from '../toast'; class DismissGroupDialog extends React.Component { constructor(props) { super(props); } dismissGroup = () => { let that = this; seafileAPI.deleteGroup(this.props.groupID).then((res)=> { that.props.onGroupChanged(); }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } render() { return( <Modal isOpen={this.props.showDismissGroupDialog} toggle={this.props.toggleDismissGroupDialog}> <ModalHeader>{gettext('Delete Group')}</ModalHeader> <ModalBody> <span>{gettext('Really want to delete this group?')}</span> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.props.toggleDismissGroupDialog}>{gettext('Cancel')}</Button> <Button color="primary" onClick={this.dismissGroup}>{gettext('Delete')}</Button> </ModalFooter> </Modal> ); } } const DismissGroupDialogPropTypes = { showDismissGroupDialog: PropTypes.bool.isRequired, toggleDismissGroupDialog: PropTypes.func.isRequired, loadGroup: PropTypes.func.isRequired, groupID: PropTypes.string.isRequired, onGroupChanged: PropTypes.func.isRequired, }; DismissGroupDialog.propTypes = DismissGroupDialogPropTypes; export default DismissGroupDialog;
libs/F2/1.3.3/f2.no-easyXDM.js
xuminready/baiducdnstatic
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON.org requires the following notice to accompany json2: Copyright (c) 2002 JSON.org http://json.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*! * jQuery JavaScript Library v1.8.3 * The jQuery Foundation and other contributors require the following notice to accompany jQuery: * * Copyright (c) 2013 jQuery Foundation and other contributors * * http://jquery.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /*! ========================================================= * bootstrap-modal.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Twitter, Inc. require the following notice to accompany Bootstrap: * * Copyright (c) 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work * except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing permissions and limitations under the License. * * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function (that) { this.$element .hide() .trigger('hidden') this.backdrop() } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : this.removeBackdrop() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /*! * This file creates $ and jQuery variables within the F2 closure scope */ var $, jQuery = $ = window.jQuery.noConflict(true); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ !function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = new Object; } function configure(conf) { if (conf) { conf.delimiter && (this.delimiter = conf.delimiter); conf.wildcard && (this.wildcard = conf.wildcard); if (this.wildcard) { this.listenerTree = new Object; } } } function EventEmitter(conf) { this._events = new Object; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = new Object; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; }; // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); }; listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener') { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { return this; } if(this.wildcard) { leaf._listeners.splice(position, 1) } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /*! * F2 v1.3.3 04-07-2014 * Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org * * "F2" is licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement('a'); ajaxLocation.href = ''; ajaxLocation = ajaxLocation.href; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} space An optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will be * packed without extra whitespace. If it is a number, it will specify the * number of spaces to indent at each level. If it is a string (such as '\t' * or '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '1.3.3'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} }, /** * Allows the container to override the script loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadScripts * @type function * * @example * F2.init({ * loadScripts: function(scripts,inlines,callback){ * //load scripts using $.load() for each script or require(scripts) * callback(); * } * }); */ loadScripts: function(scripts,inlines,callback){}, /** * Allows the container to override the stylesheet loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadStyles * @type function * * @example * F2.init({ * loadStyles: function(styles,callback){ * //load styles using $.load() for each stylesheet or another method * callback(); * } * }); */ loadStyles: function(styles,callback){} } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Alert!</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>' ].join(''); }; var _renderConfirm = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Confirm</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-primary btn-ok">OK</button>', '<button type="button" class="btn btn-cancel">Cancel</button">', '</div>', '</div>' ].join(''); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function() { var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if ( !! _config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class and Instance ID jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } // apply APP class and instanceId return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } return appConfig; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout) { containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true) { containerConfig.debugMode = F2.ContainerConfig.debugMode; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function(appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent) { // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } // Fn for loading manifest Styles var _loadStyles = function(styles, cb) { // Attempt to use the user provided method if (_config.loadStyles) { _config.loadStyles(styles, cb); } else { // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !! document.createStyleSheet; jQuery.each(styles, function(i, e) { if (useCreateStyleSheet) { document.createStyleSheet(e); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>'); } }); if (stylesFragment) { jQuery('head').append(stylesFragment.join('')); } cb(); } }; // Fn for loading manifest Scripts var _loadScripts = function(scripts, cb) { // Attempt to use the user provided method if (_config.loadScripts) { _config.loadScripts(scripts, cb); } else { if (scripts.length) { var scriptCount = scripts.length; var scriptsLoaded = 0; // Check for IE10+ so that we don't rely on onreadystatechange var readyStates = ('addEventListener' in window) ? {} : { 'loaded': true, 'complete': true }; // Log and emit event for the failed (400,500) scripts var _error = function(e) { setTimeout(function() { var evtData = { src: e.target.src, appId: appConfigs[0].appId }; // Send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); // Emit event F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout); // Defaults to 7000 }; // Load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var doc = document, script = doc.createElement('script'), resourceUrl = e; // If in debugMode, add cache buster to each script URL if (_config.debugMode) { resourceUrl += '?cachebuster=' + new Date().getTime(); } // Scripts needed to be loaded in order they're defined in the AppManifest script.async = false; // Add other attrs script.src = resourceUrl; script.type = 'text/javascript'; script.charset = 'utf-8'; script.onerror = _error; // Use a closure for the load event so that we can dereference the original script script.onload = script.onreadystatechange = function(e) { e = e || window.event; // For older IE if (e.type == 'load' || readyStates[script.readyState]) { // Done, cleanup script.onload = script.onreadystatechange = script.onerror = null; // Dereference script script = null; // Are we done loading all scripts for this app? if (++scriptsLoaded === scriptCount) { cb(); } } }; doc.body.appendChild(script); }); } else { cb(); } } }; var _loadInlineScripts = function(inlines, cb) { // Attempt to use the user provided method if (_config.loadInlineScripts) { _config.loadInlineScripts(inlines, cb); } else { for (var i = 0, len = inlines.length; i < len; i++) { try { eval(inlines[i]); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } } cb(); } }; // Determine whether an element has been added to the page var elementInDocument = function(element) { if (element) { while (element.parentNode) { element = element.parentNode; if (element === document) { return true; } } } return false; }; // Fn for loading manifest app html var _loadHtml = function(apps) { jQuery.each(apps, function(i, a) { if (!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(a.html) ); var appId = appConfigs[i].appId; var root = appConfigs[i].root; if (!root) { throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } if (!elementInDocument(root)) { throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if (!F2.isNativeDOMNode(root)) { throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } $(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); } // init events _initAppEvents(appConfigs[i]); }); }; // Pull out the manifest data var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var apps = appManifest.apps || []; // Finally, load the styles, html, and scripts _loadStyles(styles, function() { // Put the html on the page _loadHtml(apps); // Add the script content to the page _loadScripts(scripts, function() { // Load any inline scripts _loadInlineScripts(inlines, function() { // Create the apps jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }); }); }); }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if (!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config appManifest.html ); if ($root.parents('body:first').length === 0) { throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw ('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw ('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw ('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw ('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if ( !! _config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !! appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config: a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if (a.root) { if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if (jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if (!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps: [a], url: a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url: i, apps: b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx, item) { F2.log('Removed failed ' + item.name + ' app', item); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw ('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw ('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw ('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);