path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
ajax/libs/jQRangeSlider/5.5.0/jQRangeSliderBar.js | AlexisArce/cdnjs | /**
* jQRangeSlider
* A javascript slider selector that supports dates
*
* Copyright (C) Guillaume Gautreau 2012
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
(function($, undefined){
"use strict";
$.widget("ui.rangeSliderBar", $.ui.rangeSliderDraggable, {
options: {
leftHandle: null,
rightHandle: null,
bounds: {min: 0, max: 100},
type: "rangeSliderHandle",
range: false,
drag: function() {},
stop: function() {},
values: {min: 0, max:20},
wheelSpeed: 4,
wheelMode: null
},
_values: {min: 0, max: 20},
_waitingToInit: 2,
_wheelTimeout: false,
_create: function(){
$.ui.rangeSliderDraggable.prototype._create.apply(this);
this.element
.css("position", "absolute")
.css("top", 0)
.addClass("ui-rangeSlider-bar");
this.options.leftHandle
.bind("initialize", $.proxy(this._onInitialized, this))
.bind("mousestart", $.proxy(this._cache, this))
.bind("stop", $.proxy(this._onHandleStop, this));
this.options.rightHandle
.bind("initialize", $.proxy(this._onInitialized, this))
.bind("mousestart", $.proxy(this._cache, this))
.bind("stop", $.proxy(this._onHandleStop, this));
this._bindHandles();
this._values = this.options.values;
this._setWheelModeOption(this.options.wheelMode);
},
destroy: function(){
this.options.leftHandle.unbind(".bar");
this.options.rightHandle.unbind(".bar");
this.options = null;
$.ui.rangeSliderDraggable.prototype.destroy.apply(this);
},
_setOption: function(key, value){
if (key === "range"){
this._setRangeOption(value);
} else if (key === "wheelSpeed"){
this._setWheelSpeedOption(value);
} else if (key === "wheelMode"){
this._setWheelModeOption(value);
}
},
_setRangeOption: function(value){
if (typeof value !== "object" || value === null){
value = false;
}
if (value === false && this.options.range === false){
return;
}
if (value !== false){
var min = valueOrFalse(value.min, this.options.range.min),
max = valueOrFalse(value.max, this.options.range.max);
this.options.range = {
min: min,
max: max
};
}else{
this.options.range = false;
}
this._setLeftRange();
this._setRightRange();
},
_setWheelSpeedOption: function(value){
if (typeof value === "number" && value > 0){
this.options.wheelSpeed = value;
}
},
_setWheelModeOption: function(value){
if (value === null || value === false || value === "zoom" || value === "scroll"){
if (this.options.wheelMode !== value){
this.element.parent().unbind("mousewheel.bar");
}
this._bindMouseWheel(value);
this.options.wheelMode = value;
}
},
_bindMouseWheel: function(mode){
if (mode === "zoom"){
this.element.parent().bind("mousewheel.bar", $.proxy(this._mouseWheelZoom, this));
}else if (mode === "scroll"){
this.element.parent().bind("mousewheel.bar", $.proxy(this._mouseWheelScroll, this));
}
},
_setLeftRange: function(){
if (this.options.range === false){
return false;
}
var rightValue = this._values.max,
leftRange = {min: false, max: false};
if ((this.options.range.min || false) !== false){
leftRange.max = this._leftHandle("substract", rightValue, this.options.range.min);
}else{
leftRange.max = false;
}
if ((this.options.range.max || false) !== false){
leftRange.min = this._leftHandle("substract", rightValue, this.options.range.max);
}else{
leftRange.min = false;
}
this._leftHandle("option", "range", leftRange);
},
_setRightRange: function(){
var leftValue = this._values.min,
rightRange = {min: false, max:false};
if ((this.options.range.min || false) !== false){
rightRange.min = this._rightHandle("add", leftValue, this.options.range.min);
}else {
rightRange.min = false;
}
if ((this.options.range.max || false) !== false){
rightRange.max = this._rightHandle("add", leftValue, this.options.range.max);
}else{
rightRange.max = false;
}
this._rightHandle("option", "range", rightRange);
},
_deactivateRange: function(){
this._leftHandle("option", "range", false);
this._rightHandle("option", "range", false);
},
_reactivateRange: function(){
this._setRangeOption(this.options.range);
},
_onInitialized: function(){
this._waitingToInit--;
if (this._waitingToInit === 0){
this._initMe();
}
},
_initMe: function(){
this._cache();
this.min(this._values.min);
this.max(this._values.max);
var left = this._leftHandle("position"),
right = this._rightHandle("position") + this.options.rightHandle.width();
this.element.offset({
left: left
});
this.element.css("width", right - left);
},
_leftHandle: function(){
return this._handleProxy(this.options.leftHandle, arguments);
},
_rightHandle: function(){
return this._handleProxy(this.options.rightHandle, arguments);
},
_handleProxy: function(element, args){
var array = Array.prototype.slice.call(args);
return element[this.options.type].apply(element, array);
},
/*
* Draggable
*/
_cache: function(){
$.ui.rangeSliderDraggable.prototype._cache.apply(this);
this._cacheHandles();
},
_cacheHandles: function(){
this.cache.rightHandle = {};
this.cache.rightHandle.width = this.options.rightHandle.width();
this.cache.rightHandle.offset = this.options.rightHandle.offset();
this.cache.leftHandle = {};
this.cache.leftHandle.offset = this.options.leftHandle.offset();
},
_mouseStart: function(event){
$.ui.rangeSliderDraggable.prototype._mouseStart.apply(this, [event]);
this._deactivateRange();
},
_mouseStop: function(event){
$.ui.rangeSliderDraggable.prototype._mouseStop.apply(this, [event]);
this._cacheHandles();
this._values.min = this._leftHandle("value");
this._values.max = this._rightHandle("value");
this._reactivateRange();
this._leftHandle().trigger("stop");
this._rightHandle().trigger("stop");
},
/*
* Event binding
*/
_onDragLeftHandle: function(event, ui){
this._cacheIfNecessary();
if (ui.element[0] !== this.options.leftHandle[0]){
return;
}
if (this._switchedValues()){
this._switchHandles();
this._onDragRightHandle(event, ui);
return;
}
this._values.min = ui.value;
this.cache.offset.left = ui.offset.left;
this.cache.leftHandle.offset = ui.offset;
this._positionBar();
},
_onDragRightHandle: function(event, ui){
this._cacheIfNecessary();
if (ui.element[0] !== this.options.rightHandle[0]){
return;
}
if (this._switchedValues()){
this._switchHandles();
this._onDragLeftHandle(event, ui);
return;
}
this._values.max = ui.value;
this.cache.rightHandle.offset = ui.offset;
this._positionBar();
},
_positionBar: function(){
var width = this.cache.rightHandle.offset.left + this.cache.rightHandle.width - this.cache.leftHandle.offset.left;
this.cache.width.inner = width;
this.element
.css("width", width)
.offset({left: this.cache.leftHandle.offset.left});
},
_onHandleStop: function(){
this._setLeftRange();
this._setRightRange();
},
_switchedValues: function(){
if (this.min() > this.max()){
var temp = this._values.min;
this._values.min = this._values.max;
this._values.max = temp;
return true;
}
return false;
},
_switchHandles: function(){
var temp = this.options.leftHandle;
this.options.leftHandle = this.options.rightHandle;
this.options.rightHandle = temp;
this._leftHandle("option", "isLeft", true);
this._rightHandle("option", "isLeft", false);
this._bindHandles();
this._cacheHandles();
},
_bindHandles: function(){
this.options.leftHandle
.unbind(".bar")
.bind("sliderDrag.bar update.bar moving.bar", $.proxy(this._onDragLeftHandle, this));
this.options.rightHandle
.unbind(".bar")
.bind("sliderDrag.bar update.bar moving.bar", $.proxy(this._onDragRightHandle, this));
},
_constraintPosition: function(left){
var position = {},
right;
position.left = $.ui.rangeSliderDraggable.prototype._constraintPosition.apply(this, [left]);
position.left = this._leftHandle("position", position.left);
right = this._rightHandle("position", position.left + this.cache.width.outer - this.cache.rightHandle.width);
position.width = right - position.left + this.cache.rightHandle.width;
return position;
},
_applyPosition: function(position){
$.ui.rangeSliderDraggable.prototype._applyPosition.apply(this, [position.left]);
this.element.width(position.width);
},
/*
* Mouse wheel
*/
_mouseWheelZoom: function(event, delta, deltaX, deltaY){
/*jshint maxstatements:17*/
if (!this.enabled){
return false;
}
var middle = this._values.min + (this._values.max - this._values.min) / 2,
leftRange = {},
rightRange = {};
if (this.options.range === false || this.options.range.min === false){
leftRange.max = middle;
rightRange.min = middle;
} else {
leftRange.max = middle - this.options.range.min / 2;
rightRange.min = middle + this.options.range.min / 2;
}
if (this.options.range !== false && this.options.range.max !== false){
leftRange.min = middle - this.options.range.max / 2;
rightRange.max = middle + this.options.range.max / 2;
}
this._leftHandle("option", "range", leftRange);
this._rightHandle("option", "range", rightRange);
clearTimeout(this._wheelTimeout);
this._wheelTimeout = setTimeout($.proxy(this._wheelStop, this), 200);
this.zoomOut(deltaY * this.options.wheelSpeed);
return false;
},
_mouseWheelScroll: function(event, delta, deltaX, deltaY){
if (!this.enabled){
return false;
}
if (this._wheelTimeout === false){
this.startScroll();
} else {
clearTimeout(this._wheelTimeout);
}
this._wheelTimeout = setTimeout($.proxy(this._wheelStop, this), 200);
this.scrollLeft(deltaY * this.options.wheelSpeed);
return false;
},
_wheelStop: function(){
this.stopScroll();
this._wheelTimeout = false;
},
/*
* Public
*/
min: function(value){
return this._leftHandle("value", value);
},
max: function(value){
return this._rightHandle("value", value);
},
startScroll: function(){
this._deactivateRange();
},
stopScroll: function(){
this._reactivateRange();
this._triggerMouseEvent("stop");
this._leftHandle().trigger("stop");
this._rightHandle().trigger("stop");
},
scrollLeft: function(quantity){
quantity = quantity || 1;
if (quantity < 0){
return this.scrollRight(-quantity);
}
quantity = this._leftHandle("moveLeft", quantity);
this._rightHandle("moveLeft", quantity);
this.update();
this._triggerMouseEvent("scroll");
},
scrollRight: function(quantity){
quantity = quantity || 1;
if (quantity < 0){
return this.scrollLeft(-quantity);
}
quantity = this._rightHandle("moveRight", quantity);
this._leftHandle("moveRight", quantity);
this.update();
this._triggerMouseEvent("scroll");
},
zoomIn: function(quantity){
quantity = quantity || 1;
if (quantity < 0){
return this.zoomOut(-quantity);
}
var newQuantity = this._rightHandle("moveLeft", quantity);
if (quantity > newQuantity){
newQuantity = newQuantity / 2;
this._rightHandle("moveRight", newQuantity);
}
this._leftHandle("moveRight", newQuantity);
this.update();
this._triggerMouseEvent("zoom");
},
zoomOut: function(quantity){
quantity = quantity || 1;
if (quantity < 0){
return this.zoomIn(-quantity);
}
var newQuantity = this._rightHandle("moveRight", quantity);
if (quantity > newQuantity){
newQuantity = newQuantity / 2;
this._rightHandle("moveLeft", newQuantity);
}
this._leftHandle("moveLeft", newQuantity);
this.update();
this._triggerMouseEvent("zoom");
},
values: function(min, max){
if (typeof min !== "undefined" && typeof max !== "undefined")
{
var minValue = Math.min(min, max),
maxValue = Math.max(min, max);
this._deactivateRange();
this.options.leftHandle.unbind(".bar");
this.options.rightHandle.unbind(".bar");
this._values.min = this._leftHandle("value", minValue);
this._values.max = this._rightHandle("value", maxValue);
this._bindHandles();
this._reactivateRange();
this.update();
}
return {
min: this._values.min,
max: this._values.max
};
},
update: function(){
this._values.min = this.min();
this._values.max = this.max();
this._cache();
this._positionBar();
}
});
function valueOrFalse(value, defaultValue){
if (typeof value === "undefined"){
return defaultValue || false;
}
return value;
}
}(jQuery));
|
examples/huge-apps/routes/Course/components/Course.js | mozillo/react-router | /*globals COURSES:true */
import React from 'react'
import Dashboard from './Dashboard'
import Nav from './Nav'
const styles = {}
styles.sidebar = {
float: 'left',
width: 200,
padding: 20,
borderRight: '1px solid #aaa',
marginRight: 20
}
class Course extends React.Component {
render() {
let { children, params } = this.props
let course = COURSES[params.courseId]
return (
<div>
<h2>{course.name}</h2>
<Nav course={course} />
{children && children.sidebar && children.main ? (
<div>
<div className="Sidebar" style={styles.sidebar}>
{children.sidebar}
</div>
<div className="Main" style={{ padding: 20 }}>
{children.main}
</div>
</div>
) : (
<Dashboard />
)}
</div>
)
}
}
export default Course
|
react/features/base/dialog/components/native/InputDialog.js | gpolitis/jitsi-meet | // @flow
import React from 'react';
import { View } from 'react-native';
import Dialog from 'react-native-dialog';
import { translate } from '../../../i18n';
import { connect } from '../../../redux';
import { _abstractMapStateToProps } from '../../functions';
import AbstractDialog, {
type Props as AbstractProps,
type State as AbstractState
} from '../AbstractDialog';
import { inputDialog as styles } from './styles';
type Props = AbstractProps & {
/**
* The dialog descriptionKey.
*/
descriptionKey: string,
/**
* An optional initial value to initiate the field with.
*/
initialValue?: ?string,
/**
* A message key to be shown for the user (e.g. An error that is defined after submitting the form).
*/
messageKey?: string,
/**
* The translate function.
*/
t: Function,
/**
* Props for the text input.
*/
textInputProps: ?Object,
/**
* The untranslated i18n key for the dialog title.
*/
titleKey?: string,
/**
* Validating of the input.
*/
validateInput: ?Function
}
type State = AbstractState & {
/**
* The current value of the field.
*/
fieldValue: ?string
};
/**
* Implements a single field input dialog component.
*/
class InputDialog<P: Props, S: State> extends AbstractDialog<P, S> {
/**
* Instantiates a new {@code InputDialog}.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this.state = {
fieldValue: props.initialValue,
submitting: false
};
this._onChangeText = this._onChangeText.bind(this);
this._onSubmitValue = this._onSubmitValue.bind(this);
}
/**
* Implements {@code Component#render}.
*
* @inheritdoc
*/
render() {
const {
descriptionKey,
messageKey,
t,
titleKey
} = this.props;
return (
<View>
<Dialog.Container
visible = { true }>
<Dialog.Title>
{ t(titleKey) }
</Dialog.Title>
{
descriptionKey && (
<Dialog.Description>
{ t(descriptionKey) }
</Dialog.Description>
)
}
<Dialog.Input
autoFocus = { true }
onChangeText = { this._onChangeText }
value = { this.state.fieldValue }
{ ...this.props.textInputProps } />
{
messageKey && (
<Dialog.Description
style = { styles.formMessage }>
{ t(messageKey) }
</Dialog.Description>
)
}
<Dialog.Button
label = { t('dialog.Cancel') }
onPress = { this._onCancel } />
<Dialog.Button
label = { t('dialog.Ok') }
onPress = { this._onSubmitValue } />
</Dialog.Container>
</View>
);
}
_onCancel: () => void;
_onChangeText: string => void;
/**
* Callback to be invoked when the text in the field changes.
*
* @param {string} fieldValue - The updated field value.
* @returns {void}
*/
_onChangeText(fieldValue) {
if (this.props.validateInput && !this.props.validateInput(fieldValue)) {
return;
}
this.setState({
fieldValue
});
}
_onSubmit: (?string) => boolean;
_onSubmitValue: () => boolean;
/**
* Callback to be invoked when the value of this dialog is submitted.
*
* @returns {boolean}
*/
_onSubmitValue() {
return this._onSubmit(this.state.fieldValue);
}
}
export default translate(connect(_abstractMapStateToProps)(InputDialog));
|
docs/src/PropTable.js | pombredanne/react-bootstrap | import _ from 'lodash-compat';
import React from 'react';
import Glyphicon from '../../src/Glyphicon';
import Label from '../../src/Label';
import Table from '../../src/Table';
let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, '');
let capitalize = str => str[0].toUpperCase() + str.substr(1);
function getPropsData(component, metadata) {
let componentData = metadata[component] || {};
let props = componentData.props || {};
if (componentData.composes) {
componentData.composes.forEach(other => {
if (other !== component) {
props = _.merge({}, getPropsData(other, metadata), props);
}
});
}
if (componentData.mixins) {
componentData.mixins.forEach( other => {
if (other !== component && componentData.composes.indexOf(other) === -1) {
props = _.merge({}, getPropsData(other, metadata), props);
}
});
}
return props;
}
const PropTable = React.createClass({
contextTypes: {
metadata: React.PropTypes.object
},
componentWillMount() {
this.propsData = getPropsData(this.props.component, this.context.metadata);
},
render() {
let propsData = this.propsData;
if (!Object.keys(propsData).length) {
return <div className="text-muted"><em>There are no public props for this component.</em></div>;
}
return (
<Table bordered striped className="prop-table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{ this._renderRows(propsData) }
</tbody>
</Table>
);
},
_renderRows(propsData) {
return Object.keys(propsData)
.sort()
.filter(propName => propsData[propName].type && !propsData[propName].doclets.private )
.map(propName => {
let propData = propsData[propName];
return (
<tr key={propName} className="prop-table-row">
<td>
{propName} {this.renderRequiredLabel(propData)}
</td>
<td>
<div>{this.getType(propData)}</div>
</td>
<td>{propData.defaultValue}</td>
<td>
{ propData.doclets.deprecated
&& <div className="prop-desc-heading">
<strong className="text-danger">{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong>
</div>
}
{ this.renderControllableNote(propData, propName) }
<div className="prop-desc" dangerouslySetInnerHTML={{__html: propData.descHtml }} />
</td>
</tr>
);
});
},
renderRequiredLabel(prop) {
if (!prop.required) {
return null;
}
return (
<Label>required</Label>
);
},
renderControllableNote(prop, propName) {
let controllable = prop.doclets.controllable;
let isHandler = this.getDisplayTypeName(prop.type.name) === 'function';
if (!controllable) {
return false;
}
let text = isHandler ? (
<span>
controls <code>{controllable}</code>
</span>
) : (
<span>
controlled by: <code>{controllable}</code>,
initial prop: <code>{'default' + capitalize(propName)}</code>
</span>
);
return (
<div className="prop-desc-heading">
<small>
<em className="text-info">
<Glyphicon glyph="info-sign"/>
{ text }
</em>
</small>
</div>
);
},
getType(prop) {
let type = prop.type || {};
let name = this.getDisplayTypeName(type.name);
let doclets = prop.doclets || {};
switch (name) {
case 'object':
return name;
case 'union':
return type.value.reduce((current, val, i, list) => {
let item = this.getType({ type: val });
if (React.isValidElement(item)) {
item = React.cloneElement(item, {key: i});
}
current = current.concat(item);
return i === (list.length - 1) ? current : current.concat(' | ');
}, []);
case 'array':
let child = this.getType({ type: type.value });
return <span>{'array<'}{ child }{'>'}</span>;
case 'enum':
return this.renderEnum(type);
case 'custom':
return cleanDocletValue(doclets.type || name);
default:
return name;
}
},
getDisplayTypeName(typeName) {
if (typeName === 'func') {
return 'function';
} else if (typeName === 'bool') {
return 'boolean';
}
return typeName;
},
renderEnum(enumType) {
const enumValues = enumType.value || [];
const renderedEnumValues = [];
enumValues.forEach(function renderEnumValue(enumValue, i) {
if (i > 0) {
renderedEnumValues.push(
<span key={`${i}c`}>, </span>
);
}
renderedEnumValues.push(
<code key={i}>{enumValue}</code>
);
});
return (
<span>one of: {renderedEnumValues}</span>
);
}
});
export default PropTable;
|
game.js | Otouto/4inrow | import React from 'react';
import classNames from 'classnames';
const defaultState = {
isFirstPlayer: true,
isGameEnded: false,
endReason: null
}
var Game = React.createClass({
getDefaultProps() {
return {
rows: 6,
columns: 7,
winNum: 4
}
},
getInitialState() {
return Object.assign({turnes: []}, defaultState);
},
onReset(e) {
e.preventDefault();
this.setState(Object.assign({turnes: []}, defaultState));
},
checkGameEnd() {
if (Object.keys(this.state.turnes).length >= this.props.rows * this.props.columns) {
return {isGameEnded: true, endReason: 'fieldSize'};
} else {
return false;
}
},
checkWinner(key) {
let player = this.state.isFirstPlayer ? 'X' : 'O',
row = 0, col = 0, diag = 0, rDiag = 0,
rowPrev, colPrev, diagPrev, rDiagPrev,
cellCol = Number(key.split('')[1], 10),
cellRow = Number(key.split('')[0], 10);
//check win row
for (let i = 0; i < this.props.columns; i++) {
let id = cellRow.toString() + i.toString(),
result = {};
result = this._isPlayerInPoint(id, row, i, rowPrev);
row = result.counter;
rowPrev = result.prevPos;
}
//check win column
for (let i = 0; i < this.props.rows; i++) {
let id = i.toString() + cellCol.toString(),
result = {};
result = this._isPlayerInPoint(id, col, i, colPrev);
col = result.counter;
colPrev = result.prevPos;
}
//check win diag
let diff = cellRow - cellCol,
beginColl, beginRow;
if (diff < 0) {
beginColl = 0;
beginRow = Math.abs(diff);;
} else {
beginColl = diff;
beginRow = 0;
}
for (let i = 0; i < (this.props.columns - Math.abs(diff)); i++) {
let id = (beginColl + i).toString() + (beginRow + i).toString(),
result = {};
result = this._isPlayerInPoint(id, diag, i, diagPrev);
diag = result.counter;
diagPrev = result.prevPos;
}
//check win rDiag
let rSum = cellRow + cellCol,
rBeginColl, rBeginRow;
if (rSum >= 5) {
rBeginColl = cellCol - (5 - cellRow);
rBeginRow = 5;
} else {
rBeginColl = 0;
rBeginRow = cellCol + cellRow;
}
for (let i = 0; ((rBeginRow - i) >= 0) && ((rBeginColl + i) < this.props.rows); i++) {
let id = (rBeginRow - i).toString() + (rBeginColl + i).toString(),
result = {};
result = this._isPlayerInPoint(id, rDiag, i, rDiagPrev);
rDiag = result.counter;
rDiagPrev = result.prevPos;
}
//check if any condition won
if (row >= this.props.winNum ||
col >= this.props.winNum ||
diag >= this.props.winNum ||
rDiag >= this.props.winNum) {
return {isGameEnded: true, endReason: 'playerWin'};
} else {
return false;
}
},
_isPlayerInPoint(point, counter, step, prevPos = -1) {
let player = this.state.isFirstPlayer ? 'X' : 'O';
if (this.state.turnes[point] == player) {
if (prevPos == -1) prevPos = step - 1;
if(step == prevPos + 1) {
counter++;
} else {
counter = 0;
}
prevPos = step;
}
return { counter, prevPos };
},
onTurn(key) {
let player = this.state.isFirstPlayer ? 'X' : 'O',
result, isGameEnded;
this.state.turnes[key] = player;
result = this.checkWinner(key),
isGameEnded = this.checkGameEnd();
if (result) {
// show game result
this.setState(result);
} else if (isGameEnded) {
// show full field message
this.setState(isGameEnded);
} else {
// next player turn
this.setState({isFirstPlayer: !this.state.isFirstPlayer});
}
},
render() {
let itemsEl = [],
caption = this.state.isFirstPlayer ? 'First' : 'Second',
captionClasses = classNames({
'fr-caption': true,
'fr-caption__first': this.state.isFirstPlayer,
'fr-caption__second': !this.state.isFirstPlayer
});
for (let i = 0; i < this.props.rows; i++) {
for (let j = 0; j < this.props.columns; j++) {
let key = i.toString() + j.toString(),
classes = classNames({
'fr-field__item': true,
'fr-field__item_first': this.state.turnes[key] == 'X',
'fr-field__item_second': this.state.turnes[key] == 'O'
});
itemsEl.push(<li className={classes} onClick={this.onTurn.bind(this, key)} key={key} />)
}
}
return (
<div>
<GameEndMessage
isGameEnded={this.state.isGameEnded}
endReason={this.state.endReason}
isFirstPlayer={this.state.isFirstPlayer}
onReset={this.onReset}/>
<a href='#' className='fr-reset' onClick={this.onReset}>New Game</a>
<p className={captionClasses}> {caption} player turn: </p>
<ul className='fr-field'>
{itemsEl}
</ul>
</div>
)
}
});
var GameEndMessage = React.createClass({
render() {
let reasons = {
fieldSize: 'No free space left. Draw!',
playerWin: (this.props.isFirstPlayer ? 'First' : 'Second') + ' player win!',
},
classes = classNames({
'fr-game-end': true,
'fr-game-end__show': this.props.isGameEnded
});
return (
<div className={classes}>
<p>Game end</p>
<p>{reasons[this.props.endReason]}</p>
<a href='#' onClick={this.props.onReset} className='fr-game-end__play-again'>Play again</a>
</div>
)
}
});
export default Game;
|
app/routes.js | eccorley/electron-starter | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
</Route>
);
|
pootle/static/js/admin/components/UserForm.js | fabada/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
'use strict';
import React from 'react';
import { FormElement } from 'components/forms';
import { ModelFormMixin } from 'mixins/forms';
import ItemDelete from './ItemDelete';
let UserForm = React.createClass({
mixins: [ModelFormMixin],
propTypes: {
onSuccess: React.PropTypes.func.isRequired,
},
fields: [
'username', 'is_active', 'password', 'full_name', 'email',
'is_superuser', 'twitter', 'linkedin', 'website', 'bio'
],
/* Handlers */
handleSuccess(model) {
// Add models at the beginning of the collection. When models exist,
// we need to move them to the first position, as Backbone doesn't
// honor the `at: <pos>` option in that scenario and there's
// no modified time attribute that could be used for sorting.
this.props.collection.unshift(model, {merge: true});
this.props.collection.move(model, 0);
this.props.onSuccess(model);
},
/* Layout */
render() {
let model = this.getResource();
let { errors } = this.state;
let { formData } = this.state;
let deleteHelpText = gettext('Note: when deleting a user their contributions to the site, e.g. comments, suggestions and translations, are attributed to the anonymous user (nobody).');
return (
<form method="post"
id="item-form"
autoComplete="off"
onSubmit={this.handleFormSubmit}>
<div className="fields">
<FormElement
autoFocus={!model.isMeta()}
readOnly={model.isMeta()}
attribute="username"
label={gettext('Username')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
{!model.isMeta() &&
<div className="no-meta">
<FormElement
type="checkbox"
attribute="is_active"
label={gettext('Active')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
<FormElement
type="password"
attribute="password"
label={gettext('Password')}
placeholder={gettext('Set a new password')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
</div>}
<FormElement
autoFocus={model.isMeta()}
attribute="full_name"
label={gettext('Full Name')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
<FormElement
attribute="email"
label={gettext('Email')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
{!model.isMeta() &&
<div className="no-meta">
<FormElement
type="checkbox"
attribute="is_superuser"
label={gettext('Administrator')}
handleChange={this.handleChange}
formData={formData}
errors={errors} />
<p className="divider" />
<FormElement
attribute="twitter"
label={gettext('Twitter')}
handleChange={this.handleChange}
placeholder={gettext('Twitter username')}
formData={formData}
errors={errors}
maxLength="15" />
<FormElement
attribute="linkedin"
label={gettext('LinkedIn')}
handleChange={this.handleChange}
placeholder={gettext('LinkedIn profile URL')}
formData={formData}
errors={errors} />
<FormElement
attribute="website"
label={gettext('Website')}
handleChange={this.handleChange}
placeholder={gettext('Personal website URL')}
formData={formData}
errors={errors} />
<FormElement
type="textarea"
attribute="bio"
label={gettext('Short Bio')}
handleChange={this.handleChange}
placeholder={gettext('Personal description')}
formData={formData}
errors={errors} />
</div>}
</div>
<div className="buttons">
<input type="submit" className="btn btn-primary"
disabled={!this.state.isDirty}
value={gettext('Save')} />
{model.id &&
<ul className="action-links">
<li><a href={model.getProfileUrl()}>{gettext("Public Profile")}</a></li>
<li><a href={model.getSettingsUrl()}>{gettext('Settings')}</a></li>
<li><a href={model.getStatsUrl()}>{gettext("Statistics")}</a></li>
<li><a href={model.getReportsUrl()}>{gettext("Reports")}</a></li>
</ul>}
</div>
{(this.props.onDelete && !model.isMeta()) &&
<div>
<p className="divider" />
<div className="buttons">
<ItemDelete
item={model}
onDelete={this.props.onDelete}
helpText={deleteHelpText}
/>
</div>
</div>}
</form>
);
}
});
export default UserForm;
|
ajax/libs/forerunnerdb/1.3.645/fdb-core+views.js | amoyeh/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.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');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// 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!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
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', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
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);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],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 = 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);
};
/**
* 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":31}],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":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[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
};
},{}],9:[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":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
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":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],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 && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {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;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
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;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.645',
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":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload');
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.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;
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
// Hook our own join change event and refresh after change
this.on('joinChange', function () {
self.refresh();
});
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._privateData.deferEmit.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 query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
}
});
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
};
/**
* 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 () {
var self = this,
pubData,
refreshResults,
joinArr,
i, k;
if (this._from) {
pubData = this.publicData();
// 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 && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* 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;
}
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this.publicData().indexOf.apply(this.publicData(), arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.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 current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
|
src/js/tests/staff-form.spec.js | gonebusy/sample-react-app | import { expect } from 'chai';
import React from 'react';
import renderShallow from 'render-shallow';
import { findWithClass } from 'react-shallow-testutils';
import { spy, stub } from 'sinon';
import request from 'superagent-bluebird-promise';
import moment from 'moment';
import { createNew } from 'src/js/store';
import { initialState } from 'src/js/reducers/staff';
import Loader from 'halogen/ClipLoader';
import { IS_LOADING, CLEAR_AVAILABLE_SLOTS } from 'src/js/action-types';
import * as staffActions from 'src/js/actions/staff';
import Promise from 'bluebird';
import uuidv1 from 'uuid/v1';
import noop from '../../../lib/util/noop';
import StaffFormConnected, { StaffForm } from '../components/staff-form';
describe('<StaffForm>', () => {
context('when rendered with required props for StaffForm', () => {
const today = moment.utc();
const props = {
id: uuidv1(),
date: today,
startTime: '10:15 AM',
endTime: '11:15 AM',
router: {},
style: { styleAttr: 'some-style' },
dispatch: noop,
loading: false
};
let component;
before(() => {
component = renderShallow(
<StaffForm {...props} />).output;
});
it('renders report form with default values', () => {
expect(component).to.eql(
<div className="staff-form" style={props.style}>
<section>
<div className="staff-slots-date">
<p>{today.format('dddd, Do MMM YYYY')}</p>
<p>10:15 AM - 11:15 AM</p>
</div>
<div className="staff-form__form">
<div className="staff-form__form-group">
<label htmlFor="name">Name</label>
<input type="text" name="name" required="required" />
</div>
<div className="staff-form__form-group">
<label htmlFor="email">Email</label>
<input type="email" name="email" required="required" />
</div>
<button onClick={noop} className="staff-form__confirm-btn">
Confirm Booking
</button>
</div>
</section>
</div>
);
});
});
context('when it is loading', () => {
const today = moment.utc();
const props = {
id: uuidv1(),
date: today,
startTime: '10:15 AM',
endTime: '11:15 AM',
router: {},
style: { styleAttr: 'some-style' },
dispatch: noop,
loading: true
};
let component;
before(() => {
component = renderShallow(
<StaffForm {...props} />).output;
});
it('renders report form with default values', () => {
expect(component).to.eql(
<div className="staff-form" style={props.style}>
<Loader className="loader" color="#000000" size="50px" margin="4px" />
</div>
);
});
});
context('when confirm booking is clicked and booking is successful', () => {
const today = moment.utc();
const formattedDate = today.format('YYYY-MM-DD');
const props = {
id: uuidv1(),
date: today,
startTime: '10:15 AM',
endTime: '11:15 AM',
router: {
push: spy()
},
style: { styleAttr: 'some-style' },
dispatch: spy(),
loading: false
};
const body = {
resourceId: props.id,
date: formattedDate,
time: props.startTime,
duration: 60
};
before((done) => {
stub(request, 'post').returns(Promise.resolve({}));
stub(staffActions, 'fetchBookings').returns({});
const component = renderShallow(
<StaffForm {...props} />
).output;
const navElement = findWithClass(component, 'staff-form__confirm-btn');
setTimeout(() => {
navElement.props.onClick();
done();
});
});
after(() => {
request.post.restore();
});
it('calls bookings endpoint', () => {
expect(request.post).to.have.been.calledWith(
'/api/bookings/new', body
);
});
it('calls the pushView function of navigationController', () => {
expect(props.router.push).to.have.been.calledWith(
'/confirm'
);
});
it(`dispatches ${CLEAR_AVAILABLE_SLOTS}`, () => {
expect(props.dispatch).to.have.been.calledWith(
{ type: CLEAR_AVAILABLE_SLOTS, id: props.id }
);
});
it('dispatches fetchBookings', () => {
expect(props.dispatch).to.have.been.calledWith(
staffActions.fetchBookings()
);
});
it(`dispatches ${IS_LOADING}`, () => {
expect(props.dispatch).to.have.been.calledWith(
{ type: IS_LOADING, loading: true }
);
});
});
context('when confirm booking is clicked and booking returns an error', () => {
const today = moment.utc();
const formattedDate = today.format('YYYY-MM-DD');
const props = {
id: uuidv1(),
date: today,
startTime: '10:15 AM',
endTime: '11:15 AM',
router: {
push: spy()
},
style: { styleAttr: 'some-style' },
dispatch: spy(),
loading: false
};
const body = {
resourceId: props.id,
date: formattedDate,
time: props.startTime,
duration: 60
};
before((done) => {
stub(request, 'post').returns(Promise.reject());
const component = renderShallow(
<StaffForm {...props} />
).output;
const navElement = findWithClass(component, 'staff-form__confirm-btn');
setTimeout(() => {
navElement.props.onClick();
done();
});
});
after(() => {
request.post.restore();
});
it('calls bookings endpoint', () => {
expect(request.post).to.have.been.calledWith(
'/api/bookings/new', body
);
});
it('calls the pushView function of navigationController', () => {
expect(props.router.push).to.not.have.been.called();
});
it(`dispatches ${IS_LOADING} true and false`, () => {
expect(props.dispatch).to.have.been.calledWith(
{ type: IS_LOADING, loading: true }
);
expect(props.dispatch).to.have.been.calledWith(
{ type: IS_LOADING, loading: false }
);
});
});
context('when it is connected', () => {
let store;
let component;
const router = {
push: noop
};
const currentDate = moment();
const startTime = '10:15 AM';
const endTime = '11:15 AM';
const style = { styleAttr: 'some-style' };
const selectedStaffMember = {
id: uuidv1(),
imagePath: 'http://i.pravatar.cc/300?img=15',
name: 'Phillip Fry',
selectedDate: currentDate,
startTime,
endTime
};
before(() => {
store = createNew({ staff: { ...initialState, selectedStaffMember, loading: false } });
component = renderShallow(
<StaffFormConnected
store={store}
router={router}
startTime={startTime}
endTime={endTime}
style={style}
/>
).output;
});
it('renders StaffForm with store and its dispatch', () => {
expect(component).to.eql(
<StaffForm
dispatch={noop}
store={store}
router={router}
date={currentDate}
startTime={startTime}
endTime={endTime}
id={selectedStaffMember.id}
style={style}
loading={false}
/>
);
});
});
});
|
src/scripts/components/BidForm.js | scyclow/fire-sale | import React, { Component } from 'react';
require('../../styles/bid-form.scss');
class BidForm extends Component {
state = { error: '', confirmation: '' }
_createBid = () => {
const amount = Number(this.refs.amount.value);
const bidderName = this.refs.bidderName.value;
const comment = this.refs.comment.value || _.sample([
'What a great deal!',
'Steve\'s so cool! What a guy!',
'Wow, this is a steal! I should buy more stuff!',
'',
'Steve\'s so fucking cool. I wish I were him!'
]);
if (!bidderName) {
this.setState({ error: 'Enter your name' });
} else if ((amount !== 0 && !amount) || amount % 1 !== 0) {
this.setState({ error: 'Enter a valid INTEGER' });
} else {
const itemId = this.props.item.id;
this.props.onSubmit({ amount, bidderName, comment, itemId });
this._clearInputs();
this.setState({ error: '', confirmation: 'Groovy' });
}
}
_clearInputs = () => {
['bidderName', 'amount', 'comment', 'flash'].forEach(ref => {
this.refs[ref].value = ''
});
}
_onKeyPress = (e) => {
if (e.nativeEvent.keyCode === 13) {
this._createBid();
}
}
render() {
const { item } = this.props;
const { error, confirmation } = this.state;
return (
<div className="bid-form" onKeyPress={this._onKeyPress}>
<div className={error ? 'error' : 'confirmation'} ref="flash">
{error || confirmation}
</div>
<input className="bid-input" ref="bidderName" type="text" placeholder="Your Name" />
<input className="bid-input" ref="amount" type="text" placeholder="Bid $$$" />
<input className="bid-input" ref="comment" type="text" placeholder="Comment" />
<button onClick={this._createBid}>Bid Now!</button>
</div>
);
}
}
export default BidForm;
|
frontend/app_v2/src/components/Gallery/GalleryPresentationWidget.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
// FPCC
import SectionTitle from 'components/SectionTitle'
import ImageWithLightbox from 'components/ImageWithLightbox'
function GalleryPresentationWidget({ data, sitename }) {
const images = window.innerWidth >= 1024 ? data?.images?.slice(0, 7) : data?.images?.slice(0, 4)
return (
<section className="py-3 md:py-6 px-2 lg:px-10 bg-fv-charcoal space-y-2 lg:space-y-4">
<SectionTitle.Presentation title={data?.title} bgColor={'fv-charcoal'} accentColor={'white'} />
<div className="text-center text-white text-xl">{data?.description}</div>
<div className="mx-auto text-center">
{images?.length > 0 &&
images?.map((image, index) => (
<div key={`${index}_${image?.uid}`} className="inline-flex m-2">
<ImageWithLightbox.Presentation
image={image}
maxWidth={120}
imgStyling={'object-contain md:h-1/3-screen xl:h-2/5-screen w-full'}
/>
</div>
))}
</div>
<div className="flex justify-center">
<Link
className="bg-secondary hover:bg-secondary-dark font-medium items-center justify-center px-5 py-2 rounded-lg shadow-sm text-base text-center text-white"
to={`/${sitename}/gallery/${data?.id}`}
>
View All
</Link>
</div>
</section>
)
}
// PROPTYPES
const { object, string } = PropTypes
GalleryPresentationWidget.propTypes = {
data: object,
sitename: string,
}
export default GalleryPresentationWidget
|
js/components/card/index.js | LetsBuildSomething/vmag_mobile |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, Text, Left, Body, Right, List, ListItem } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { openDrawer, closeDrawer } from '../../actions/drawer';
import styles from './styles';
const {
pushRoute,
} = actions;
const datas = [
{
route: 'basic',
text: 'Basic Card',
},
{
route: 'cardList',
text: 'Card List',
},
{
route: 'cardImage',
text: 'Card Image',
},
{
route: 'cardShowcase',
text: 'Card Showcase',
},
{
route: 'cardHeaderAndFooter',
text: 'Card Header & Footer',
},
];
class NHCard extends Component {
static propTypes = {
openDrawer: React.PropTypes.func,
pushRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
pushRoute(route) {
this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Card</Title>
</Body>
<Right />
</Header>
<Content>
<List
dataArray={datas} renderRow={data =>
<ListItem button onPress={() => { Actions[data.route](); this.props.closeDrawer() }} >
<Text>{data.text}</Text>
<Right>
<Icon name="arrow-forward" style={{ color: '#999' }} />
</Right>
</ListItem>
}
/>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
closeDrawer: () => dispatch(closeDrawer()),
pushRoute: (route, key) => dispatch(pushRoute(route, key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(NHCard);
|
reactNativeThermo/src/containers/pairButton.js | jontore/web_bluetooth_demo | import React, { Component } from 'react';
import { BleManager } from 'react-native-ble-plx';
import { Buffer } from 'buffer';
import {
Text,
View,
StyleSheet,
FlatList,
Vibration
} from 'react-native';
import Button from './button';
const vibrationPattern = [0, 500, 200, 500];
class PairButton extends Component {
constructor(props) {
super(props);
this.state = {
connecting: false,
connected: null,
devices: []
}
this.manager = new BleManager();
this._renderItem = this._renderItem.bind(this);
this.getMessage = this.getMessage.bind(this);
this.scanAndConnect = this.scanAndConnect.bind(this);
this.connectToDevice = this.connectToDevice.bind(this);
}
componentWillMount() {
const subscription = this.manager.onStateChange((state) => {
if (state === 'PoweredOn') {
this.scanAndConnect();
subscription.remove();
}
}, true);
}
scanAndConnect() {
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
// Handle error (scanning will be stopped automatically)
return
}
if (device.serviceUUIDs && device.serviceUUIDs.length > 0 && device.serviceUUIDs[0] === this.props.serviceId) {
const isInList = this.state.devices.find(({ id }) => id === device.id);
if (!isInList) {
this.setState({
devices: [...this.state.devices, device]
});
}
}
});
}
connectToDevice(device) {
this.setState({
connecting: true
}, () => {
device.isConnected()
.then((isConnected) => {
if(isConnected) {
return new Promise((resolve) => resolve(device))
} else {
return device.connect();
}
})
.then(device => device.discoverAllServicesAndCharacteristics())
.then(() => {
this.setState({
connecting: false,
connected: device
}, () => this.props.onConnection(device));
})
.catch((error) => {
this.setState({
connecting: true,
error: 'Could not connect'
});
console.error(error);
});
});
}
_keyExtractor = (item, index) => item.id;
_renderItem({ item: device }) {
return (
<Button
title={device.name}
disabled={this.state.connecting}
onPress={() => this.connectToDevice(device)}
/>
);
}
getMessage() {
if (this.state.error) {
return this.state.error;
}
if (this.state.devices.length === 0 ) {
return 'No Temperature device found';
}
if (this.state.connecting) {
return 'Connecting';
}
if (this.state.connected) {
return 'Connected'
}
return 'Not connected';
}
render() {
function listHeader() {
return (<Text>Devices:</Text>);
};
return (
<View style={styles.container}>
<Text style={styles.instruction}>{this.getMessage()}</Text>
{this.state.devices.length > 0 ?
<FlatList
style={styles.list}
ListHeaderComponent={listHeader}
data={this.state.devices}
keyExtractor={(item) => item.id}
renderItem={this._renderItem}
/>
: <Button title="Refresh" onPress={this.scanAndConnect}/>
}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#6E6E6E'
},
list: {
backgroundColor: '#6E6E6E'
},
instruction: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
export default PairButton;
|
packages/material-ui-icons/src/CropOriginalSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 3H3v18h18V3zm-2 16H5V5h14v14zm-5.04-6.71l-2.75 3.54-1.96-2.36L6.5 17h11l-3.54-4.71z" /></g></React.Fragment>
, 'CropOriginalSharp');
|
ui/src/js/plantBag/PlantBagItem.js | Dica-Developer/weplantaforest | import Accounting from 'accounting';
import React, { Component } from 'react';
import IconButton from '../common/components/IconButton';
require('./plantBagItem.less');
export default class PlantBagItem extends Component {
constructor() {
super();
this.state = {
};
}
componentWillUnmount() {
const elm = this.refs.result;
// elm.removeEventListener('animationend', this.scalingDone);
}
scalingDone() {
this.setState({ scaleResult: false });
}
componentDidMount() {
const elm = this.refs.result;
elm.addEventListener('animationend', this.scalingDone);
}
updateAmount(event) {
this.props.setPlantBagItemAmount(event.target.value);
}
render() {
let imageUrl = 'http://localhost:8081/treeType/image/' + this.props.plantBagitem.imageFile + '/60/60';
return (
<div className="plantBagItem">
<div className="image">
<img src={imageUrl} />
</div>
<div className="treeTypeInfo">
<p>
<span className="bold uppercase">{this.props.plantItemName}</span>
<br />
<span className="bold">{Accounting.formatNumber(this.props.plantBagitem.price / 100, 2, '.', ',')} €</span>
</p>
</div>
<div className="customizer">
<input ref="amountInput" type="number" value={this.props.plantBagitem.amount} onChange={this.updateAmount.bind(this)} />
</div>
<div ref="result" className={'result'}>
<p className="bold">{Accounting.formatNumber((this.props.plantBagitem.amount * this.props.plantBagitem.price) / 100, 2, '.', ',')} €</p>
<IconButton glyphIcon="glyphicon-trash" onClick={this.props.removePlantBagItem.bind(this)} />
</div>
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
linksa/Scustomera.js | liuhui219/linksa | import React from 'react';
import {
View,
StyleSheet,
Navigator,
TouchableOpacity,
TouchableHighlight,
Text,
ScrollView,
ActivityIndicator,
InteractionManager,
Dimensions,
BackAndroid,
Image,
RefreshControl,
ListView,
} from 'react-native';
import ScrollableTabView, { DefaultTabBar, } from 'react-native-scrollable-tab-view';
import Token from './Token';
import Icon from 'react-native-vector-icons/Ionicons';
import Gonggaob from './Gonggaob';
var array = [];
export default class Scustomera extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
id: '',
uid:'',
datas:[],
imgs:[],
loaded: false,
isLoadMore:false,
p:1,
isReach:false,
isRefreshing:false,
isNull:false,
sx:false,
};
}
componentDidMount() {
//这里获取传递过来的参数: name
array = [];
this.fetchData('' + data.data.domain + '/index.php?app=Customer&m=MPrecustom&a=lists&num=15&access_token=' + data.data.token + '&p='+this.state.p)
}
fetchData(url) {
var that=this;
fetch(url)
.then((response) => response.json())
.then((responseData)=>{
if(responseData.data.data != ''){
responseData.data.data.forEach((Data,i) => {
key={i}
array.push(Data);
})
}
if(responseData.data.count <= 10){
that.setState({
isReach:true,
isLoadMore:false,
})
}
if(responseData.data.count == 0){
that.setState({
dataSource: that.state.dataSource.cloneWithRows(['暂无数据']),
loaded: true,
sx:false,
isLoadMore:false,
isNull:true,
})
}else if(array.length > responseData.data.count){
that.setState({
isReach:true,
isLoadMore:false,
isNull:false,
})
}else{
that.setState({
dataSource: that.state.dataSource.cloneWithRows(array),
loaded: true,
sx:false,
isNull:false,
})
}
})
.catch((error) => {
that.setState({
loaded: true,
sx:true,
isReach:true,
dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']),
})
});
}
render() {
if(!this.state.loaded){
return (
<View style={{justifyContent: 'center',alignItems: 'center',height:Dimensions.get('window').height-170,}}>
<View style={styles.loading}>
<ActivityIndicator color="white"/>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.loadingTitle}>加载中……</Text>
</View>
</View>
)
}
return(
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie.bind(this)}
onEndReached={this._onEndReach.bind(this) }
onEndReachedThreshold={2}
renderFooter={this._renderFooter.bind(this)}
refreshControl={
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this._onRefresh.bind(this) }
colors={['#ff0000', '#00ff00', '#0000ff','#3ad564']}
progressBackgroundColor="#ffffff"
/>
}
/>
)
}
_ggButton(id){
const { navigator } = this.props;
if(navigator) {
InteractionManager.runAfterInteractions(() => {
this.props.navigator.push({
name: 'Gonggaob',
component: Gonggaob,
params: {
id: id,
}
})
})
}
}
renderMovie(data,sectionID: number, rowID: number) {
if(this.state.sx){
return(
<View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}>
<Icon name="ios-sad-outline" color="#ccc"size={70} />
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text>
</View>
)
}
else if(this.state.isNull){
return (
<View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}>
<Icon name="ios-folder-outline" color="#ccc"size={70} />
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text>
</View>
)
}
else{
return (
<TouchableOpacity onPress={this.props._select.bind(this,data)}>
<View style={{flexDirection:'row',height:60,alignItems:'center', justifyContent:'space-between',backgroundColor:'#fff',borderBottomWidth:1,borderColor:'#ececec',}}>
<View style={{marginLeft:15,marginRight:15,width: 40, height: 40,borderRadius:20,backgroundColor:'#dcdcdc',alignItems:'center', justifyContent:'center'}}>
<Image source={require('./imgs/ren.png')} style={{width: 20, height: 20, }} />
</View>
<View style={{flexDirection:'column',flex:1,}}>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:16,color:'#777'}}>
{data.custom_company}
</Text>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:12,color:'#999'}}>
{data.custom_type}
</Text>
</View>
<View style={{flexDirection:'row',marginRight:15, alignSelf:'flex-start',paddingTop:10,}}>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{marginRight:5,color:'#999'}}>负责人</Text>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#999'}}>{data.apportion_id}</Text>
</View>
</View>
</TouchableOpacity>
)
}
}
_renderFooter() {
if(this.state.isLoadMore){
return (
<View style={styles.footer}>
<ActivityIndicator color="#4385f4"/>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.footerTitle}>正在加载更多……</Text>
</View>
)
}
}
// 下拉刷新
_onRefresh() {
this.setState({
isRefreshing:true,
isReach:false,
isLoadMore:false,
p:1,
})
var that=this
fetch('' + data.data.domain + '/index.php?app=Customer&m=MPrecustom&a=lists&num=15&access_token=' + data.data.token + '')
.then((response) => response.json())
.then(function (result) {
array=[];
array.length = 0;
if(result.data.data != ''){
result.data.data.forEach((Data,i) => {
key={i}
array.push(Data);
})
}
if(result.data.count <= 10){
that.setState({
isReach:true,
isLoadMore:false,
})
}
if(result.data.count == 0){
that.setState({
dataSource: that.state.dataSource.cloneWithRows(['暂无数据']),
loaded: true,
sx:false,
isLoadMore:false,
isRefreshing:false,
isReach:true,
isNull:true,
})
}else if(array.length > result.data.count){
that.setState({
isReach:true,
isLoadMore:false,
isNull:false,
})
}else{
that.setState({
dataSource: that.state.dataSource.cloneWithRows(array),
loaded: true,
sx:false,
isRefreshing:false,
isNull:false,
})
}
})
.catch((error) => {
that.setState({
loaded: true,
sx:true,
isReach:true,
isRefreshing:false,
dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']),
})
});
}
_onEndReach() {
if(!this.state.isReach){
this.setState({
isLoadMore:true,
p:this.state.p+1,
})
InteractionManager.runAfterInteractions(() => {
this.fetchData('' + data.data.domain + '/index.php?app=Customer&m=MPrecustom&a=lists&num=15&access_token=' + data.data.token + '&p='+this.state.p);
})
}
}
}
const styles = StyleSheet.create({
tabView: {
flex: 1,
flexDirection: 'column',
backgroundColor:'#fafafa',
},
card: {
height:45,
backgroundColor:'#4385f4',
flexDirection:'row'
},
loading: {
backgroundColor: 'gray',
height: 80,
width: 100,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
},
loadingTitle: {
marginTop: 10,
fontSize: 14,
color: 'white'
},
footer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
height: 40,
},
footerTitle: {
marginLeft: 10,
fontSize: 15,
color: 'gray'
},
default: {
height: 37,
borderWidth: 0,
borderColor: 'rgba(0,0,0,0.55)',
flex: 1,
fontSize: 13,
},
}); |
resources/assets/admin/components/utilities/Shell.js | DoSomething/northstar | import React from 'react';
const BaseShell = ({ title, subtitle, children }) => (
<div>
<header className="header" role="banner">
<div className="wrapper">
<h1 className="header__title">{title}</h1>
<p className="header__subtitle">{subtitle}</p>
</div>
</header>
<div className="container">
<div className="wrapper">{children}</div>
</div>
</div>
);
const Shell = ({ title, subtitle, children, error, loading }) => {
if (error) {
return (
<BaseShell title="Oops!" subtitle="Something went wrong...">
<div className="placeholder flex-center-xy">{error.toString()}</div>
</BaseShell>
);
}
if (loading) {
return (
<BaseShell title={title || 'Loading...'} subtitle={subtitle || '...'}>
<div className="h-content flex-center-xy">
<div className="spinner" />
</div>
</BaseShell>
);
}
return (
<BaseShell title={title} subtitle={subtitle}>
{children}
</BaseShell>
);
};
export default Shell;
|
d3-view/0.7.2/d3-view.min.js | quantmind/giottojs.org | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("d3-collection"),require("d3-let"),require("object-assign"),require("d3-timer"),require("d3-selection"),require("d3-dispatch"),require("d3-require")):"function"==typeof define&&define.amd?define(["exports","d3-collection","d3-let","object-assign","d3-timer","d3-selection","d3-dispatch","d3-require"],e):e(t.d3=t.d3||{},t.d3,t.d3,t.assign,t.d3,t.d3,t.d3,t.d3)}(this,function(t,e,n,r,i,o,a,s){"use strict";function u(t){ot.logger.info(rt+" "+t)}function c(t){function e(t){ft(this).el=t}return e.prototype=r({},pt,t),e}function l(t,e,n){return dt(function(){e.$set(n,t.value())})}function d(t){var e=n.inBrowser?window.handlebars:require("handlebars");if(e)return e.compile(t);at("compile function requires handlebars")}function f(t,e){if(n.isString(t)){if(!e)return t;if(!d(t))return t}return t(e)}function p(t,e){var n=o.select(document.createElement("div"));n.html(f(t,e));var r=n.node().children;return 1!==r.length&&at("HtmlElement function should return one root element only, got "+r.length),r[0]}function h(t){this.response=t,this.description=t.statusText}function v(t){if(t.status>=300)throw new h(t);var e=(t.headers.get("content-type")||"").split(";")[0];if("application/json"===e)return t.json();throw new Error("Expected JSON content type, got "+e)}function m(t,e){switch(e.type){case xt.IDENTIFIER:return t[e.name];case xt.LITERAL:return e.value;case xt.ARRAY_EXP:return e.elements.map(function(e){return m(t,e)});case xt.LOGICAL_EXP:case xt.BINARY_EXP:return E(e.operator,m(t,e.left),m(t,e.right));case xt.CALL_EXP:return y(t,e.callee,e.arguments);case xt.MEMBER_EXP:return m(m(t,e.object),e.property);case xt.CONDITIONAL_EXP:return m(t,e.test)?m(t,e.consequent):m(t,e.alternate);case xt.UNARY_EXP:return b(e.operator,m(t,e.argument))}}function g(t,n){switch(1===arguments.length&&(n=e.set()),t.type){case xt.IDENTIFIER:n.add(t.name);break;case xt.ARRAY_EXP:t.elements.forEach(function(t){return g(t,n)});break;case xt.BINARY_EXP:g(t.left,n),g(t.right,n);break;case xt.CALL_EXP:g(t.callee,n),t.arguments.forEach(function(t){return g(t,n)});break;case xt.MEMBER_EXP:n.add(w(t));break;case xt.CONDITIONAL_EXP:g(t.test,n),g(t.consequent,n),m(t.alternate,n);break;case xt.UNARY_EXP:g(t.argument,n)}return n}function y(t,e,n){var r;if(n=n.map(function(e){return m(t,e)}),e.type!==xt.IDENTIFIER&&(t=m(t,e.object),e=e.property),!(r=t[e.name]))throw new EvalError('callable "'+e.name+'" not found in context');return r.apply(t,n)}function b(t,e){return Mt[t]||(Mt[t]=new Function("arg","return "+t+" arg")),Mt[t](e)}function E(t,e,n){return Tt[t]||(Tt[t]=new Function("a","b","return a "+t+" b")),Tt[t](e,n)}function w(t){return t.type===xt.IDENTIFIER?t.name:w(t.object)+"."+t.property.name}function x(t){this.codes=xt,this.expr=t,this.parsed=jt(t)}function _(t,n){var r=e.map(),i=null;r.set("",Bt()),Object.defineProperties(Ft(t),{$events:{get:function(){return r}}}),t.$child=function(e){return null===i&&(i=$(t)),new i(e)},t.$update(n)}function $(t){function e(e){_(this,e),Object.defineProperty(this,"parent",{get:function(){return t}})}return e.prototype=t,e}function P(t){return t&&t.toString&&"[object d3Model]"===t.toString()}function A(t,e,r){function i(n){if(u&&(n=u.get.call(t)),n!==r){var i=r;r=o(n,i);var a=t.name||"model";it("updating "+a+"."+e),t.$change(e,i),t.$change()}}function o(e,r){return e===r?r:n.isArray(e)?a(e,r):P(r)?s(e,r):Ut(e)?t.$new(e):e}function a(t,e){return P(e)?e.$off():n.isArray(e)&&t.forEach(function(n,r){r<e.length&&(t[r]=o(t[r],e[r]))}),t}function s(t,e){return Ut(t)?(e.$update(t),e):(e.$off(),t)}var u;t.$events.set(e,Bt()),Object.defineProperty(t,e,function(){var o={get:function(){return r}};return n.isFunction(r)&&(r={get:r}),Ut(r)&&n.isFunction(r.get)?(r=(u=r).get.call(t),u.reactOn?u.reactOn.forEach(function(n){t.$on(n+"."+e,i)}):at("reactive lazy property "+e+" does not specify 'reactOn' list or properties"),n.isFunction(u.set)&&(o.set=u.set)):o.set=i,o}()),r=Ut(r)?t.$new(r):r,t.$change(e)}function O(t,e){var n=t.$events.get(e);return!n&&t.parent?O(t.parent,e):n}function C(t,e){e?t.on("change."+e,null):t.on("change",null)}function N(t){_(this,t)}function I(t){return new N(t)}function L(t,r,i){var o=t.get(r.uid),a=3===arguments.length?r[i]:void 0;o||(o={model:r,events:e.set()},t.set(r.uid,o)),n.isFunction(a)||2===arguments.length?o.events.add(""):a instanceof I?(o.events.add(""),L(t,a)):(r.$events.has(i)||r.$set(i,null),o.events.add(i))}function D(t,i,o,s){function u(i){var o=n.pop(i,"parent"),u=e.map(o?o.components:null),c=e.map(o?o.directives:s),l=a.dispatch("message","mounted"),v={};d.each(function(t,e){u.set(e,t)}),f.each(function(t,e){c.set(e,t)}),k(u,n.pop(i,"components")),S(c,n.pop(i,"directives")),Object.defineProperties(this,{name:{get:function(){return t}},components:{get:function(){return u}},directives:{get:function(){return c}},parent:{get:function(){return o}},root:{get:function(){return o?o.root:this}},cache:{get:function(){return o?o.cache:v}},props:{get:function(){return h}},uid:{get:function(){return this.model.uid}},events:{get:function(){return l}}}),this.model=r({},n.isFunction(p)?p():p,n.pop(i,"model")),Ht.call("component-created",void 0,this)}function c(t){return new u(t)}n.isFunction(i)&&(i={render:i});var l=r({},i),d=k(e.map(),n.pop(l,"components")),f=S(e.map(),n.pop(l,"directives")),p=n.pop(l,"model"),h=n.pop(l,"props");return u.prototype=r({},o,l),c.prototype=u.prototype,c}function k(t,n){return e.map(n).each(function(e,n){t.set(n,D(n,e,Vt))}),t}function S(t,n){return e.map(n).each(function(e,n){t.set(n,zt(e))}),t}function j(t,e,r){Object.defineProperty(ft(t),"el",{get:function(){return e}});var i=t.select(e).view(t).mount(null,r);if(n.isPromise(i))return i.then(function(){return T(t,r)});T(t,r)}function M(t,e){return void 0===t.isMounted?(t.isMounted=!1,!1):(t.isMounted?at("view "+t.name+" already mounted"):(t.isMounted=!0,t.mounted(),e&&e(t),t.events.call("mounted",void 0,t,e),t.events.on("mounted",null),Ht.call("component-mounted",void 0,t)),!0)}function T(t,e){var n=t.parent;t.childrenMounted(),n&&!n.isMounted?n.events.on("mounted."+t.uid,function(){M(t,e)}):M(t,e)}function R(t,e,n,r){return n?(1!==(n=Et(n)).size()&&at("render function must return a single HTML node"),n=n.node(),e.parentNode.insertBefore(n,e),t.select(e).remove(),j(t,n,r)):at("render function must return a single HTML node. It returned nothing!")}function q(t){for(var e={},n=void 0,r=0;r<t.attributes.length;++r)e[(n=t.attributes[r]).name]=n.value;return e}function X(){this.attrs={},this.all=[]}function F(t,e,r,i){if(t&&t.tagName){var o=e.components.get(t.tagName.toLowerCase()),a=Wt(t,e.directives),s=a.preMount();if(s)return s.execute(e.model);var u=void 0;if(o)u=(e=o({parent:e})).mount(t,r,i);else{for(var c=[],l=ct(t.children),d=0;d<l.length;++d)u=F(l[d],e,r,i),n.isPromise(u)&&c.push(u);c.length&&(u=Promise.all(c))}return n.isPromise(u)?u.then(function(){return a.execute(e.model)}):a.execute(e.model)}}function B(t){if(!t)return at("element not defined, pass an identifier or an HTMLElement object");var e=(n.isFunction(t.node)?t:o.select(t)).node();if(e)return e;at("could not find "+t+" element")}function U(){var t=this.__d3_directives__,e=this.__d3_view__;t&&(t.all.forEach(function(t){return t.destroy()}),delete this.__d3_directives__),e&&(e.destroy(),delete this.__d3_view__)}function Y(){document.removeEventListener("DOMContentLoaded",Y),window.removeEventListener("load",Y),z()}function z(){for(var t=void 0;ot.readyCallbacks.length;)t=ot.readyCallbacks.shift(),i.timeout(t)}function G(t,e,r){var i,o,a;if(n.isObject(r))for(o in r)i=r[o],n.isObject(i)&&("d3-"===o.substring(0,3)?(a=o.replace("-","_"),e.$set(a,i),i=a):i=JSON.stringify(i)),t.attr(o,i||"")}function H(t){var e=t.type||"text";return ae[e]||e}function V(t){var e=this.model.data.children;if(e){if(!n.isArray(e))return ne("children should be an array of fields, for "+(void 0===e?"undefined":oe(e))),t;t.selectAll(".d3form").data(e).enter().append(J).classed("d3form",!0)}return t}function J(t){var e=H(t);return e||(ne("Could not find form component "+t.type),e="input",t.type="hidden"),document.createElement("d3-form-"+e)}function W(t){var e=t.attr("min"),n=t.attr("max");return e=null===e?-1/0:+e,n=null===n?1/0:+n,[e,n]}function K(t,e){return{set:function(e,n){n[t]},validate:function(t,n){return e(t,n)}}}function Q(t){var e=t.label||t.name;return"<label for="+t.id+' class="control-label" d3-class="[srOnly ? \'sr-only\' : null]">'+e+"</label>\n<slot></slot>"}function Z(t,e){return'<div class="input-group" :class="bootstrapStatus()">\n<span class="input-group-addon" id="'+t+'">'+e+"</span>\n<slot></slot>\n</div>"}function tt(t){return'<div class="form-check">\n<label class="form-check-label">\n<slot></slot>\n'+t+"\n</label>\n</div>"}function et(t,e,n){var r=be[n.attr("type")]||be[n.node().tagName.toLowerCase()];if(!r)return e;var i=void 0;return r.forEach(function(r){(i=be.wrappers[r])?e=i(t,e,n):ne("Could not find form field wrapper "+r)}),e}function nt(t){return"string"==typeof t&&we.test(t)}r=r&&r.hasOwnProperty("default")?r.default:r;var rt="[d3-view-debug]",it=function(t){ot.logger.debug&&ot.logger.debug(t)};n.logger.debug=null;var ot={logger:n.logger,fetch:function(){if(n.inBrowser)return window.fetch}(),readyCallbacks:[],setDebug:function(t){!arguments.length||t?this.logger.debug=n.isFunction(t)?t:u:this.logger.debug=null}},at=function(t){ot.logger.warn("[d3-view] "+t)},st=["disabled","readonly","required"],ut={create:function(t){return this.arg?t:at("Cannot bind to empty attribute. Specify :<attr-name>")},refresh:function(t,e){return"class"===this.arg?this.refreshClass(e):n.isArray(e)?at("Cannot apply array to attribute "+this.arg):void(st.indexOf(this.arg)>-1?this.sel.property(this.arg,e||!1):this.sel.attr(this.arg,e||null))},refreshClass:function(t){var e=this.sel;n.isArray(t)||(t=[t]),this.oldValue&&this.oldValue.forEach(function(t){t&&e.classed(t,!1)}),this.oldValue=t.map(function(t){var r=!0;return n.isArray(t)&&(r=t[1],t=t[0]),t&&e.classed(t,r),t})}},ct=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return Array.prototype.slice.call(t,e)},lt={refresh:function(t,e){if(n.isNumber(e)&&(e=""+e),n.isString(e)){this.sel.html(e);for(var r=ct(this.el.children),i=0;i<r.length;++i)this.select(r[i]).mount()}}},dt=function(t,e){var n=null;return function(){if(null!==n)return n;var r=this,o=arguments;return n=new Promise(function(a,s){i.timeout(function(){n=null;try{a(t?t.apply(r,o):void 0)}catch(t){s(t)}},e)})}},ft=function(t){return Object.defineProperty(t,"sel",{get:function(){return o.select(this.el)}}),t},pt={on:function(t,e){var n=l(this,t,e);this.sel.on("input",n).on("change",n)},off:function(){this.sel.on("input",null).on("change",null)},value:function(t){if(!arguments.length)return this.sel.property("value");this.sel.property("value",t)}},ht=c(),vt=c({value:function(t){if(!arguments.length)return this.sel.property("checked");this.sel.property("checked",t)}}),mt={input:ht,textarea:ht,select:c({value:function(t){var e,r=this.sel,i=r.selectAll("option"),a=t;if(!arguments.length)return a=[],i.each(function(){(e=o.select(this)).property("selected")&&a.push(e.attr("value")||"")}),r.property("multiple")?a:a[0]||"";n.isArray(a)||(a=[t||""]),i.each(function(){e=o.select(this),t=e.attr("value")||"",e.property("selected",a.indexOf(t)>-1)})}}),checkbox:vt},gt={create:function(t){var e=this.sel.attr("type"),n=this.el.tagName.toLowerCase(),r=mt[e]||mt[n];return r?(this.tag=new r(this.el),t):at("Cannot apply d3-value directive to "+n)},mount:function(t){var e=this.expression;if(e.parsed.type!==e.codes.IDENTIFIER)return at('d3-value expression support identifiers only, got "'+e.parsed.type+'": '+this.expression);var n=this.expression.expr;return t.$set(n,this.tag.value()),this.tag.on(t,n),t},refresh:function(t,e){this.tag.value(e)},destroy:function(){this.tag.off()}},yt={mount:function(t){var e=this.arg||"click",n=this.expression;this.on(this.sel,e+"."+this.uid,function(e){t.$event=e;try{n.eval(t)}finally{delete t.$event}})},destroy:function(){var t=this.arg||"click";this.on(this.sel,t+"."+this.uid,null)}};h.prototype=Error.prototype;var bt=function(t){return new Promise(function(e){e(t)})},Et=function(t){return t&&!n.isFunction(t.size)?o.select(t):t},wt={isd3:!0,providers:ot,viewElement:p,select:function(t){return o.select(t)},selectAll:function(t){return o.selectAll(t)},createElement:function(t){return o.select(document.createElement(t))},fetch:function(t,e){var n=ot.fetch;return 1==arguments.length?n(t):n(t,e)},fetchText:function(t){for(var e=arguments.length,n=Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return this.fetch.apply(this,[t].concat(n)).then(function(t){return t.text()})},json:function(t){for(var e=arguments.length,n=Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return this.fetch.apply(this,[t].concat(n)).then(v)},renderFromUrl:function(t,e){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=this.cache;return t in r?bt(n?p(r[t]):r[t]):this.fetchText(t).then(function(i){return r[t]=i,n?p(i,e):f(i,e)})},on:function(t,e,n){if(t=Et(t),null===n)return t.on(e,null);t.on(e,function(){return n(o.event)})}},xt={COMPOUND:"Compound",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",LOGICAL_EXP:"LogicalExpression",CONDITIONAL_EXP:"ConditionalExpression",ARRAY_EXP:"ArrayExpression"},_t=function(t,e){var n=new Error(t+" at character "+e);throw n.index=e,n.description=t,n},$t={"-":!0,"!":!0,"~":!0,"+":!0},Pt={"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},At=function(t){var e,n=0;for(var r in t)(e=r.length)>n&&t.hasOwnProperty(r)&&(n=e);return n},Ot=At($t),Ct=At(Pt),Nt={true:!0,false:!1,null:null},It=function(t){return Pt[t]||0},Lt=function(t,e,n){return{type:"||"===t||"&&"===t?xt.LOGICAL_EXP:xt.BINARY_EXP,operator:t,left:e,right:n}},Dt=function(t){return t>=48&&t<=57},kt=function(t){return 36===t||95===t||t>=65&&t<=90||t>=97&&t<=122||t>=128&&!Pt[String.fromCharCode(t)]},St=function(t){return 36===t||95===t||t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||t>=128&&!Pt[String.fromCharCode(t)]},jt=function(t){for(var e,n,r=0,i=t.charAt,o=t.charCodeAt,a=function(e){return i.call(t,e)},s=function(e){return o.call(t,e)},u=t.length,c=function(){for(var t=s(r);32===t||9===t;)t=s(++r)},l=function t(){var e,n,i=f();return c(),63!==s(r)?i:(r++,(e=t())||_t("Expected expression",r),c(),58===s(r)?(r++,(n=t())||_t("Expected expression",r),{type:xt.CONDITIONAL_EXP,test:i,consequent:e,alternate:n}):void _t("Expected :",r))},d=function(){c();for(var e=t.substr(r,Ct),n=e.length;n>0;){if(Pt.hasOwnProperty(e))return r+=n,e;e=e.substr(0,--n)}return!1},f=function(){var t,e,n,i,o,a,s,u;if(a=p(),!(e=d()))return a;for(o={value:e,prec:It(e)},(s=p())||_t("Expected expression after "+e,r),i=[a,o,s];(e=d())&&0!==(n=It(e));){for(o={value:e,prec:n};i.length>2&&n<=i[i.length-2].prec;)s=i.pop(),e=i.pop().value,a=i.pop(),t=Lt(e,a,s),i.push(t);(t=p())||_t("Expected expression after "+e,r),i.push(o,t)}for(t=i[u=i.length-1];u>1;)t=Lt(i[u-1].value,i[u-2],t),u-=2;return t},p=function e(){var n,i,o;if(c(),n=s(r),Dt(n)||46===n)return h();if(39===n||34===n)return v();if(kt(n)||40===n)return y();if(91===n)return E();for(o=(i=t.substr(r,Ot)).length;o>0;){if($t.hasOwnProperty(i))return r+=o,{type:xt.UNARY_EXP,operator:i,argument:e(),prefix:!0};i=i.substr(0,--o)}return!1},h=function(){for(var t,e,n="";Dt(s(r));)n+=a(r++);if(46===s(r))for(n+=a(r++);Dt(s(r));)n+=a(r++);if("e"===(t=a(r))||"E"===t){for(n+=a(r++),"+"!==(t=a(r))&&"-"!==t||(n+=a(r++));Dt(s(r));)n+=a(r++);Dt(s(r-1))||_t("Expected exponent ("+n+a(r)+")",r)}return e=s(r),kt(e)?_t("Variable names cannot start with a number ("+n+a(r)+")",r):46===e&&_t("Unexpected period",r),{type:xt.LITERAL,value:parseFloat(n),raw:n}},v=function(){for(var t,e="",n=a(r++),i=!1;r<u;){if((t=a(r++))===n){i=!0;break}if("\\"===t)switch(t=a(r++)){case"n":e+="\n";break;case"r":e+="\r";break;case"t":e+="\t";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+="\\"+t}else e+=t}return i||_t('Unclosed quote after "'+e+'"',r),{type:xt.LITERAL,value:e,raw:n+e+n}},m=function(){var e,n=s(r),i=r;for(kt(n)?r++:_t("Unexpected "+a(r),r);r<u&&(n=s(r),St(n));)r++;return e=t.slice(i,r),Nt.hasOwnProperty(e)?{type:xt.LITERAL,value:Nt[e],raw:e}:"this"===e?{type:xt.THIS_EXP}:{type:xt.IDENTIFIER,name:e}},g=function(t){for(var e,n,i=[],o=!1;r<u;){if(c(),(e=s(r))===t){o=!0,r++;break}44===e?r++:((n=l())&&n.type!==xt.COMPOUND||_t("Expected comma",r),i.push(n))}return o||_t("Expected "+String.fromCharCode(t),r),i},y=function(){var t,e;for(e=40===(t=s(r))?b():m(),c(),t=s(r);46===t||91===t||40===t;)r++,46===t?(c(),e={type:xt.MEMBER_EXP,computed:!1,object:e,property:m()}):91===t?(e={type:xt.MEMBER_EXP,computed:!0,object:e,property:l()},c(),93!==(t=s(r))&&_t("Unclosed [",r),r++):40===t&&(e={type:xt.CALL_EXP,arguments:g(41),callee:e}),c(),t=s(r);return e},b=function(){r++;var t=l();if(c(),41===s(r))return r++,t;_t("Unclosed (",r)},E=function(){return r++,{type:xt.ARRAY_EXP,elements:g(93)}},w=[];r<u;)59===(e=s(r))||44===e?r++:(n=l())?w.push(n):r<u&&_t('Unexpected "'+a(r)+'"',r);return 1===w.length?w[0]:{type:xt.COMPOUND,body:w}};jt.addUnaryOp=function(t){return Ot=Math.max(t.length,Ot),$t[t]=!0,this},jt.addBinaryOp=function(t,e){return Ct=Math.max(t.length,Ct),Pt[t]=e,this},jt.addLiteral=function(t,e){return Nt[t]=e,this},jt.removeUnaryOp=function(t){return delete $t[t],t.length===Ot&&(Ot=At($t)),this},jt.removeBinaryOp=function(t){return delete Pt[t],t.length===Ct&&(Ct=At(Pt)),this},jt.removeLiteral=function(t){return delete Nt[t],this};var Mt={},Tt={},Rt={eval:function(t){return m(t,this.parsed)},safeEval:function(t){try{return m(t,this.parsed)}catch(t){at("Could not evaluate <<"+this.expr+">> expression: "+t)}},identifiers:function(){return g(this.parsed).values()}};x.prototype=Rt;var qt=function(t){return new x(t)},Xt=0,Ft=function(t){var e="d3v"+ ++Xt;return arguments.length?(Object.defineProperty(t,"uid",{get:function(){return e}}),t):e},Bt=function(){var t=a.dispatch("change"),e=0;return{on:function(e,n){return arguments.length<2?t.on(e):(t.on(e,n),this)},trigger:dt(function(){t.apply("change",this,arguments),e+=1}),triggered:function(){return e}}},Ut=function(t){return t&&t.constructor===Object};I.prototype=N.prototype,N.prototype.toString=function(){return"[object d3Model]"},N.prototype.$on=function(t,e){1===arguments.length&&n.isFunction(t)&&(e=t,t="");var r=t.split("."),i=r[0],o=O(this,i);return o?(this.$events.get(i)||r.push(this.uid),r[0]="change",o.on(r.join("."),e)):at('Cannot bind to "'+i+'" - no such reactive property')},N.prototype.$change=function(t){var e=arguments.length?t:"",n=this.$events.get(e),r=ct(arguments,1);return n?n.trigger.apply(this,r):at("attribute '"+e+"' is not a reactive property this model"),this},N.prototype.$update=function(t,e){if(t){e=2!==arguments.length||e;for(var n in t)(e||void 0===this[n])&&("$"===n.substring(0,1)?this.constructor.prototype[n]?at("Cannot set attribute method "+n+", it is protected"):this[n]=t[n]:this.$set(n,t[n]))}return this},N.prototype.$set=function(t,e){this.$events.get(t)?this[t]=e:A(this,t,e)},N.prototype.$new=function(t){var e=this,n=I(t);return Object.defineProperty(n,"parent",{get:function(){return e}}),n},N.prototype.$off=function(t){if(void 0===t)this.$events.each(function(t){return C(t)});else{var e=t.split("."),n=e.splice(0,1)[0],r=this.$events.get(n);r&&C(r,e.join("."))}},Object.defineProperty(N.prototype,"root",{get:function(){return this.parent?this.parent.root:this}});var Yt=r({},wt,{priority:1,create:function(t){return t},preMount:function(){},mount:function(t){return t},refresh:function(){},destroy:function(){},removeAttribute:function(){this.el.removeAttribute(this.name)},execute:function(t){var r=this;if(this.active&&(this.removeAttribute(),t=this.mount(t))){var i=this,o=this.destroy,a=this.sel,s=function(){var e=i.expression?i.expression.eval(t):void 0;i.refresh(t,e)};i.destroy=function(){return o.call(i,t)};var u=void 0,c=void 0,l=void 0,d=void 0;if(i.identifiers=[],this.expression){var f=e.map();this.expression.identifiers().forEach(function(e){for(u=e.split("."),c=t,l=null,d=0;d<u.length-1;++d)if(c=c[u[d]],!n.isObject(c)){l=u.slice(0,d+1).join("."),at("Property "+l+" is not an object. Directive "+i.name+" cannot bind to "+e);break}if(null===l){if(!(c instanceof I))return at(e+" is not a reactive model. Directive "+i.name+" cannot bind to it");L(f,c,u[u.length-1])}}),f.each(function(t){t.events.has("")?i.identifiers.push({model:t.model,attr:""}):t.events.each(function(e){i.identifiers.push({model:t.model,attr:e})})})}else i.identifiers.push({model:t,attr:""});this.identifiers.forEach(function(t){var e=t.attr+"."+i.uid;t.model.$on(e,s)}),a.on("remove."+i.uid,function(){r.identifiers.forEach(function(t){t.model.$off(t.attr+"."+i.uid)}),i.destroy(t)}),s()}}}),zt=function(t){function e(t,e,n){this.el=t,this.name=e.name,this.arg=n;var r=ft(Ft(this)).create(e.value);r&&(this.expression=qt(r)),this.active||(this.active=!e.value||this.expression)}function n(t,n,r){return new e(t,n,r)}return e.prototype=r({},Yt,t),n.prototype=e.prototype,n},Gt=function(t){if(n.isString(t))try{return JSON.parse(t)}catch(e){return t}return t},Ht=a.dispatch("message","component-created","component-mount","component-mounted"),Vt=r({},wt,{render:function(){},childrenMounted:function(){},mounted:function(){},destroy:function(){},mount:function(t,e,i){if(!M(this)){Ht.call("component-mount",void 0,this,t,e);var o=this.select(t),a=o.directives(),s=a?a.attrs:q(t),u=this.model,c=void 0,l=void 0,d=void 0;e=r({},o.datum(),e);for(c in u)void 0!==(d=void 0===e[c]?s:e)[c]&&(u[c]=Gt(n.pop(d,c)));this.model=u=this.parent.model.$child(u),n.isArray(this.props)&&this.props.forEach(function(t){void 0!==(l=Gt(void 0===e[t]?s[t]:e[t]))&&(n.isString(l)&&u[l]&&(l=u[l]),e[t]=l)}),u.name||(u.name=this.name);var f=this.render(e,s,t);if(n.isPromise(f)){var p=this;return f.then(function(e){return R(p,t,e,i)})}return R(this,t,f,i)}at("already mounted")},mountInner:function(t,e){var n=t.node();if(t.html(e),n.childNodes.length){var r=ct(n.childNodes),i=t.view(this).selectAll(function(){return r}).mount();return i?i.then(function(){return t}):t}return t}}),Jt=["name","class","disabled","readonly","required","href"],Wt=function(t,e){var n=o.select(t),r=n.directives();if(r)return r;if(r=new X,!e)return r;for(var i=0;i<t.attributes.length;++i){var a=t.attributes[i],s=a.name.split("-"),u=s[2],c="d3"===s[0]?s[1]:null;if(c){!u&&Jt.indexOf(c)>-1&&(u=c,c="attr");var l=e.get(c);l?r.add(l(t,a,u)):at(t.tagName+' cannot find directive "'+c+'". Did you forget to register it?')}r.attrs[a.name]=a.value}return r.size()&&n.directives(r),r};X.prototype={size:function(){return this.all.length},pop:function(t){var e=this.all.indexOf(t);return e>-1&&(t.removeAttribute(),this.all.splice(e,1)),t},add:function(t){this.all.push(t)},forEach:function(t){this.all.forEach(t)},preMount:function(){for(var t=void 0,e=0;e<this.all.length;++e)if((t=this.all[e]).preMount())return this.pop(t)},execute:function(t){if(this.size()){var e=[],r=void 0;return this.forEach(function(i){r=i.execute(t),n.isPromise(r)&&e.push(r)}),e.length?Promise.all(e):void 0}}},o.selection.prototype.mount=function(t,e){var r=[],i=void 0;return this.each(function(){var a=o.select(this).view();a?(i=F(this,a,t,e),n.isPromise(i)&&r.push(i)):at("Cannot mount, no view object available to mount to")}),r.length?Promise.all(r):null},o.selection.prototype.view=function(t){if(arguments.length)return this.property("__d3_view__",t);for(var e=this.node(),n=e.__d3_view__,r=e.parentNode;r&&!n;)n=r.__d3_view__,r=r.parentNode;return n},o.selection.prototype.model=function(){var t=this.view();return t?t.model:null},o.selection.prototype.directives=function(t){return arguments.length?this.property("__d3_directives__",t):this.node().__d3_directives__};var Kt=r({},Vt,{use:function(t){return n.isObject(t)?t.install(this):t(this),this},addComponent:function(t,e){var n=D(t,e,Vt);return this.components.set(t,n),n},addDirective:function(t,e){var n=zt(e);return this.directives.set(t,n),n},mount:function(t,e){if(M(this))at("already mounted");else if(Ht.call("component-mount",void 0,this,t),t=B(t))return this.model=this.parent?this.parent.model.$child(this.model):I(this.model),j(this,t,e)}}),Qt=D("forView",null,Kt),Zt={attr:ut,html:lt,value:gt,on:yt,for:{create:function(t){var e=[];return t.trim().split(" ").forEach(function(t){t&&e.push(t)}),3!==e.length||"in"!=e[1]?at('d3-for directive requires "item in expression" template, got "'+t+'"'):(this.itemName=e[0],this.itemClass="for"+this.uid,e[2])},preMount:function(){return!0},mount:function(t){if(this.creator=this.el,this.el=this.creator.parentNode,o.select(this.creator).remove(),this.el)return t},refresh:function(t,e){if(n.isArray(e)){var r=this.creator,i=r.tagName+"."+this.itemClass,o=this.itemName,a=this.sel,s=a.selectAll(i).data(e),u=a.view(),c=void 0;s.exit().remove(),s.enter().append(function(){return r.cloneNode(!0)}).classed(this.itemClass,!0).each(function(t,n){(c={index:n})[o]=t,Qt({model:c,parent:u}).mount(this,function(t){e[n]=t.model[o]})}).merge(s).each(function(t){this.__d3_view__.model[o]=t})}}},if:{mount:function(t){return this.display=this.sel.style("display"),this.display&&"none"!==this.display||(this.display="block"),t},refresh:function(t,e){e?this.sel.style("display",this.display):this.sel.style("display","none")}}};n.inBrowser&&new MutationObserver(function(t){t.forEach(function(t){var e=t.removedNodes,n=void 0;e&&e.length&&e.forEach(function(t){"#text"!==t.nodeName&&(n=o.select(t)).view()&&(n.selectAll("*").each(U),U.call(t))})})}).observe(document.documentElement,{childList:!0,subtree:!0});var te=D("view",null,Kt,S(e.map(),Zt)),ee={logger:n.logger},ne=function(t){ee.logger.warn("[d3-form] "+t)},re={inputData:function(t,e){var r=this.model;return e||(e={}),e.id=e.id||r.uid,r.data=e,t.attr("id",e.id),e.classes&&t.classed(e.classes,!0),G(t,r,e.attributes),e.disabled&&(n.isString(e.disabled)?t.attr("d3-attr-disabled",e.disabled):t.property("disabled",!0)),e},wrap:function(t){var e=this,n=t;return e.model.$formExtensions.forEach(function(r){n=r(e,n,t)||n}),n},wrapTemplate:function(t,e){var n=document.createElement("div"),r=o.select(n).html(e).select("slot");if(!r.size())return ne("template does not provide a slot element"),t;var i=o.select(r.node().parentNode);return t.nodes().forEach(function(t){i.insert(function(){return t},"slot")}),r.remove(),o.selectAll(n.children)}},ie=r({},re,{model:{value:null,error:"",isDirty:null,changed:!1,srOnly:!1,placeholder:"",showError:{reactOn:["error","isDirty"],get:function(){return!!this.error&&this.isDirty}},$validate:function(){}},inputData:function(t,e){if(!(e=re.inputData.call(this,t,e)).name)return ne("Input field without a name");t.attr("name",e.name),e.placeholder=e.placeholder||e.label||e.name;var n=this.model;return n.form.inputs[e.name]=n,n.name=e.name,n.$on("value",function(){null===n.isDirty?n.isDirty=!1:(n.isDirty=!0,n.changed=!0),n.form.$change()}),e}}),oe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ae=(function(){function t(t){this.value=t}function e(e){function n(i,o){try{var a=e[i](o),s=a.value;s instanceof t?Promise.resolve(s.value).then(function(t){n("next",t)},function(t){n("throw",t)}):r(a.done?"return":"normal",a.value)}catch(t){r("throw",t)}}function r(t,e){switch(t){case"return":i.resolve({value:e,done:!0});break;case"throw":i.reject(e);break;default:i.resolve({value:e,done:!1})}(i=i.next)?n(i.key,i.arg):o=null}var i,o;this._invoke=function(t,e){return new Promise(function(r,a){var s={key:t,arg:e,resolve:r,reject:a,next:null};o?o=o.next=s:(i=o=s,n(t,e))})},"function"!=typeof e.return&&(this.return=void 0)}"function"==typeof Symbol&&Symbol.asyncIterator&&(e.prototype[Symbol.asyncIterator]=function(){return this}),e.prototype.next=function(t){return this._invoke("next",t)},e.prototype.throw=function(t){return this._invoke("throw",t)},e.prototype.return=function(t){return this._invoke("return",t)}}(),{text:"input",email:"input",password:"input",checkbox:"input",number:"input",date:"input",url:"input","datetime-local":"input"}),se=r({},re,{render:function(t){var e=t?t.tag||"fieldset":"fieldset",n=this.createElement(e);return t=this.inputData(n,t),V.call(this,n)}}),ue={get:function(t){var e=this.all.slice(0);if(n.isObject(t))for(var r in t)e.push(K(r,t[r]));return e},set:function(t,e){var n=t.model;n._view=t,n.validators.forEach(function(t){return t.set(e,n.data)}),n.$on("value.validate",this.validate),n.$validate=this.validate},validate:function(){for(var t,e,n=this,r=n._view,i=n.validators,o=n.value,a=r.sel.attr("id")===n.data.id?r.sel:r.sel.select("#"+n.data.id),s=0;s<i.length;++s)if(t=i[s],e=t.validate(a,o)){!0===e&&(e="");break}n.error=e||""},all:[{set:function(t,e){var r=e.required;n.isString(r)?t.attr("d3-required",r):t.property("required",r||null)},validate:function(t,e){if(t.property("required")){if(!e)return"required";if(""===e)return!0}}},{set:function(t,e){var r=e.minLength;n.isString(r)?t.attr("d3-attr-minlength",r):void 0!==r&&t.attr("minlength",r)},validate:function(t,e){var n=+t.attr("minlength");if(n===n&&n>0&&e.length<n)return"too short - "+n+" characters or more expected"}},{set:function(t,e){var r=e.maxLength;n.isString(r)?t.attr("d3-attr-maxlength",r):void 0!==r&&t.attr("maxlength",r)},validate:function(t,e){var n=+t.attr("maxlength");if(n===n&&n>0&&e&&e.length>n)return"too long - "+n+" characters or less expected"}},{set:function(t,e){var r=e.minimum;n.isString(r)?t.attr("d3-attr-min",r):void 0!==r&&t.attr("min",r)},validate:function(t,e){var n=W(t);if(n&&+e<n[0])return"must be greater or equal "+n[0]}},{set:function(t,e){var r=e.maximum;n.isString(r)?t.attr("d3-attr-max",r):void 0!==r&&t.attr("max",r)},validate:function(t,e){var n=W(t);if(n&&+e>n[1])return"must be less or equal "+n[1]}}]},ce=["checkbox","radio"],le=r({},ie,{render:function(t){var e=this.createElement("input");return t=this.inputData(e,t),e.attr("type",t.type||"text").attr("d3-value","value"),-1===ce.indexOf(e.attr("type"))&&e.attr("placeholder",t.placeholder),ue.set(this,e),this.wrap(e)}}),de=r({},ie,{render:function(t){var e=this.createElement("textarea");return t=this.inputData(e,t),e.attr("placeholder",t.placeholder).attr("d3-value","value"),ue.set(this,e),this.wrap(e)}}),fe=r({},ie,{model:r({options:[],$optionLabel:function(){return n.isArray(this.option)?this.option[1]||this.option[0]:this.option},$optionValue:function(){return n.isArray(this.option)?this.option[0]:this.option}},ie.model),render:function(t){var e=this.createElement("select");return t=this.inputData(e,t),e.attr("d3-value","value").attr("placeholder",t.placeholder).append("option").attr("d3-for","option in options").attr("d3-html","$optionLabel()").attr("d3-attr-value","$optionValue()"),ue.set(this,e),this.wrap(e)}}),pe=r({},re,{render:function(t){var e=t?t.tag||"button":"button",r=this.createElement(e);t=this.inputData(r,t);var i=this.model;return i.type=t.type||"submit",t.endpoint&&(i.endpoint=t.endpoint),i.$submit=function(){i.actions.submit.call(i,o.event)},n.isString(t.disabled)||(this.model.$set("disabled",t.disabled||null),t.disabled="disabled"),t.submit||(t.submit="$submit()"),r.attr("type",i.type).attr("name",i.name).attr("d3-attr-disabled",t.disabled).attr("d3-on-click",t.submit).html(t.label||"submit"),this.wrap(r)}}),he={default:function(t){this.message(t)},redirect:function(t){window.location.href=t.redirectTo||"/"}},ve={submit:function(t){var e=this,n=e.form,i=r({},me,e.endpoint);t&&(t.preventDefault(),t.stopPropagation());var o=ee.fetch,a=n.$inputData(),s={};if(o)if(i.url){if("application/json"===i.contentType)s.headers={"Content-Type":i.contentType},s.body=JSON.stringify(a);else{s.body=new FormData;for(var u in a)s.body.set(u,a[u])}n.$setSubmit()?(s.method=i.method,o(i.url,s).then(function(t){n.$setSubmitDone();var e=(t.headers.get("content-type")||"").split(";")[0];"application/json"===e?t.json().then(function(e){n.$response(e,t.status,t.headers)}):ne("Cannot load content type '"+e+"'")},function(){n.$setSubmitDone()})):n.$setSubmitDone()}else ne("No url, cannot submit");else ne("fetch provider not available, cannot submit")}},me={contentType:"application/json",method:"post"},ge={props:["schema"],components:{"d3-form-fieldset":se,"d3-form-input":le,"d3-form-textarea":de,"d3-form-select":fe,"d3-form-submit":pe},model:{formSubmitted:!1,formPending:!1,$isValid:function(t){var e=void 0,n=!0;for(var r in this.inputs)e=this.inputs[r],t&&(e.isDirty=!0),e.$validate(),e.error&&(n=!1);return n},$setSubmit:function(){return this.formSubmitted=!0,this.formPending=!0,this.$isValid(!0)},$setSubmitDone:function(){this.formPending=!1},$inputData:function(){var t,e=this.inputs,n={};for(var r in e)((t=e[r].value)||le.changed)&&(n[r]=t);return n},$response:function(t,e,n){if(e<300)if(this.data.resultHandler){var r=he[this.data.resultHandler];r?r.call(this,t,e,n):ne("Could not find "+this.data.resultHandler+" result handler")}else he.default.call(this,t,e,n);else this.$responseError(t,e,n)},$responseError:function(t){t.level="error",this.$message(t)}},render:function(t){function e(t){t=re.inputData.call(o,i,t),r.validators=ue.get(t.validators);for(var e in ve){var a=t[e];n.isString(a)&&(a=o.model.$get(a)),r.actions[e]=a||ve[e]}return V.call(o,i),i}var r=this.model,i=this.createElement("form").attr("novalidate",""),o=this;r.$formExtensions=this.root.$formExtensions||[],r.inputs={},r.actions={},r.form=r;var a=t.schema;return n.isString(a)?(0,ee.fetch)(a,{method:"GET"}).then(function(t){if(200===t.status)return t.json().then(e);ne("Could not load form from "+a+": status "+t.status)}):e(a)}},ye={install:function(t){t.addComponent("d3form",ge),t.$formExtensions=[];for(var e in t.providers)ee[e]=t.providers[e]},actions:ve,responses:he},be={input:["inputGroup","label","formGroup"],checkbox:["formCheck"],textarea:["label","formGroup"],select:["label","formGroup"],submit:["submit"],wrappers:{label:function(t,e){var n=t.model.data;return t.wrapTemplate(e,Q(n))},formGroup:function(t,e,n){var r=t.model.data,i=void 0!==r.size?r.size:t.model.form.data.size,o=i?"form-control form-control-"+i:"form-control";return n.classed(o,!0).attr("d3-class","["+(r.required||!1)+' ? "form-control-required" : null, showError ? "form-control-danger" : null]'),t.wrapTemplate(e,'<div class="form-group" d3-class=\'showError ? "has-danger" : null\'>\n<slot></slot>\n<p d3-if="showError" class="text-danger error-block" d3-html="error"></p>\n</div>')},inputGroup:function(t,e,n){var r=t.model.data.group;if(!r)return e;var i="g"+n.attr("id");return n.attr("aria-describedby",i),t.wrapTemplate(e,Z(i,r))},formCheck:function(t,e,n){var r=t.model.data;return n.classed("form-check-input",!0),t.wrapTemplate(e,tt(r.label))},submit:function(t,e,n){var r=t.model.data.theme||"primary";return n.classed("btn",!0).classed("btn-"+r,!0),t.wrapTemplate(e,'<div class="form-group">\n<slot></slot>\n</div>')}}},Ee={install:function(t){if(!t.$formExtensions)return ne("form bootstrap requires the form plugin installed first!");t.$formExtensions.push(et)}},we=new RegExp("^([a-z]+://|//)"),xe=s.requireFrom(function(t){var e=xe.libs.get(t)||t;return nt(e)?e:"https://unpkg.com/"+t});xe.libs=e.map();t.view=te,t.viewMount=function(t,e,n,r){var i=o.select(t).html(e).mount(n,r);return i||(i=new Promise(function(t){t()})),i},t.viewBase=wt,t.viewEvents=Ht,t.viewModel=I,t.viewExpression=qt,t.viewReady=function(t){ot.readyCallbacks.push(t),"complete"!==document.readyState?(document.addEventListener("DOMContentLoaded",Y),window.addEventListener("load",Y)):z()},t.viewProviders=ot,t.viewWarn=at,t.viewDebug=it,t.viewForms=ye,t.viewBootstrapForms=Ee,t.viewUid=Ft,t.viewDebounce=dt,t.require=xe,t.viewVersion="0.7.2",t.resolvedPromise=bt,t.viewElement=p,t.viewTemplate=d,t.viewHtml=f,t.jsonResponse=v,Object.defineProperty(t,"__esModule",{value:!0})}); |
test/integration/jsconfig-paths/pages/basic-alias.js | JeromeFitz/next.js | import React from 'react'
import { World } from '@c/world'
export default function HelloPage() {
return (
<div>
<World />
</div>
)
}
|
ajax/libs/yasgui/0.0.11/yasgui.bundled.min.js | cgvarela/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.YASGUI=e()}}(function(){var e;return function t(e,n,r){function i(s,a){if(!n[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 c=n[s]={exports:{}};e[s][0].call(c.exports,function(t){var n=e[s][1][t];return i(n?n:t)},c,c.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":98}],2:[function(e,t){function n(){this._events=this._events||{};this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n;n.EventEmitter=n;n.prototype._events=void 0;n.prototype._maxListeners=void 0;n.defaultMaxListeners=10;n.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};n.prototype.emit=function(e){var t,n,i,a,l,u;this._events||(this._events={});if("error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){t=arguments[1];if(t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}n=this._events[e];if(s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];n.apply(this,a)}else if(o(n)){i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];u=n.slice();i=u.length;for(l=0;i>l;l++)u[l].apply(this,a)}return!0};n.prototype.addListener=function(e,t){var i;if(!r(t))throw TypeError("listener must be a function");this._events||(this._events={});this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t);this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t;if(o(this._events[e])&&!this._events[e].warned){var i;i=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners;if(i&&i>0&&this._events[e].length>i){this._events[e].warned=!0;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length);"function"==typeof console.trace&&console.trace()}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){function n(){this.removeListener(e,n);if(!i){i=!0;t.apply(this,arguments)}}if(!r(t))throw TypeError("listener must be a function");var i=!1;n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var n,i,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;n=this._events[e];s=n.length;i=-1;if(n===t||r(n.listener)&&n.listener===t){delete this._events[e];this._events.removeListener&&this.emit("removeListener",e,t)}else if(o(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=a;break}if(0>i)return this;if(1===n.length){n.length=0;delete this._events[e]}else n.splice(i,1);this._events.removeListener&&this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener){0===arguments.length?this._events={}:this._events[e]&&delete this._events[e];return this}if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);this.removeAllListeners("removeListener");this._events={};return this}n=this._events[e];if(r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);delete this._events[e];return this};n.prototype.listeners=function(e){var t;t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[];return t};n.listenerCount=function(e,t){var n;n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0;return n}},{}],3:[function(e){var t=e("jquery");(function(e,t){function n(e,t,n){return[parseFloat(e[0])*(f.test(e[0])?t/100:1),parseFloat(e[1])*(f.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return 9===n.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var o,s=Math.max,a=Math.abs,l=Math.round,u=/left|center|right/,c=/top|center|bottom/,p=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,f=/%$/,h=e.fn.position;e.position={scrollbarWidth:function(){if(o!==t)return o;var n,r,i=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),s=i.children()[0];e("body").append(i);n=s.offsetWidth;i.css("overflow","scroll");r=s.offsetWidth;n===r&&(r=i[0].clientWidth);i.remove();return o=n-r},getScrollInfo:function(t){var n=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),r=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),i="scroll"===n||"auto"===n&&t.width<t.element[0].scrollWidth,o="scroll"===r||"auto"===r&&t.height<t.element[0].scrollHeight;return{width:o?e.position.scrollbarWidth():0,height:i?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]),i=!!n[0]&&9===n[0].nodeType;return{element:n,isWindow:r,isDocument:i,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}};e.fn.position=function(t){if(!t||!t.of)return h.apply(this,arguments);t=e.extend({},t);var o,f,g,m,v,E,y=e(t.of),x=e.position.getWithinInfo(t.within),b=e.position.getScrollInfo(x),T=(t.collision||"flip").split(" "),S={};E=i(y);y[0].preventDefault&&(t.at="left top");f=E.width;g=E.height;m=E.offset;v=e.extend({},m);e.each(["my","at"],function(){var e,n,r=(t[this]||"").split(" ");1===r.length&&(r=u.test(r[0])?r.concat(["center"]):c.test(r[0])?["center"].concat(r):["center","center"]);r[0]=u.test(r[0])?r[0]:"center";r[1]=c.test(r[1])?r[1]:"center";e=p.exec(r[0]);n=p.exec(r[1]);S[this]=[e?e[0]:0,n?n[0]:0];t[this]=[d.exec(r[0])[0],d.exec(r[1])[0]]});1===T.length&&(T[1]=T[0]);"right"===t.at[0]?v.left+=f:"center"===t.at[0]&&(v.left+=f/2);"bottom"===t.at[1]?v.top+=g:"center"===t.at[1]&&(v.top+=g/2);o=n(S.at,f,g);v.left+=o[0];v.top+=o[1];return this.each(function(){var i,u,c=e(this),p=c.outerWidth(),d=c.outerHeight(),h=r(this,"marginLeft"),E=r(this,"marginTop"),N=p+h+r(this,"marginRight")+b.width,C=d+E+r(this,"marginBottom")+b.height,L=e.extend({},v),A=n(S.my,c.outerWidth(),c.outerHeight());"right"===t.my[0]?L.left-=p:"center"===t.my[0]&&(L.left-=p/2);"bottom"===t.my[1]?L.top-=d:"center"===t.my[1]&&(L.top-=d/2);L.left+=A[0];L.top+=A[1];if(!e.support.offsetFractions){L.left=l(L.left);L.top=l(L.top)}i={marginLeft:h,marginTop:E};e.each(["left","top"],function(n,r){e.ui.position[T[n]]&&e.ui.position[T[n]][r](L,{targetWidth:f,targetHeight:g,elemWidth:p,elemHeight:d,collisionPosition:i,collisionWidth:N,collisionHeight:C,offset:[o[0]+A[0],o[1]+A[1]],my:t.my,at:t.at,within:x,elem:c})});t.using&&(u=function(e){var n=m.left-L.left,r=n+f-p,i=m.top-L.top,o=i+g-d,l={target:{element:y,left:m.left,top:m.top,width:f,height:g},element:{element:c,left:L.left,top:L.top,width:p,height:d},horizontal:0>r?"left":n>0?"right":"center",vertical:0>o?"top":i>0?"bottom":"middle"};p>f&&a(n+r)<f&&(l.horizontal="center");d>g&&a(i+o)<g&&(l.vertical="middle");l.important=s(a(n),a(r))>s(a(i),a(o))?"horizontal":"vertical";t.using.call(this,e,l)});c.offset(e.extend(L,{using:u}))})};e.ui.position={fit:{left:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollLeft:r.offset.left,o=r.width,a=e.left-t.collisionPosition.marginLeft,l=i-a,u=a+t.collisionWidth-o-i;if(t.collisionWidth>o)if(l>0&&0>=u){n=e.left+l+t.collisionWidth-o-i;e.left+=l-n}else e.left=u>0&&0>=l?i:l>u?i+o-t.collisionWidth:i;else l>0?e.left+=l:u>0?e.left-=u:e.left=s(e.left-a,e.left)},top:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollTop:r.offset.top,o=t.within.height,a=e.top-t.collisionPosition.marginTop,l=i-a,u=a+t.collisionHeight-o-i;if(t.collisionHeight>o)if(l>0&&0>=u){n=e.top+l+t.collisionHeight-o-i;e.top+=l-n}else e.top=u>0&&0>=l?i:l>u?i+o-t.collisionHeight:i;else l>0?e.top+=l:u>0?e.top-=u:e.top=s(e.top-a,e.top)}},flip:{left:function(e,t){var n,r,i=t.within,o=i.offset.left+i.scrollLeft,s=i.width,l=i.isWindow?i.scrollLeft:i.offset.left,u=e.left-t.collisionPosition.marginLeft,c=u-l,p=u+t.collisionWidth-s-l,d="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,f="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,h=-2*t.offset[0];if(0>c){n=e.left+d+f+h+t.collisionWidth-s-o;(0>n||n<a(c))&&(e.left+=d+f+h)}else if(p>0){r=e.left-t.collisionPosition.marginLeft+d+f+h-l;(r>0||a(r)<p)&&(e.left+=d+f+h)}},top:function(e,t){var n,r,i=t.within,o=i.offset.top+i.scrollTop,s=i.height,l=i.isWindow?i.scrollTop:i.offset.top,u=e.top-t.collisionPosition.marginTop,c=u-l,p=u+t.collisionHeight-s-l,d="top"===t.my[1],f=d?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,h="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,g=-2*t.offset[1];if(0>c){r=e.top+f+h+g+t.collisionHeight-s-o;e.top+f+h+g>c&&(0>r||r<a(c))&&(e.top+=f+h+g)}else if(p>0){n=e.top-t.collisionPosition.marginTop+f+h+g-l;e.top+f+h+g>p&&(n>0||a(n)<p)&&(e.top+=f+h+g)}}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments);e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments);e.ui.position.fit.top.apply(this,arguments)}}};(function(){var t,n,r,i,o,s=document.getElementsByTagName("body")[0],a=document.createElement("div");t=document.createElement(s?"div":"body");r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};s&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in r)t.style[o]=r[o];t.appendChild(a);n=s||document.documentElement;n.insertBefore(t,n.firstChild);a.style.cssText="position: absolute; left: 10.7432222px;";i=e(a).offset().left;e.support.offsetFractions=i>10&&11>i;t.innerHTML="";n.removeChild(t)})()})(t)},{jquery:4}],4:[function(t,n){(function(e,t){"object"==typeof n&&"object"==typeof n.exports?n.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,n){function r(e){var t=e.length,n=ot.type(e);return"function"===n||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function i(e,t,n){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return ot.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,n);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==n})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=bt[e]={};ot.each(e.match(xt)||[],function(e,n){t[n]=!0});return t}function a(){if(gt.addEventListener){gt.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{gt.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(gt.addEventListener||"load"===event.type||"complete"===gt.readyState){a();ot.ready()}}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Lt,"-$1").toLowerCase();n=e.getAttribute(r);if("string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Ct.test(n)?ot.parseJSON(n):n}catch(i){}ot.data(e,t,n)}else n=void 0}return n}function c(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function p(e,t,n,r){if(ot.acceptData(e)){var i,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t){u||(u=a?e[s]=Y.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==n&&(o[ot.camelCase(t)]=n);if("string"==typeof t){i=o[t];null==i&&(i=o[ot.camelCase(t)])}else i=o;return i}}}function d(e,t,n){if(ot.acceptData(e)){var r,i,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=n?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}i=t.length;for(;i--;)delete r[t[i]];if(n?!c(r):!ot.isEmptyObject(r))return}}if(!n){delete s[a].data;if(!c(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function g(){try{return gt.activeElement}catch(e){}}function m(e){var t=Mt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function v(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Nt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Nt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,v(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function E(e){Ot.test(e.type)&&(e.defaultChecked=e.checked)}function y(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 x(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function b(e){var t=Xt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function T(e,t){for(var n,r=0;null!=(n=e[r]);r++)ot._data(n,"globalEval",!t||ot._data(t[r],"globalEval"))}function S(e,t){if(1===t.nodeType&&ot.hasData(e)){var n,r,i,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(n in a)for(r=0,i=a[n].length;i>r;r++)ot.event.add(t,n,a[n][r])}s.data&&(s.data=ot.extend({},s.data))}}function N(e,t){var n,r,i;if(1===t.nodeType){n=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){i=ot._data(t);for(r in i.events)ot.removeEvent(t,r,i.handle);t.removeAttribute(ot.expando)}if("script"===n&&t.text!==e.text){x(t).text=e.text;b(t)}else if("object"===n){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===n&&Ot.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function C(e,n){var r,i=ot(n.createElement(e)).appendTo(n.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(i[0]))?r.display:ot.css(i[0],"display");i.detach();return o}function L(e){var t=gt,n=en[e];if(!n){n=C(e,t);if("none"===n||!n){Zt=(Zt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Zt[0].contentWindow||Zt[0].contentDocument).document;t.write();t.close();n=C(e,t);Zt.detach()}en[e]=n}return n}function A(e,t){return{get:function(){var n=e();if(null!=n){if(!n)return(this.get=t).apply(this,arguments);delete this.get}}}}function I(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=hn.length;i--;){t=hn[i]+n;if(t in e)return t}return r}function w(e,t){for(var n,r,i,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");n=r.style.display;if(t){o[s]||"none"!==n||(r.style.display="");""===r.style.display&&wt(r)&&(o[s]=ot._data(r,"olddisplay",L(r.nodeName)))}else{i=wt(r);(n&&"none"!==n||!i)&&ot._data(r,"olddisplay",i?n:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function R(e,t,n){var r=cn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function O(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===n&&(s+=ot.css(e,n+It[o],!0,i));if(r){"content"===n&&(s-=ot.css(e,"padding"+It[o],!0,i));"margin"!==n&&(s-=ot.css(e,"border"+It[o]+"Width",!0,i))}else{s+=ot.css(e,"padding"+It[o],!0,i);"padding"!==n&&(s+=ot.css(e,"border"+It[o]+"Width",!0,i))}}return s}function _(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=tn(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=i||null==i){i=nn(e,t,o);(0>i||null==i)&&(i=e.style[t]);if(on.test(i))return i;r=s&&(rt.boxSizingReliable()||i===e.style[t]);i=parseFloat(i)||0}return i+O(e,t,n||(s?"border":"content"),r,o)+"px"}function D(e,t,n,r,i){return new D.prototype.init(e,t,n,r,i)}function F(){setTimeout(function(){gn=void 0});return gn=ot.now()}function k(e,t){var n,r={height:e},i=0;t=t?1:0;for(;4>i;i+=2-t){n=It[i];r["margin"+n]=r["padding"+n]=e}t&&(r.opacity=r.width=e);return r}function P(e,t,n){for(var r,i=(bn[t]||[]).concat(bn["*"]),o=0,s=i.length;s>o;o++)if(r=i[o].call(n,t,e))return r}function M(e,t,n){var r,i,o,s,a,l,u,c,p=this,d={},f=e.style,h=e.nodeType&&wt(e),g=ot._data(e,"fxshow");if(!n.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;p.always(function(){p.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){n.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");c="none"===u?ot._data(e,"olddisplay")||L(e.nodeName):u;"inline"===c&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==L(e.nodeName)?f.zoom=1:f.display="inline-block")}if(n.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||p.always(function(){f.overflow=n.overflow[0];f.overflowX=n.overflow[1];f.overflowY=n.overflow[2]})}for(r in t){i=t[r];if(vn.exec(i)){delete t[r];o=o||"toggle"===i;if(i===(h?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;h=!0}d[r]=g&&g[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?L(e.nodeName):u)&&(f.display=u);else{g?"hidden"in g&&(h=g.hidden):g=ot._data(e,"fxshow",{});o&&(g.hidden=!h);h?ot(e).show():p.done(function(){ot(e).hide()});p.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=P(h?g[r]:0,r,p);if(!(r in g)){g[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function j(e,t){var n,r,i,o,s;for(n in e){r=ot.camelCase(n);i=t[r];o=e[n];if(ot.isArray(o)){i=o[1];o=e[n]=o[0]}if(n!==r){e[r]=o;delete e[n]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(n in o)if(!(n in e)){e[n]=o[n];t[n]=i}}else t[r]=i}}function G(e,t,n){var r,i,o=0,s=xn.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=gn||F(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,n]);if(1>o&&l)return n;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:gn||F(),duration:n.duration,tweens:[],createTween:function(t,n){var r=ot.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;i=!0;for(;r>n;n++)u.tweens[n].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),c=u.props;j(c,u.opts.specialEasing);for(;s>o;o++){r=xn[o].call(u,e,c,u.opts);if(r)return r}ot.map(c,P,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function U(e){return function(t,n){if("string"!=typeof t){n=t;t="*"}var r,i=0,o=t.toLowerCase().match(xt)||[];if(ot.isFunction(n))for(;r=o[i++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(n)}else(e[r]=e[r]||[]).push(n)}}function B(e,t,n,r){function i(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,n,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);i(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wn;return i(t.dataTypes[0])||!o["*"]&&i("*")}function q(e,t){var n,r,i=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);n&&ot.extend(!0,e,n);return e}function H(e,t,n){for(var r,i,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"))}if(i)for(s in a)if(a[s]&&a[s].test(i)){l.unshift(s);break}if(l[0]in n)o=l[0];else{for(s in n){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return n[o]}}function V(e,t,n,r){var i,o,s,a,l,u={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=c.shift();for(;o;){e.responseFields[o]&&(n[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=c.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(i in u){a=i.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[i];else if(u[i]!==!0){o=a[0];c.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(p){return{state:"parsererror",error:s?p:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function W(e,t,n,r){var i;if(ot.isArray(t))ot.each(t,function(t,i){n||Yn.test(e)?r(e,i):W(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==ot.type(t))r(e,t);else for(i in t)W(e+"["+i+"]",t[i],n,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function $(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function X(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var Y=[],K=Y.slice,Q=Y.concat,J=Y.push,Z=Y.indexOf,et={},tt=et.toString,nt=et.hasOwnProperty,rt={},it="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:it,constructor:ot,selector:"",length:0,toArray:function(){return K.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:K.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(K.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:J,sort:Y.sort,splice:Y.splice};ot.extend=ot.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(i=arguments[a]))for(r in i){e=s[r];n=i[r];if(s!==n)if(u&&n&&(ot.isPlainObject(n)||(t=ot.isArray(n)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,n)}else void 0!==n&&(s[r]=n)}return s};ot.extend({expando:"jQuery"+(it+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!nt.call(e,"constructor")&&!nt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(rt.ownLast)for(t in e)return nt.call(e,t);for(t in e);return void 0===t||nt.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,n){var i,o=0,s=e.length,a=r(e);if(n)if(a)for(;s>o;o++){i=t.apply(e[o],n);if(i===!1)break}else for(o in e){i=t.apply(e[o],n);if(i===!1)break}else if(a)for(;s>o;o++){i=t.call(e[o],o,e[o]);if(i===!1)break}else for(o in e){i=t.call(e[o],o,e[o]);if(i===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var n=t||[];null!=e&&(r(Object(e))?ot.merge(n,"string"==typeof e?[e]:e):J.call(n,e));return n},inArray:function(e,t,n){var r;if(t){if(Z)return Z.call(t,e,n);r=t.length;n=n?0>n?Math.max(0,r+n):n:0;for(;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];e.length=i;return e},grep:function(e,t,n){for(var r,i=[],o=0,s=e.length,a=!n;s>o;o++){r=!t(e[o],o);r!==a&&i.push(e[o])}return i},map:function(e,t,n){var i,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){i=t(e[o],o,n);null!=i&&l.push(i)}else for(o in e){i=t(e[o],o,n);null!=i&&l.push(i)}return Q.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;if("string"==typeof t){i=e[t];t=e;e=i}if(!ot.isFunction(e))return void 0;n=K.call(arguments,2);r=function(){return e.apply(t||this,n.concat(K.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var ct=function(e){function t(e,t,n,r){var i,o,s,a,l,u,p,f,h,g;(t?t.ownerDocument||t:U)!==_&&O(t);t=t||_;n=n||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return n;if(!r&&F){if(11!==a&&(i=Et.exec(e)))if(s=i[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return n;if(o.id===s){n.push(o);return n}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&j(t,o)&&o.id===s){n.push(o);return n}}else{if(i[2]){J.apply(n,t.getElementsByTagName(e));return n}if((s=i[3])&&b.getElementsByClassName){J.apply(n,t.getElementsByClassName(s));return n}}if(b.qsa&&(!k||!k.test(e))){f=p=G;h=t;g=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=C(e);(p=t.getAttribute("id"))?f=p.replace(xt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=yt.test(e)&&c(t.parentNode)||t;g=u.join(",")}if(g)try{J.apply(n,h.querySelectorAll(g));return n}catch(m){}finally{p||t.removeAttribute("id")}}}return A(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){t.push(n+" ")>T.cacheLength&&delete e[t.shift()];return e[n+" "]=r}var t=[];return e}function r(e){e[G]=!0;return e}function i(e){var t=_.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function s(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||$)-(~e.sourceIndex||$);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function a(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(n,r){for(var i,o=e([],n.length,t),s=o.length;s--;)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function p(){}function d(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function f(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=q++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,s){var a,l,u=[B,o];if(s){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,s))return!0}else for(;t=t[r];)if(1===t.nodeType||i){l=t[G]||(t[G]={});if((a=l[r])&&a[0]===B&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,n,s))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function m(e,t,n,r,i){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!n||n(o,r,i))){s.push(o);u&&t.push(a)}return s}function v(e,t,n,i,o,s){i&&!i[G]&&(i=v(i));o&&!o[G]&&(o=v(o,s));return r(function(r,s,a,l){var u,c,p,d=[],f=[],h=s.length,v=r||g(t||"*",a.nodeType?[a]:a,[]),E=!e||!r&&t?v:m(v,d,e,a,l),y=n?o||(r?e:h||i)?[]:s:E;n&&n(E,y,a,l);if(i){u=m(y,f);i(u,[],a,l);c=u.length;for(;c--;)(p=u[c])&&(y[f[c]]=!(E[f[c]]=p))}if(r){if(o||e){if(o){u=[];c=y.length;for(;c--;)(p=y[c])&&u.push(E[c]=p);o(null,y=[],u,l)}c=y.length;for(;c--;)(p=y[c])&&(u=o?et(r,p):d[c])>-1&&(r[u]=!(s[u]=p))}}else{y=m(y===s?y.splice(h,y.length):y);o?o(null,s,y,l):J.apply(s,y)}})}function E(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],s=o||T.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),c=[function(e,n,r){var i=!o&&(r||n!==I)||((t=n).nodeType?l(e,n,r):u(e,n,r));t=null;return i}];i>a;a++)if(n=T.relative[e[a].type])c=[f(h(c),n)];else{n=T.filter[e[a].type].apply(null,e[a].matches);if(n[G]){r=++a;for(;i>r&&!T.relative[e[r].type];r++);return v(a>1&&h(c),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),n,r>a&&E(e.slice(a,r)),i>r&&E(e=e.slice(r)),i>r&&d(e))}c.push(n)}return h(c)}function y(e,n){var i=n.length>0,o=e.length>0,s=function(r,s,a,l,u){var c,p,d,f=0,h="0",g=r&&[],v=[],E=I,y=r||o&&T.find.TAG("*",u),x=B+=null==E?1:Math.random()||.1,b=y.length;u&&(I=s!==_&&s);for(;h!==b&&null!=(c=y[h]);h++){if(o&&c){p=0;for(;d=e[p++];)if(d(c,s,a)){l.push(c);break}u&&(B=x)}if(i){(c=!d&&c)&&f--;r&&g.push(c)}}f+=h;if(i&&h!==f){p=0;for(;d=n[p++];)d(g,v,s,a);if(r){if(f>0)for(;h--;)g[h]||v[h]||(v[h]=K.call(l));v=m(v)}J.apply(l,v);u&&!r&&v.length>0&&f+n.length>1&&t.uniqueSort(l)}if(u){B=x;I=E}return g};return i?r(s):s}var x,b,T,S,N,C,L,A,I,w,R,O,_,D,F,k,P,M,j,G="sizzle"+1*new Date,U=e.document,B=0,q=0,H=n(),V=n(),W=n(),z=function(e,t){e===t&&(R=!0);return 0},$=1<<31,X={}.hasOwnProperty,Y=[],K=Y.pop,Q=Y.push,J=Y.push,Z=Y.slice,et=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",nt="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",it=rt.replace("w","w#"),ot="\\["+nt+"*("+rt+")(?:"+nt+"*([*^$|!~]?=)"+nt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+it+"))|)"+nt+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(nt+"+","g"),lt=new RegExp("^"+nt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+nt+"+$","g"),ut=new RegExp("^"+nt+"*,"+nt+"*"),ct=new RegExp("^"+nt+"*([>+~]|"+nt+")"+nt+"*"),pt=new RegExp("="+nt+"*([^\\]'\"]*?)"+nt+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+it+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+nt+"*(even|odd|(([+-]|)(\\d*)n|)"+nt+"*(?:([+-]|)"+nt+"*(\\d+)|))"+nt+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+nt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+nt+"*((?:-\\d)?\\d*)"+nt+"*\\)|)(?=[^-]|$)","i")},gt=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,Et=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,yt=/[+~]/,xt=/'|\\/g,bt=new RegExp("\\\\([\\da-f]{1,6}"+nt+"?|("+nt+")|.)","ig"),Tt=function(e,t,n){var r="0x"+t-65536;
return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},St=function(){O()};try{J.apply(Y=Z.call(U.childNodes),U.childNodes);Y[U.childNodes.length].nodeType}catch(Nt){J={apply:Y.length?function(e,t){Q.apply(e,Z.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}b=t.support={};N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};O=t.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:U;if(r===_||9!==r.nodeType||!r.documentElement)return _;_=r;D=r.documentElement;n=r.defaultView;n&&n!==n.top&&(n.addEventListener?n.addEventListener("unload",St,!1):n.attachEvent&&n.attachEvent("onunload",St));F=!N(r);b.attributes=i(function(e){e.className="i";return!e.getAttribute("className")});b.getElementsByTagName=i(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});b.getElementsByClassName=vt.test(r.getElementsByClassName);b.getById=i(function(e){D.appendChild(e).id=G;return!r.getElementsByName||!r.getElementsByName(G).length});if(b.getById){T.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&F){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}};T.filter.ID=function(e){var t=e.replace(bt,Tt);return function(e){return e.getAttribute("id")===t}}}else{delete T.find.ID;T.filter.ID=function(e){var t=e.replace(bt,Tt);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}}T.find.TAG=b.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):b.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o};T.find.CLASS=b.getElementsByClassName&&function(e,t){return F?t.getElementsByClassName(e):void 0};P=[];k=[];if(b.qsa=vt.test(r.querySelectorAll)){i(function(e){D.appendChild(e).innerHTML="<a id='"+G+"'></a><select id='"+G+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&k.push("[*^$]="+nt+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||k.push("\\["+nt+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+G+"-]").length||k.push("~=");e.querySelectorAll(":checked").length||k.push(":checked");e.querySelectorAll("a#"+G+"+*").length||k.push(".#.+[+~]")});i(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&k.push("name"+nt+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||k.push(":enabled",":disabled");e.querySelectorAll("*,:x");k.push(",.*:")})}(b.matchesSelector=vt.test(M=D.matches||D.webkitMatchesSelector||D.mozMatchesSelector||D.oMatchesSelector||D.msMatchesSelector))&&i(function(e){b.disconnectedMatch=M.call(e,"div");M.call(e,"[s!='']:x");P.push("!=",st)});k=k.length&&new RegExp(k.join("|"));P=P.length&&new RegExp(P.join("|"));t=vt.test(D.compareDocumentPosition);j=t||vt.test(D.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){R=!0;return 0}var n=!e.compareDocumentPosition-!t.compareDocumentPosition;if(n)return n;n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&n||!b.sortDetached&&t.compareDocumentPosition(e)===n?e===r||e.ownerDocument===U&&j(U,e)?-1:t===r||t.ownerDocument===U&&j(U,t)?1:w?et(w,e)-et(w,t):0:4&n?-1:1}:function(e,t){if(e===t){R=!0;return 0}var n,i=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:w?et(w,e)-et(w,t):0;if(o===a)return s(e,t);n=e;for(;n=n.parentNode;)l.unshift(n);n=t;for(;n=n.parentNode;)u.unshift(n);for(;l[i]===u[i];)i++;return i?s(l[i],u[i]):l[i]===U?-1:u[i]===U?1:0};return r};t.matches=function(e,n){return t(e,null,null,n)};t.matchesSelector=function(e,n){(e.ownerDocument||e)!==_&&O(e);n=n.replace(pt,"='$1']");if(!(!b.matchesSelector||!F||P&&P.test(n)||k&&k.test(n)))try{var r=M.call(e,n);if(r||b.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,_,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==_&&O(e);return j(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==_&&O(e);var n=T.attrHandle[t.toLowerCase()],r=n&&X.call(T.attrHandle,t.toLowerCase())?n(e,t,!F):void 0;return void 0!==r?r:b.attributes||!F?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,n=[],r=0,i=0;R=!b.detectDuplicates;w=!b.sortStable&&e.slice(0);e.sort(z);if(R){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}w=null;return e};S=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=S(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=S(t);return n};T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(bt,Tt);e[3]=(e[3]||e[4]||e[5]||"").replace(bt,Tt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,n=!e[6]&&e[2];if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(n&&dt.test(n)&&(t=C(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)){e[0]=e[0].slice(0,t);e[2]=n.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(bt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=H[e+" "];return t||(t=new RegExp("(^|"+nt+")"+e+"("+nt+"|$)"))&&H(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);if(null==o)return"!="===n;if(!n)return!0;o+="";return"="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,d,f,h,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),E=!l&&!a;if(m){if(o){for(;g;){p=t;for(;p=p[g];)if(a?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&E){c=m[G]||(m[G]={});u=c[e]||[];f=u[0]===B&&u[1];d=u[0]===B&&u[2];p=f&&m.childNodes[f];for(;p=++f&&p&&p[g]||(d=f=0)||h.pop();)if(1===p.nodeType&&++d&&p===t){c[e]=[B,f,d];break}}else if(E&&(u=(t[G]||(t[G]={}))[e])&&u[0]===B)d=u[1];else for(;p=++f&&p&&p[g]||(d=f=0)||h.pop();)if((a?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++d){E&&((p[G]||(p[G]={}))[e]=[B,d]);if(p===t)break}d-=i;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[G])return o(n);if(o.length>1){i=[e,e,"",n];return T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),s=i.length;s--;){r=et(e,i[s]);e[r]=!(t[r]=i[s])}}):function(e){return o(e,0,i)}}return o}},pseudos:{not:r(function(e){var t=[],n=[],i=L(e.replace(lt,"$1"));return i[G]?r(function(e,t,n,r){for(var o,s=i(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;i(t,null,o,n);t[0]=null;return!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){e=e.replace(bt,Tt);return function(t){return(t.textContent||t.innerText||S(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(bt,Tt).toLowerCase();return function(t){var n;do if(n=F?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){n=n.toLowerCase();return n===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===D},focus:function(e){return e===_.activeElement&&(!_.hasFocus||_.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return gt.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,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}};T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=a(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=l(x);p.prototype=T.filters=T.pseudos;T.setFilters=new p;C=t.tokenize=function(e,n){var r,i,o,s,a,l,u,c=V[e+" "];if(c)return n?0:c.slice(0);a=e;l=[];u=T.preFilter;for(;a;){if(!r||(i=ut.exec(a))){i&&(a=a.slice(i[0].length)||a);l.push(o=[])}r=!1;if(i=ct.exec(a)){r=i.shift();o.push({value:r,type:i[0].replace(lt," ")});a=a.slice(r.length)}for(s in T.filter)if((i=ht[s].exec(a))&&(!u[s]||(i=u[s](i)))){r=i.shift();o.push({value:r,type:s,matches:i});a=a.slice(r.length)}if(!r)break}return n?a.length:a?t.error(e):V(e,l).slice(0)};L=t.compile=function(e,t){var n,r=[],i=[],o=W[e+" "];if(!o){t||(t=C(e));n=t.length;for(;n--;){o=E(t[n]);o[G]?r.push(o):i.push(o)}o=W(e,y(i,r));o.selector=e}return o};A=t.select=function(e,t,n,r){var i,o,s,a,l,u="function"==typeof e&&e,p=!r&&C(e=u.selector||e);n=n||[];if(1===p.length){o=p[0]=p[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&b.getById&&9===t.nodeType&&F&&T.relative[o[1].type]){t=(T.find.ID(s.matches[0].replace(bt,Tt),t)||[])[0];if(!t)return n;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}i=ht.needsContext.test(e)?0:o.length;for(;i--;){s=o[i];if(T.relative[a=s.type])break;if((l=T.find[a])&&(r=l(s.matches[0].replace(bt,Tt),yt.test(o[0].type)&&c(t.parentNode)||t))){o.splice(i,1);e=r.length&&d(o);if(!e){J.apply(n,r);return n}break}}}(u||L(e,p))(r,t,!F,n,yt.test(e)&&c(t.parentNode)||t);return n};b.sortStable=G.split("").sort(z).join("")===G;b.detectDuplicates=!!R;O();b.sortDetached=i(function(e){return 1&e.compareDocumentPosition(_.createElement("div"))});i(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});b.attributes&&i(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});i(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=ct;ot.expr=ct.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=ct.uniqueSort;ot.text=ct.getText;ot.isXMLDoc=ct.isXML;ot.contains=ct.contains;var pt=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,n){var r=t[0];n&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;i>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;i>t;t++)ot.find(e,r[t],n);n=this.pushStack(i>1?ot.unique(n):n);n.selector=this.selector?this.selector+" "+e:e;return n},filter:function(e){return this.pushStack(i(this,e||[],!1))},not:function(e){return this.pushStack(i(this,e||[],!0))},is:function(e){return!!i(this,"string"==typeof e&&pt.test(e)?ot(e):e||[],!1).length}});var ht,gt=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,vt=ot.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!n||!n[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(n[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:gt,!0));if(dt.test(n[1])&&ot.isPlainObject(t))for(n in t)ot.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}r=gt.getElementById(n[2]);if(r&&r.parentNode){if(r.id!==n[2])return ht.find(e);this.length=1;this[0]=r}this.context=gt;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};vt.prototype=ot.fn;ht=ot(gt);var Et=/^(?:parents|prev(?:Until|All))/,yt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!ot(i).is(n));){1===i.nodeType&&r.push(i);i=i[t]}return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});ot.fn.extend({has:function(e){var t,n=ot(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],s=pt.test(e)||"string"!=typeof e?ot(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(s?s.index(n)>-1:1===n.nodeType&&ot.find.matchesSelector(n,e))){o.push(n);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,n){return ot.dir(e,"parentNode",n)},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,n){return ot.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return ot.dir(e,"previousSibling",n)},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(n,r){var i=ot.map(this,t,n);"Until"!==e.slice(-5)&&(r=n);r&&"string"==typeof r&&(i=ot.filter(r,i));if(this.length>1){yt[e]||(i=ot.unique(i));Et.test(e)&&(i=i.reverse())}return this.pushStack(i)}});var xt=/\S+/g,bt={};ot.Callbacks=function(e){e="string"==typeof e?bt[e]||s(e):ot.extend({},e);var t,n,r,i,o,a,l=[],u=!e.once&&[],c=function(s){n=e.memory&&s;r=!0;o=a||0;a=0;i=l.length;t=!0;for(;l&&i>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){n=!1;break}t=!1;l&&(u?u.length&&c(u.shift()):n?l=[]:p.disable())},p={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,n){var r=ot.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})})(arguments);if(t)i=l.length;else if(n){a=r;c(n)}}return this},remove:function(){l&&ot.each(arguments,function(e,n){for(var r;(r=ot.inArray(n,l,r))>-1;){l.splice(r,1);if(t){i>=r&&i--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];i=0;return this},disable:function(){l=u=n=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;n||p.disable();return this},locked:function(){return!u},fireWith:function(e,n){if(l&&(!r||u)){n=n||[];n=[e,n.slice?n.slice():n];t?u.push(n):c(n)}return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!r}};return p};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")]],n="pending",r={state:function(){return n},always:function(){i.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(n){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},i={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock);i[o[0]]=function(){i[o[0]+"With"](this===i?r:this,arguments);return this};i[o[0]+"With"]=s.fireWith});r.promise(i);e&&e.call(i,i);return i},when:function(e){var t,n,r,i=0,o=K.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,n,r){return function(i){n[e]=this;r[e]=arguments.length>1?K.call(arguments):i;r===t?l.notifyWith(n,r):--a||l.resolveWith(n,r)}};if(s>1){t=new Array(s);n=new Array(s);r=new Array(s);for(;s>i;i++)o[i]&&ot.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Tt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!gt.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Tt.resolveWith(gt,[ot]);if(ot.fn.triggerHandler){ot(gt).triggerHandler("ready");ot(gt).off("ready")}}}}});ot.ready.promise=function(e){if(!Tt){Tt=ot.Deferred();if("complete"===gt.readyState)setTimeout(ot.ready);else if(gt.addEventListener){gt.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{gt.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var n=!1;try{n=null==t.frameElement&>.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!ot.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a();ot.ready()}}()}}return Tt.promise(e)};var St,Nt="undefined";for(St in ot(rt))break;rt.ownLast="0"!==St;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,n,r;n=gt.getElementsByTagName("body")[0];if(n&&n.style){t=gt.createElement("div");r=gt.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(t);if(typeof t.style.zoom!==Nt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(n.style.zoom=1)}n.removeChild(r)}});(function(){var e=gt.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Ct=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Lt=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!c(e)},data:function(e,t,n){return p(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return p(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var n,r,i,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){i=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){n=s.length;for(;n--;)if(s[n]){r=s[n].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,i[r])}}ot._data(o,"parsedAttrs",!0)}}return i}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,n){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);n&&(!r||ot.isArray(n)?r=ot._data(e,t,ot.makeArray(n)):r.push(n));return r||[]}},dequeue:function(e,t){t=t||"fx";var n=ot.queue(e,t),r=n.length,i=n.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===i){i=n.shift();r--}if(i){"fx"===t&&n.unshift("inprogress");delete o.stop;i.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return ot._data(e,n)||ot._data(e,n,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,n)})})}});ot.fn.extend({queue:function(e,t){var n=2;if("string"!=typeof e){t=e;e="fx";n--}return arguments.length<n?ot.queue(this[0],e):void 0===t?this:this.each(function(){var n=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==n[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 n,r=1,i=ot.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){n=ot._data(o[s],e+"queueHooks");if(n&&n.empty){r++;n.empty.add(a)}}a();return i.promise(t)}});var At=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,It=["Top","Right","Bottom","Left"],wt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Rt=ot.access=function(e,t,n,r,i,o,s){var a=0,l=e.length,u=null==n;if("object"===ot.type(n)){i=!0;for(a in n)ot.access(e,t,a,n[a],!0,o,s)}else if(void 0!==r){i=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,n){return u.call(ot(e),n)}}if(t)for(;l>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)))}return i?e:u?t.call(e):l?t(e[0],n):o},Ot=/^(?:checkbox|radio)$/i;(function(){var e=gt.createElement("input"),t=gt.createElement("div"),n=gt.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==gt.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;n.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;n.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,n,r=gt.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){n="on"+e;if(!(rt[e+"Bubbles"]=n in t)){r.setAttribute(n,"t");rt[e+"Bubbles"]=r.attributes[n].expando===!1}}r=null})();var _t=/^(?:input|select|textarea)$/i,Dt=/^key/,Ft=/^(?:mouse|pointer|contextmenu)|click/,kt=/^(?:focusinfocus|focusoutblur)$/,Pt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,n,r,i){var o,s,a,l,u,c,p,d,f,h,g,m=ot._data(e);if(m){if(n.handler){l=n;n=l.handler;i=l.selector}n.guid||(n.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(c=m.handle)){c=m.handle=function(e){return typeof ot===Nt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(c.elem,arguments)};c.elem=e}t=(t||"").match(xt)||[""];a=t.length;for(;a--;){o=Pt.exec(t[a])||[];f=g=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(i?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};p=ot.extend({type:f,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ot.expr.match.needsContext.test(i),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(f,c,!1):e.attachEvent&&e.attachEvent("on"+f,c))}if(u.add){u.add.call(e,p);p.handler.guid||(p.handler.guid=n.guid)}i?d.splice(d.delegateCount++,0,p):d.push(p);ot.event.global[f]=!0}}e=null}},remove:function(e,t,n,r,i){var o,s,a,l,u,c,p,d,f,h,g,m=ot.hasData(e)&&ot._data(e);if(m&&(c=m.events)){t=(t||"").match(xt)||[""];u=t.length;for(;u--;){a=Pt.exec(t[u])||[];f=g=a[1];h=(a[2]||"").split(".").sort();if(f){p=ot.event.special[f]||{};f=(r?p.delegateType:p.bindType)||f;d=c[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!i&&g!==s.origType||n&&n.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;p.remove&&p.remove.call(e,s)}}if(l&&!d.length){p.teardown&&p.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete c[f]}}else for(f in c)ot.event.remove(e,f+t[u],n,r,!0)}if(ot.isEmptyObject(c)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,n,r,i){var o,s,a,l,u,c,p,d=[r||gt],f=nt.call(e,"type")?e.type:e,h=nt.call(e,"namespace")?e.namespace.split("."):[];a=c=r=r||gt;if(3!==r.nodeType&&8!==r.nodeType&&!kt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=i?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);n=null==n?[e]:ot.makeArray(n,[e]);u=ot.event.special[f]||{};if(i||!u.trigger||u.trigger.apply(r,n)!==!1){if(!i&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;kt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);c=a}c===(r.ownerDocument||gt)&&d.push(c.defaultView||c.parentWindow||t)}p=0;for(;(a=d[p++])&&!e.isPropagationStopped();){e.type=p>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,n);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,n);e.result===!1&&e.preventDefault()}}e.type=f;if(!i&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),n)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){c=r[s];c&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(g){}ot.event.triggered=void 0;c&&(r[s]=c)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,n,r,i,o,s=[],a=K.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(i=s[t++])&&!e.isPropagationStopped();){e.currentTarget=i.elem;o=0;for(;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;n=((ot.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,a);if(void 0!==n&&(e.result=n)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var n,r,i,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)){i=[];for(o=0;a>o;o++){r=t[o];n=r.selector+" ";void 0===i[n]&&(i[n]=r.needsContext?ot(n,this).index(l)>=0:ot.find(n,this,null,[l]).length);i[n]&&i.push(r)}i.length&&s.push({elem:l,handlers:i})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=Ft.test(i)?this.mouseHooks:Dt.test(i)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){n=r[t];e[n]=o[n]}e.target||(e.target=o.srcElement||gt);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||gt;i=r.documentElement;n=r.body;e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0);e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==g()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===g()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=ot.extend(new ot.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(i,null,t):ot.event.dispatch.call(t,i);i.isDefaultPrevented()&&n.preventDefault()}};ot.removeEvent=gt.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;if(e.detachEvent){typeof e[r]===Nt&&(e[r]=null);e.detachEvent(r,n)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;
this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;if(!i||i!==r&&!ot.contains(r,i)){e.type=o.origType;n=o.handler.apply(this,arguments);e.type=t}return n}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(n&&!ot._data(n,"submitBubbles")){ot.event.add(n,"submit._submit",function(e){e._submit_bubble=!0});ot._data(n,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(_t.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(_t.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!_t.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=ot._data(r,t);i||r.addEventListener(e,n,!0);ot._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=ot._data(r,t)-1;if(i)ot._data(r,t,i);else{r.removeEventListener(e,n,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){if("string"!=typeof t){n=n||t;t=void 0}for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r){r=t;n=t=void 0}else if(null==r)if("string"==typeof t){r=n;n=void 0}else{r=n;n=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===i){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}if(t===!1||"function"==typeof t){n=t;t=void 0}n===!1&&(n=h);return this.each(function(){ot.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ot.event.trigger(e,t,n,!0):void 0}});var Mt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",jt=/ jQuery\d+="(?:null|\d+)"/g,Gt=new RegExp("<(?:"+Mt+")[\\s/>]","i"),Ut=/^\s+/,Bt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,qt=/<([\w:]+)/,Ht=/<tbody/i,Vt=/<|&#?\w+;/,Wt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,$t=/^$|\/(?:java|ecma)script/i,Xt=/^true\/(.*)/,Yt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Kt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(gt),Jt=Qt.appendChild(gt.createElement("div"));Kt.optgroup=Kt.option;Kt.tbody=Kt.tfoot=Kt.colgroup=Kt.caption=Kt.thead;Kt.th=Kt.td;ot.extend({clone:function(e,t,n){var r,i,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Gt.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Jt.innerHTML=e.outerHTML;Jt.removeChild(o=Jt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=v(o);a=v(e);for(s=0;null!=(i=a[s]);++s)r[s]&&N(i,r[s])}if(t)if(n){a=a||v(e);r=r||v(o);for(s=0;null!=(i=a[s]);s++)S(i,r[s])}else S(e,o);r=v(o,"script");r.length>0&&T(r,!l&&v(e,"script"));r=a=i=null;return o},buildFragment:function(e,t,n,r){for(var i,o,s,a,l,u,c,p=e.length,d=m(t),f=[],h=0;p>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Vt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(qt.exec(o)||["",""])[1].toLowerCase();c=Kt[l]||Kt._default;a.innerHTML=c[1]+o.replace(Bt,"<$1></$2>")+c[2];i=c[0];for(;i--;)a=a.lastChild;!rt.leadingWhitespace&&Ut.test(o)&&f.push(t.createTextNode(Ut.exec(o)[0]));if(!rt.tbody){o="table"!==l||Ht.test(o)?"<table>"!==c[1]||Ht.test(o)?0:a:a.firstChild;i=o&&o.childNodes.length;for(;i--;)ot.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(v(f,"input"),E);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=v(d.appendChild(o),"script");s&&T(a);if(n){i=0;for(;o=a[i++];)$t.test(o.type||"")&&n.push(o)}}a=null;return d},cleanData:function(e,t){for(var n,r,i,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,c=ot.event.special;null!=(n=e[s]);s++)if(t||ot.acceptData(n)){i=n[a];o=i&&l[i];if(o){if(o.events)for(r in o.events)c[r]?ot.event.remove(n,r):ot.removeEvent(n,r,o.handle);if(l[i]){delete l[i];u?delete n[a]:typeof n.removeAttribute!==Nt?n.removeAttribute(a):n[a]=null;Y.push(i)}}}}});ot.fn.extend({text:function(e){return Rt(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||gt).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?ot.filter(e,this):this,i=0;null!=(n=r[i]);i++){t||1!==n.nodeType||ot.cleanData(v(n));if(n.parentNode){t&&ot.contains(n.ownerDocument,n)&&T(v(n,"script"));n.parentNode.removeChild(n)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(v(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Rt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(jt,""):void 0;if(!("string"!=typeof e||Wt.test(e)||!rt.htmlSerialize&&Gt.test(e)||!rt.leadingWhitespace&&Ut.test(e)||Kt[(qt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Bt,"<$1></$2>");try{for(;r>n;n++){t=this[n]||{};if(1===t.nodeType){ot.cleanData(v(t,!1));t.innerHTML=e}}t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(v(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var n,r,i,o,s,a,l=0,u=this.length,c=this,p=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(n){var r=c.eq(n);f&&(e[0]=d.call(this,n,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);n=a.firstChild;1===a.childNodes.length&&(a=n);if(n){o=ot.map(v(a,"script"),x);i=o.length;for(;u>l;l++){r=a;if(l!==p){r=ot.clone(r,!0,!0);i&&ot.merge(o,v(r,"script"))}t.call(this[l],r,l)}if(i){s=o[o.length-1].ownerDocument;ot.map(o,b);for(l=0;i>l;l++){r=o[l];$t.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Yt,"")))}}a=n=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 n,r=0,i=[],o=ot(e),s=o.length-1;s>=r;r++){n=r===s?this:this.clone(!0);ot(o[r])[t](n);J.apply(i,n.get())}return this.pushStack(i)}});var Zt,en={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;n=gt.getElementsByTagName("body")[0];if(n&&n.style){t=gt.createElement("div");r=gt.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(t);if(typeof t.style.zoom!==Nt){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(gt.createElement("div")).style.width="5px";e=3!==t.offsetWidth}n.removeChild(r);return e}}})();var tn,nn,rn=/^margin/,on=new RegExp("^("+At+")(?!px)[a-z%]+$","i"),sn=/^(top|right|bottom|left)$/;if(t.getComputedStyle){tn=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};nn=function(e,t,n){var r,i,o,s,a=e.style;n=n||tn(e);s=n?n.getPropertyValue(t)||n[t]:void 0;if(n){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(on.test(s)&&rn.test(t)){r=a.width;i=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=n.width;a.width=r;a.minWidth=i;a.maxWidth=o}}return void 0===s?s:s+""}}else if(gt.documentElement.currentStyle){tn=function(e){return e.currentStyle};nn=function(e,t,n){var r,i,o,s,a=e.style;n=n||tn(e);s=n?n[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(on.test(s)&&!sn.test(t)){r=a.left;i=e.runtimeStyle;o=i&&i.left;o&&(i.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(i.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,n,r,i;n=gt.getElementsByTagName("body")[0];if(n&&n.style){e=gt.createElement("div");r=gt.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(e);e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;i=e.appendChild(gt.createElement("div"));i.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";i.style.marginRight=i.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(i,null)||{}).marginRight);e.removeChild(i)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";i=e.getElementsByTagName("td");i[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===i[0].offsetHeight;if(a){i[0].style.display="";i[1].style.display="none";a=0===i[0].offsetHeight}n.removeChild(r)}}var n,r,i,o,s,a,l;n=gt.createElement("div");n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";i=n.getElementsByTagName("a")[0];r=i&&i.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;n.style.backgroundClip="content-box";n.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===n.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,n,r){var i,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i};var an=/alpha\([^)]*\)/i,ln=/opacity\s*=\s*([^)]*)/,un=/^(none|table(?!-c[ea]).+)/,cn=new RegExp("^("+At+")(.*)$","i"),pn=new RegExp("^([+-])=("+At+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},fn={letterSpacing:"0",fontWeight:"400"},hn=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=I(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===n)return s&&"get"in s&&void 0!==(i=s.get(e,!1,r))?i:l[t];o=typeof n;if("string"===o&&(i=pn.exec(n))){n=(i[1]+1)*i[2]+parseFloat(ot.css(e,t));o="number"}if(null!=n&&n===n){"number"!==o||ot.cssNumber[a]||(n+="px");rt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(n=s.set(e,n,r))))try{l[t]=n}catch(u){}}}},css:function(e,t,n,r){var i,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=I(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,n));void 0===o&&(o=nn(e,t,r));"normal"===o&&t in fn&&(o=fn[t]);if(""===n||n){i=parseFloat(o);return n===!0||ot.isNumeric(i)?i||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,n,r){return n?un.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,dn,function(){return _(e,t,r)}):_(e,t,r):void 0},set:function(e,n,r){var i=r&&tn(e);return R(e,n,r?O(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,i),i):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ln.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=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(an,""))&&n.removeAttribute){n.removeAttribute("filter");if(""===t||r&&!r.filter)return}n.filter=an.test(o)?o.replace(an,i):o+" "+i}});ot.cssHooks.marginRight=A(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},nn,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+It[r]+t]=o[r]||o[r-2]||o[0];return i}};rn.test(e)||(ot.cssHooks[e+t].set=R)});ot.fn.extend({css:function(e,t){return Rt(this,function(e,t,n){var r,i,o={},s=0;if(ot.isArray(t)){r=tn(e);i=t.length;for(;i>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==n?ot.style(e,t,n):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return w(this,!0)},hide:function(){return w(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){wt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=D;D.prototype={constructor:D,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||(ot.cssNumber[n]?"":"px")},cur:function(){var e=D.propHooks[this.prop];return e&&e.get?e.get(this):D.propHooks._default.get(this)},run:function(e){var t,n=D.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);n&&n.set?n.set(this):D.propHooks._default.set(this);return this}};D.prototype.init.prototype=D.prototype;D.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};D.propHooks.scrollTop=D.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=D.prototype.init;ot.fx.step={};var gn,mn,vn=/^(?:toggle|show|hide)$/,En=new RegExp("^(?:([+-])=|)("+At+")([a-z%]*)$","i"),yn=/queueHooks$/,xn=[M],bn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=En.exec(t),o=i&&i[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&En.exec(ot.css(n.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];i=i||[];s=+r||1;do{a=a||".5";s/=a;ot.style(n.elem,e,s+o)}while(a!==(a=n.cur()/r)&&1!==a&&--l)}if(i){s=n.start=+s||+r||0;n.unit=o;n.end=i[1]?s+(i[1]+1)*i[2]:+i[2]}return n}]};ot.Animation=ot.extend(G,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++){n=e[r];bn[n]=bn[n]||[];bn[n].unshift(t)}},prefilter:function(e,t){t?xn.unshift(e):xn.push(e)}});ot.speed=function(e,t,n){var r=e&&"object"==typeof e?ot.extend({},e):{complete:n||!n&&t||ot.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,n,r){return this.filter(wt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=ot.isEmptyObject(e),o=ot.speed(t,n,r),s=function(){var t=G(this,ot.extend({},e),o);(i||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return i||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop;t(n)};if("string"!=typeof e){n=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&yn.test(i)&&r(s[i]);for(i=o.length;i--;)if(o[i].elem===this&&(null==e||o[i].queue===e)){o[i].anim.stop(n);t=!1;o.splice(i,1)}(t||!n)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,n=ot._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=ot.timers,s=r?r.length:0;n.finish=!0;ot.queue(this,e,[]);i&&i.stop&&i.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});ot.each(["toggle","show","hide"],function(e,t){var n=ot.fn[t];ot.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(k(t,!0),e,r,i)}});ot.each({slideDown:k("show"),slideUp:k("hide"),slideToggle:k("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,n=0;gn=ot.now();for(;n<t.length;n++){e=t[n];e()||t[n]!==e||t.splice(n--,1)}t.length||ot.fx.stop();gn=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(){mn||(mn=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(mn);mn=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})};(function(){var e,t,n,r,i;t=gt.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];n=gt.createElement("select");i=n.appendChild(gt.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=i.selected;rt.enctype=!!gt.createElement("form").enctype;n.disabled=!0;rt.optDisabled=!i.disabled;e=gt.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Tn=/\r/g;ot.fn.extend({val:function(e){var t,n,r,i=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(n){var i;if(1===this.nodeType){i=r?e.call(this,n,ot(this).val()):e;null==i?i="":"number"==typeof i?i+="":ot.isArray(i)&&(i=ot.map(i,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,i,"value")||(this.value=i)}})}if(i){t=ot.valHooks[i.type]||ot.valHooks[i.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(n=t.get(i,"value")))return n;n=i.value;return"string"==typeof n?n.replace(Tn,""):null==n?"":n}}});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,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,l=0>i?a:o?i:0;a>l;l++){n=r[l];if(!(!n.selected&&l!==i||(rt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&ot.nodeName(n.parentNode,"optgroup"))){t=ot(n).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var n,r,i=e.options,o=ot.makeArray(t),s=i.length;s--;){r=i[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(a){r.scrollHeight}else r.selected=!1}n||(e.selectedIndex=-1);return i}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Sn,Nn,Cn=ot.expr.attrHandle,Ln=/^(?:checked|selected)$/i,An=rt.getSetAttribute,In=rt.input;ot.fn.extend({attr:function(e,t){return Rt(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,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===Nt)return ot.prop(e,t,n);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Nn:Sn)}if(void 0===n){if(r&&"get"in r&&null!==(i=r.get(e,t)))return i;i=ot.find.attr(e,t);return null==i?void 0:i}if(null!==n){if(r&&"set"in r&&void 0!==(i=r.set(e,n,t)))return i;e.setAttribute(t,n+"");return n}ot.removeAttr(e,t)}},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(xt);if(o&&1===e.nodeType)for(;n=o[i++];){r=ot.propFix[n]||n;ot.expr.match.bool.test(n)?In&&An||!Ln.test(n)?e[r]=!1:e[ot.camelCase("default-"+n)]=e[r]=!1:ot.attr(e,n,"");e.removeAttribute(An?n:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var n=e.value;e.setAttribute("type",t);n&&(e.value=n);return t}}}}});Nn={set:function(e,t,n){t===!1?ot.removeAttr(e,n):In&&An||!Ln.test(n)?e.setAttribute(!An&&ot.propFix[n]||n,n):e[ot.camelCase("default-"+n)]=e[n]=!0;return n}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Cn[t]||ot.find.attr;Cn[t]=In&&An||!Ln.test(t)?function(e,t,r){var i,o;if(!r){o=Cn[t];Cn[t]=i;i=null!=n(e,t,r)?t.toLowerCase():null;Cn[t]=o}return i}:function(e,t,n){return n?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});In&&An||(ot.attrHooks.value={set:function(e,t,n){if(!ot.nodeName(e,"input"))return Sn&&Sn.set(e,t,n);e.defaultValue=t;return void 0}});if(!An){Sn={set:function(e,t,n){var r=e.getAttributeNode(n);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n));r.value=t+="";return"value"===n||t===e.getAttribute(n)?t:void 0}};Cn.id=Cn.name=Cn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Sn.set};ot.attrHooks.contenteditable={set:function(e,t,n){Sn.set(e,""===t?!1:t,n)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,n){if(""===n){e.setAttribute(t,"auto");return n}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var wn=/^(?:input|select|textarea|button|object)$/i,Rn=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Rt(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;i=ot.propHooks[t]}return void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):wn.test(e.nodeName)||Rn.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var On=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,n,r,i,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(xt)||[];for(;l>a;a++){n=this[a];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(On," "):" ");if(r){o=0;for(;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");s=ot.trim(r);n.className!==s&&(n.className=s)}}}return this},removeClass:function(e){var t,n,r,i,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(xt)||[];for(;l>a;a++){n=this[a];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(On," "):"");if(r){o=0;for(;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");s=e?ot.trim(r):"";n.className!==s&&(n.className=s)}}}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(n){ot(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=ot(this),o=e.match(xt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else if(n===Nt||"boolean"===n){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+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(On," ").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,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var _n=ot.now(),Dn=/\?/,Fn=/(,)|(\[|{)|(}|])|"(?:[^"\\\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 n,r=null,i=ot.trim(e+"");return i&&!ot.trim(i.replace(Fn,function(e,t,i,o){n&&t&&(r=0);if(0===r)return e;n=i||t;r+=!o-!i;return""}))?Function("return "+i)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var n,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;n=r.parseFromString(e,"text/xml")}else{n=new ActiveXObject("Microsoft.XMLDOM");n.async="false";n.loadXML(e)}}catch(i){n=void 0}n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return n};var kn,Pn,Mn=/#.*$/,jn=/([?&])_=[^&]*/,Gn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Un=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Bn=/^(?:GET|HEAD)$/,qn=/^\/\//,Hn=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Vn={},Wn={},zn="*/".concat("*");try{Pn=location.href}catch($n){Pn=gt.createElement("a");Pn.href="";Pn=Pn.href}kn=Hn.exec(Pn.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Pn,type:"GET",isLocal:Un.test(kn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":zn,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?q(q(e,ot.ajaxSettings),t):q(ot.ajaxSettings,e)},ajaxPrefilter:U(Vn),ajaxTransport:U(Wn),ajax:function(e,t){function n(e,t,n,r){var i,c,v,E,x,T=t;if(2!==y){y=2;a&&clearTimeout(a);u=void 0;s=r||"";b.readyState=e>0?4:0;i=e>=200&&300>e||304===e;n&&(E=H(p,b,n));E=V(p,E,b,i);if(i){if(p.ifModified){x=b.getResponseHeader("Last-Modified");x&&(ot.lastModified[o]=x);x=b.getResponseHeader("etag");x&&(ot.etag[o]=x)}if(204===e||"HEAD"===p.type)T="nocontent";else if(304===e)T="notmodified";else{T=E.state;c=E.data;v=E.error;i=!v}}else{v=T;if(e||!T){T="error";0>e&&(e=0)}}b.status=e;b.statusText=(t||T)+"";i?h.resolveWith(d,[c,T,b]):h.rejectWith(d,[b,T,v]);b.statusCode(m);m=void 0;l&&f.trigger(i?"ajaxSuccess":"ajaxError",[b,p,i?c:v]);g.fireWith(d,[b,T]);if(l){f.trigger("ajaxComplete",[b,p]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,i,o,s,a,l,u,c,p=ot.ajaxSetup({},t),d=p.context||p,f=p.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),g=ot.Callbacks("once memory"),m=p.statusCode||{},v={},E={},y=0,x="canceled",b={readyState:0,getResponseHeader:function(e){var t;
if(2===y){if(!c){c={};for(;t=Gn.exec(s);)c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===y?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();if(!y){e=E[n]=E[n]||e;v[e]=t}return this},overrideMimeType:function(e){y||(p.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>y)for(t in e)m[t]=[m[t],e[t]];else b.always(e[b.status]);return this},abort:function(e){var t=e||x;u&&u.abort(t);n(0,t);return this}};h.promise(b).complete=g.add;b.success=b.done;b.error=b.fail;p.url=((e||p.url||Pn)+"").replace(Mn,"").replace(qn,kn[1]+"//");p.type=t.method||t.type||p.method||p.type;p.dataTypes=ot.trim(p.dataType||"*").toLowerCase().match(xt)||[""];if(null==p.crossDomain){r=Hn.exec(p.url.toLowerCase());p.crossDomain=!(!r||r[1]===kn[1]&&r[2]===kn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(kn[3]||("http:"===kn[1]?"80":"443")))}p.data&&p.processData&&"string"!=typeof p.data&&(p.data=ot.param(p.data,p.traditional));B(Vn,p,t,b);if(2===y)return b;l=ot.event&&p.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");p.type=p.type.toUpperCase();p.hasContent=!Bn.test(p.type);o=p.url;if(!p.hasContent){if(p.data){o=p.url+=(Dn.test(o)?"&":"?")+p.data;delete p.data}p.cache===!1&&(p.url=jn.test(o)?o.replace(jn,"$1_="+_n++):o+(Dn.test(o)?"&":"?")+"_="+_n++)}if(p.ifModified){ot.lastModified[o]&&b.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&b.setRequestHeader("If-None-Match",ot.etag[o])}(p.data&&p.hasContent&&p.contentType!==!1||t.contentType)&&b.setRequestHeader("Content-Type",p.contentType);b.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+zn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)b.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(d,b,p)===!1||2===y))return b.abort();x="abort";for(i in{success:1,error:1,complete:1})b[i](p[i]);u=B(Wn,p,t,b);if(u){b.readyState=1;l&&f.trigger("ajaxSend",[b,p]);p.async&&p.timeout>0&&(a=setTimeout(function(){b.abort("timeout")},p.timeout));try{y=1;u.send(v,n)}catch(T){if(!(2>y))throw T;n(-1,T)}}else n(-1,"No Transport");return b},getJSON:function(e,t,n){return ot.get(e,t,n,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,n,r,i){if(ot.isFunction(n)){i=i||r;r=n;n=void 0}return ot.ajax({url:e,type:t,dataType:i,data:n,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(n){ot(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xn=/%20/g,Yn=/\[\]$/,Kn=/\r?\n/g,Qn=/^(?:submit|button|image|reset|file)$/i,Jn=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var n,r=[],i=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){i(this.name,this.value)});else for(n in e)W(n,e[n],t,i);return r.join("&").replace(Xn,"+")};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")&&Jn.test(this.nodeName)&&!Qn.test(e)&&(this.checked||!Ot.test(e))}).map(function(e,t){var n=ot(this).val();return null==n?null:ot.isArray(n)?ot.map(n,function(e){return{name:t.name,value:e.replace(Kn,"\r\n")}}):{name:t.name,value:n.replace(Kn,"\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()||$()}:z;var Zn=0,er={},tr=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in er)er[e](void 0,!0)});rt.cors=!!tr&&"withCredentials"in tr;tr=rt.ajax=!!tr;tr&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),s=++Zn;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null);t=function(n,i){var a,l,u;if(t&&(i||4===o.readyState)){delete er[s];t=void 0;o.onreadystatechange=ot.noop;if(i)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=er[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=gt.head||ot("head")[0]||gt.documentElement;return{send:function(r,i){t=gt.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,n){if(n||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;n||i(200,"success")}};n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var nr=[],rr=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=nr.pop()||ot.expando+"_"+_n++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,n,r){var i,o,s,a=e.jsonp!==!1&&(rr.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&rr.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){i=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(rr,"$1"+i):e.jsonp!==!1&&(e.url+=(Dn.test(e.url)?"&":"?")+e.jsonp+"="+i);e.converters["script json"]=function(){s||ot.error(i+" was not called");return s[0]};e.dataTypes[0]="json";o=t[i];t[i]=function(){s=arguments};r.always(function(){t[i]=o;if(e[i]){e.jsonpCallback=n.jsonpCallback;nr.push(i)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){n=t;t=!1}t=t||gt;var r=dt.exec(e),i=!n&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,i);i&&i.length&&ot(i).remove();return ot.merge([],r.childNodes)};var ir=ot.fn.load;ot.fn.load=function(e,t,n){if("string"!=typeof e&&ir)return ir.apply(this,arguments);var r,i,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){n=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,i||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var or=t.document.documentElement;ot.offset={setOffset:function(e,t,n){var r,i,o,s,a,l,u,c=ot.css(e,"position"),p=ot(e),d={};"static"===c&&(e.style.position="relative");a=p.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===c||"fixed"===c)&&ot.inArray("auto",[o,l])>-1;if(u){r=p.position();s=r.top;i=r.left}else{s=parseFloat(o)||0;i=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,n,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+i);"using"in t?t.using.call(e,d):p.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,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,i))return r;typeof i.getBoundingClientRect!==Nt&&(r=i.getBoundingClientRect());n=X(o);return{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(n=e.offset());n.top+=ot.css(e[0],"borderTopWidth",!0);n.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-n.top-ot.css(r,"marginTop",!0),left:t.left-n.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||or;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||or})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);ot.fn[e]=function(r){return Rt(this,function(e,r,i){var o=X(e);if(void 0===i)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(n?ot(o).scrollLeft():i,n?i:ot(o).scrollTop()):e[r]=i;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=A(rt.pixelPosition,function(e,n){if(n){n=nn(e,t);return on.test(n)?ot(e).position()[t]+"px":n}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){ot.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),s=n||(r===!0||i===!0?"margin":"border");return Rt(this,function(t,n,r){var i;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){i=t.documentElement;return Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])}return void 0===r?ot.css(t,n,s):ot.style(t,n,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var sr=t.jQuery,ar=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=ar);e&&t.jQuery===ot&&(t.jQuery=sr);return ot};typeof n===Nt&&(t.jQuery=t.$=ot);return ot})},{}],5:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.MicroPlugin=i()})(this,function(){var e={};e.mixin=function(e){e.plugins={};e.prototype.initializePlugins=function(e){var n,r,i,o=this,s=[];o.plugins={names:[],settings:{},requested:{},loaded:{}};if(t.isArray(e))for(n=0,r=e.length;r>n;n++)if("string"==typeof e[n])s.push(e[n]);else{o.plugins.settings[e[n].name]=e[n].options;s.push(e[n].name)}else if(e)for(i in e)if(e.hasOwnProperty(i)){o.plugins.settings[i]=e[i];s.push(i)}for(;s.length;)o.require(s.shift())};e.prototype.loadPlugin=function(t){var n=this,r=n.plugins,i=e.plugins[t];if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin');r.requested[t]=!0;r.loaded[t]=i.fn.apply(n,[n.plugins.settings[t]||{}]);r.names.push(t)};e.prototype.require=function(e){var t=this,n=t.plugins;if(!t.plugins.loaded.hasOwnProperty(e)){if(n.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")');t.loadPlugin(e)}return n.loaded[e]};e.define=function(t,n){e.plugins[t]={name:t,fn:n}}};var t={isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}};return e})},{}],6:[function(t,n,r){(function(i,o){"function"==typeof e&&e.amd?e(["jquery","sifter","microplugin"],o):"object"==typeof r?n.exports=o(t("jquery"),t("sifter"),t("microplugin")):i.Selectize=o(i.jQuery,i.Sifter,i.MicroPlugin)})(this,function(e,t,n){"use strict";var r=function(e,t){if("string"!=typeof t||t.length){var n="string"==typeof t?new RegExp(t,"i"):t,r=function(e){var t=0;if(3===e.nodeType){var i=e.data.search(n);if(i>=0&&e.data.length>0){var o=e.data.match(n),s=document.createElement("span");s.className="highlight";var a=e.splitText(i),l=(a.splitText(o[0].length),a.cloneNode(!0));s.appendChild(l);a.parentNode.replaceChild(s,a);t=1}}else if(1===e.nodeType&&e.childNodes&&!/(script|style)/i.test(e.tagName))for(var u=0;u<e.childNodes.length;++u)u+=r(e.childNodes[u]);return t};return e.each(function(){r(this)})}},i=function(){};i.prototype={on:function(e,t){this._events=this._events||{};this._events[e]=this._events[e]||[];this._events[e].push(t)},off:function(e,t){var n=arguments.length;if(0===n)return delete this._events;if(1===n)return delete this._events[e];this._events=this._events||{};e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(t),1)},trigger:function(e){this._events=this._events||{};if(e in this._events!=!1)for(var t=0;t<this._events[e].length;t++)this._events[e][t].apply(this,Array.prototype.slice.call(arguments,1))}};i.mixin=function(e){for(var t=["on","off","trigger"],n=0;n<t.length;n++)e.prototype[t[n]]=i.prototype[t[n]]};var o=/Mac/.test(navigator.userAgent),s=65,a=13,l=27,u=37,c=38,p=80,d=39,f=40,h=78,g=8,m=46,v=16,E=o?91:17,y=o?18:17,x=9,b=1,T=2,S=function(e){return"undefined"!=typeof e},N=function(e){return"undefined"==typeof e||null===e?null:"boolean"==typeof e?e?"1":"0":e+""},C=function(e){return(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},L=function(e){return(e+"").replace(/\$/g,"$$$$")},A={};A.before=function(e,t,n){var r=e[t];e[t]=function(){n.apply(e,arguments);return r.apply(e,arguments)}};A.after=function(e,t,n){var r=e[t];e[t]=function(){var t=r.apply(e,arguments);n.apply(e,arguments);return t}};var I=function(t,n){if(!e.isArray(n))return n;var r,i,o={};for(r=0,i=n.length;i>r;r++)n[r].hasOwnProperty(t)&&(o[n[r][t]]=n[r]);return o},w=function(e){var t=!1;return function(){if(!t){t=!0;e.apply(this,arguments)}}},R=function(e,t){var n;return function(){var r=this,i=arguments;window.clearTimeout(n);n=window.setTimeout(function(){e.apply(r,i)},t)}},O=function(e,t,n){var r,i=e.trigger,o={};e.trigger=function(){var n=arguments[0];if(-1===t.indexOf(n))return i.apply(e,arguments);o[n]=arguments;return void 0};n.apply(e,[]);e.trigger=i;for(r in o)o.hasOwnProperty(r)&&i.apply(e,o[r])},_=function(e,t,n,r){e.on(t,n,function(t){for(var n=t.target;n&&n.parentNode!==e[0];)n=n.parentNode;t.currentTarget=n;return r.apply(this,[t])})},D=function(e){var t={};if("selectionStart"in e){t.start=e.selectionStart;t.length=e.selectionEnd-t.start}else if(document.selection){e.focus();var n=document.selection.createRange(),r=document.selection.createRange().text.length;n.moveStart("character",-e.value.length);t.start=n.text.length-r;t.length=r}return t},F=function(e,t,n){var r,i,o={};if(n)for(r=0,i=n.length;i>r;r++)o[n[r]]=e.css(n[r]);else o=e.css();t.css(o)},k=function(t,n){if(!t)return 0;var r=e("<test>").css({position:"absolute",top:-99999,left:-99999,width:"auto",padding:0,whiteSpace:"pre"}).text(t).appendTo("body");F(n,r,["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"]);var i=r.width();r.remove();return i},P=function(e){var t=null,n=function(n,r){var i,o,s,a,l,u,c,p;n=n||window.event||{};r=r||{};if(!n.metaKey&&!n.altKey&&(r.force||e.data("grow")!==!1)){i=e.val();if(n.type&&"keydown"===n.type.toLowerCase()){o=n.keyCode;s=o>=97&&122>=o||o>=65&&90>=o||o>=48&&57>=o||32===o;if(o===m||o===g){p=D(e[0]);p.length?i=i.substring(0,p.start)+i.substring(p.start+p.length):o===g&&p.start?i=i.substring(0,p.start-1)+i.substring(p.start+1):o===m&&"undefined"!=typeof p.start&&(i=i.substring(0,p.start)+i.substring(p.start+1))}else if(s){u=n.shiftKey;c=String.fromCharCode(n.keyCode);c=u?c.toUpperCase():c.toLowerCase();i+=c}}a=e.attr("placeholder");!i&&a&&(i=a);l=k(i,e)+4;if(l!==t){t=l;e.width(l);e.triggerHandler("resize")}}};e.on("keydown keyup update blur",n);n()},M=function(n,r){var i,o,s=this;o=n[0];o.selectize=s;var a=window.getComputedStyle&&window.getComputedStyle(o,null);i=a?a.getPropertyValue("direction"):o.currentStyle&&o.currentStyle.direction;i=i||n.parents("[dir]:first").attr("dir")||"";e.extend(s,{settings:r,$input:n,tagType:"select"===o.tagName.toLowerCase()?b:T,rtl:/rtl/i.test(i),eventNS:".selectize"+ ++M.count,highlightedValue:null,isOpen:!1,isDisabled:!1,isRequired:n.is("[required]"),isInvalid:!1,isLocked:!1,isFocused:!1,isInputHidden:!1,isSetup:!1,isShiftDown:!1,isCmdDown:!1,isCtrlDown:!1,ignoreFocus:!1,ignoreBlur:!1,ignoreHover:!1,hasOptions:!1,currentResults:null,lastValue:"",caretPos:0,loading:0,loadedSearches:{},$activeOption:null,$activeItems:[],optgroups:{},options:{},userOptions:{},items:[],renderCache:{},onSearchChange:null===r.loadThrottle?s.onSearchChange:R(s.onSearchChange,r.loadThrottle)});s.sifter=new t(this.options,{diacritics:r.diacritics});e.extend(s.options,I(r.valueField,r.options));delete s.settings.options;e.extend(s.optgroups,I(r.optgroupValueField,r.optgroups));delete s.settings.optgroups;s.settings.mode=s.settings.mode||(1===s.settings.maxItems?"single":"multi");"boolean"!=typeof s.settings.hideSelected&&(s.settings.hideSelected="multi"===s.settings.mode);s.initializePlugins(s.settings.plugins);s.setupCallbacks();s.setupTemplates();s.setup()};i.mixin(M);n.mixin(M);e.extend(M.prototype,{setup:function(){var t,n,r,i,s,a,l,u,c,p,d=this,f=d.settings,h=d.eventNS,g=e(window),m=e(document),x=d.$input;l=d.settings.mode;u=x.attr("tabindex")||"";c=x.attr("class")||"";t=e("<div>").addClass(f.wrapperClass).addClass(c).addClass(l);n=e("<div>").addClass(f.inputClass).addClass("items").appendTo(t);r=e('<input type="text" autocomplete="off" />').appendTo(n).attr("tabindex",u);a=e(f.dropdownParent||t);i=e("<div>").addClass(f.dropdownClass).addClass(l).hide().appendTo(a);s=e("<div>").addClass(f.dropdownContentClass).appendTo(i);d.settings.copyClassesToDropdown&&i.addClass(c);t.css({width:x[0].style.width});if(d.plugins.names.length){p="plugin-"+d.plugins.names.join(" plugin-");t.addClass(p);i.addClass(p)}(null===f.maxItems||f.maxItems>1)&&d.tagType===b&&x.attr("multiple","multiple");d.settings.placeholder&&r.attr("placeholder",f.placeholder);x.attr("autocorrect")&&r.attr("autocorrect",x.attr("autocorrect"));x.attr("autocapitalize")&&r.attr("autocapitalize",x.attr("autocapitalize"));d.$wrapper=t;d.$control=n;d.$control_input=r;d.$dropdown=i;d.$dropdown_content=s;i.on("mouseenter","[data-selectable]",function(){return d.onOptionHover.apply(d,arguments)});i.on("mousedown","[data-selectable]",function(){return d.onOptionSelect.apply(d,arguments)});_(n,"mousedown","*:not(input)",function(){return d.onItemSelect.apply(d,arguments)});P(r);n.on({mousedown:function(){return d.onMouseDown.apply(d,arguments)},click:function(){return d.onClick.apply(d,arguments)}});r.on({mousedown:function(e){e.stopPropagation()},keydown:function(){return d.onKeyDown.apply(d,arguments)},keyup:function(){return d.onKeyUp.apply(d,arguments)},keypress:function(){return d.onKeyPress.apply(d,arguments)},resize:function(){d.positionDropdown.apply(d,[])},blur:function(){return d.onBlur.apply(d,arguments)},focus:function(){d.ignoreBlur=!1;return d.onFocus.apply(d,arguments)},paste:function(){return d.onPaste.apply(d,arguments)}});m.on("keydown"+h,function(e){d.isCmdDown=e[o?"metaKey":"ctrlKey"];d.isCtrlDown=e[o?"altKey":"ctrlKey"];d.isShiftDown=e.shiftKey});m.on("keyup"+h,function(e){e.keyCode===y&&(d.isCtrlDown=!1);e.keyCode===v&&(d.isShiftDown=!1);e.keyCode===E&&(d.isCmdDown=!1)});m.on("mousedown"+h,function(e){if(d.isFocused){if(e.target===d.$dropdown[0]||e.target.parentNode===d.$dropdown[0])return!1;d.$control.has(e.target).length||e.target===d.$control[0]||d.blur()}});g.on(["scroll"+h,"resize"+h].join(" "),function(){d.isOpen&&d.positionDropdown.apply(d,arguments)});g.on("mousemove"+h,function(){d.ignoreHover=!1});this.revertSettings={$children:x.children().detach(),tabindex:x.attr("tabindex")};x.attr("tabindex",-1).hide().after(d.$wrapper);if(e.isArray(f.items)){d.setValue(f.items);delete f.items}x[0].validity&&x.on("invalid"+h,function(e){e.preventDefault();d.isInvalid=!0;d.refreshState()});d.updateOriginalInput();d.refreshItems();d.refreshState();d.updatePlaceholder();d.isSetup=!0;x.is(":disabled")&&d.disable();d.on("change",this.onChange);x.data("selectize",d);x.addClass("selectized");d.trigger("initialize");f.preload===!0&&d.onSearchChange("")},setupTemplates:function(){var t=this,n=t.settings.labelField,r=t.settings.optgroupLabelField,i={optgroup:function(e){return'<div class="optgroup">'+e.html+"</div>"},optgroup_header:function(e,t){return'<div class="optgroup-header">'+t(e[r])+"</div>"},option:function(e,t){return'<div class="option">'+t(e[n])+"</div>"},item:function(e,t){return'<div class="item">'+t(e[n])+"</div>"},option_create:function(e,t){return'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>"}};t.settings.render=e.extend({},i,t.settings.render)},setupCallbacks:function(){var e,t,n={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad"};for(e in n)if(n.hasOwnProperty(e)){t=this.settings[n[e]];t&&this.on(e,t)}},onClick:function(e){var t=this;if(!t.isFocused){t.focus();e.preventDefault()}},onMouseDown:function(t){{var n=this,r=t.isDefaultPrevented();e(t.target)}if(n.isFocused){if(t.target!==n.$control_input[0]){"single"===n.settings.mode?n.isOpen?n.close():n.open():r||n.setActiveItem(null);return!1}}else r||window.setTimeout(function(){n.focus()},0)},onChange:function(){this.$input.trigger("change")},onPaste:function(e){var t=this;(t.isFull()||t.isInputHidden||t.isLocked)&&e.preventDefault()},onKeyPress:function(e){if(this.isLocked)return e&&e.preventDefault();var t=String.fromCharCode(e.keyCode||e.which);if(this.settings.create&&t===this.settings.delimiter){this.createItem();e.preventDefault();return!1}},onKeyDown:function(e){var t=(e.target===this.$control_input[0],this);if(t.isLocked)e.keyCode!==x&&e.preventDefault();else{switch(e.keyCode){case s:if(t.isCmdDown){t.selectAll();return}break;case l:t.close();return;case h:if(!e.ctrlKey||e.altKey)break;case f:if(!t.isOpen&&t.hasOptions)t.open();else if(t.$activeOption){t.ignoreHover=!0;var n=t.getAdjacentOption(t.$activeOption,1);n.length&&t.setActiveOption(n,!0,!0)}e.preventDefault();return;case p:if(!e.ctrlKey||e.altKey)break;case c:if(t.$activeOption){t.ignoreHover=!0;var r=t.getAdjacentOption(t.$activeOption,-1);r.length&&t.setActiveOption(r,!0,!0)}e.preventDefault();return;case a:t.isOpen&&t.$activeOption&&t.onOptionSelect({currentTarget:t.$activeOption});e.preventDefault();return;case u:t.advanceSelection(-1,e);return;case d:t.advanceSelection(1,e);return;case x:if(t.settings.selectOnTab&&t.isOpen&&t.$activeOption){t.onOptionSelect({currentTarget:t.$activeOption});e.preventDefault()}t.settings.create&&t.createItem()&&e.preventDefault();return;case g:case m:t.deleteSelection(e);return}!t.isFull()&&!t.isInputHidden||(o?e.metaKey:e.ctrlKey)||e.preventDefault()}},onKeyUp:function(e){var t=this;if(t.isLocked)return e&&e.preventDefault();var n=t.$control_input.val()||"";if(t.lastValue!==n){t.lastValue=n;t.onSearchChange(n);t.refreshOptions();t.trigger("type",n)}},onSearchChange:function(e){var t=this,n=t.settings.load;if(n&&!t.loadedSearches.hasOwnProperty(e)){t.loadedSearches[e]=!0;t.load(function(r){n.apply(t,[e,r])})}},onFocus:function(e){var t=this;t.isFocused=!0;if(t.isDisabled){t.blur();e&&e.preventDefault();return!1}if(!t.ignoreFocus){"focus"===t.settings.preload&&t.onSearchChange("");if(!t.$activeItems.length){t.showInput();t.setActiveItem(null);t.refreshOptions(!!t.settings.openOnFocus)}t.refreshState()}},onBlur:function(e){var t=this;t.isFocused=!1;if(!t.ignoreFocus)if(t.ignoreBlur||document.activeElement!==t.$dropdown_content[0]){t.settings.create&&t.settings.createOnBlur&&t.createItem(!1);t.close();t.setTextboxValue("");t.setActiveItem(null);t.setActiveOption(null);t.setCaret(t.items.length);t.refreshState()}else{t.ignoreBlur=!0;t.onFocus(e)}},onOptionHover:function(e){this.ignoreHover||this.setActiveOption(e.currentTarget,!1)},onOptionSelect:function(t){var n,r,i=this;if(t.preventDefault){t.preventDefault();t.stopPropagation()}r=e(t.currentTarget);if(r.hasClass("create"))i.createItem();else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);!i.settings.hideSelected&&t.type&&/mouse/.test(t.type)&&i.setActiveOption(i.getOption(n))}}},onItemSelect:function(e){var t=this;if(!t.isLocked&&"multi"===t.settings.mode){e.preventDefault();t.setActiveItem(e.currentTarget,e)}},load:function(e){var t=this,n=t.$wrapper.addClass("loading");t.loading++;e.apply(t,[function(e){t.loading=Math.max(t.loading-1,0);if(e&&e.length){t.addOption(e);t.refreshOptions(t.isFocused&&!t.isInputHidden)}t.loading||n.removeClass("loading");t.trigger("load",e)}])},setTextboxValue:function(e){var t=this.$control_input,n=t.val()!==e;if(n){t.val(e).triggerHandler("update");this.lastValue=e}},getValue:function(){return this.tagType===b&&this.$input.attr("multiple")?this.items:this.items.join(this.settings.delimiter)},setValue:function(e){O(this,["change"],function(){this.clear();this.addItems(e)})},setActiveItem:function(t,n){var r,i,o,s,a,l,u,c,p=this;if("single"!==p.settings.mode){t=e(t);if(t.length){r=n&&n.type.toLowerCase();if("mousedown"===r&&p.isShiftDown&&p.$activeItems.length){c=p.$control.children(".active:last");s=Array.prototype.indexOf.apply(p.$control[0].childNodes,[c[0]]);a=Array.prototype.indexOf.apply(p.$control[0].childNodes,[t[0]]);if(s>a){u=s;s=a;a=u}for(i=s;a>=i;i++){l=p.$control[0].childNodes[i];if(-1===p.$activeItems.indexOf(l)){e(l).addClass("active");p.$activeItems.push(l)}}n.preventDefault()}else if("mousedown"===r&&p.isCtrlDown||"keydown"===r&&this.isShiftDown)if(t.hasClass("active")){o=p.$activeItems.indexOf(t[0]);p.$activeItems.splice(o,1);t.removeClass("active")}else p.$activeItems.push(t.addClass("active")[0]);else{e(p.$activeItems).removeClass("active");p.$activeItems=[t.addClass("active")[0]]}p.hideInput();this.isFocused||p.focus()}else{e(p.$activeItems).removeClass("active");p.$activeItems=[];p.isFocused&&p.showInput()}}},setActiveOption:function(t,n,r){var i,o,s,a,l,u=this;u.$activeOption&&u.$activeOption.removeClass("active");u.$activeOption=null;t=e(t);if(t.length){u.$activeOption=t.addClass("active");if(n||!S(n)){i=u.$dropdown_content.height();o=u.$activeOption.outerHeight(!0);n=u.$dropdown_content.scrollTop()||0;s=u.$activeOption.offset().top-u.$dropdown_content.offset().top+n;a=s;l=s-i+o;s+o>i+n?u.$dropdown_content.stop().animate({scrollTop:l},r?u.settings.scrollDuration:0):n>s&&u.$dropdown_content.stop().animate({scrollTop:a},r?u.settings.scrollDuration:0)}}},selectAll:function(){var e=this;if("single"!==e.settings.mode){e.$activeItems=Array.prototype.slice.apply(e.$control.children(":not(input)").addClass("active"));if(e.$activeItems.length){e.hideInput();e.close()}e.focus()}},hideInput:function(){var e=this;e.setTextboxValue("");e.$control_input.css({opacity:0,position:"absolute",left:e.rtl?1e4:-1e4});e.isInputHidden=!0},showInput:function(){this.$control_input.css({opacity:1,position:"relative",left:0});this.isInputHidden=!1},focus:function(){var e=this;if(!e.isDisabled){e.ignoreFocus=!0;e.$control_input[0].focus();window.setTimeout(function(){e.ignoreFocus=!1;e.onFocus()},0)}},blur:function(){this.$control_input.trigger("blur")},getScoreFunction:function(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())},getSearchOptions:function(){var e=this.settings,t=e.sortField;"string"==typeof t&&(t={field:t});return{fields:e.searchField,conjunction:e.searchConjunction,sort:t}},search:function(t){var n,r,i,o=this,s=o.settings,a=this.getSearchOptions();if(s.score){i=o.settings.score.apply(this,[t]);if("function"!=typeof i)throw new Error('Selectize "score" setting must be a function that returns a function')}if(t!==o.lastQuery){o.lastQuery=t;r=o.sifter.search(t,e.extend(a,{score:i}));o.currentResults=r}else r=e.extend(!0,{},o.currentResults);if(s.hideSelected)for(n=r.items.length-1;n>=0;n--)-1!==o.items.indexOf(N(r.items[n].id))&&r.items.splice(n,1);return r},refreshOptions:function(t){var n,i,o,s,a,l,u,c,p,d,f,h,g,m,v,E;"undefined"==typeof t&&(t=!0);var y=this,x=e.trim(y.$control_input.val()),b=y.search(x),T=y.$dropdown_content,S=y.$activeOption&&N(y.$activeOption.attr("data-value"));s=b.items.length;"number"==typeof y.settings.maxOptions&&(s=Math.min(s,y.settings.maxOptions));a={};if(y.settings.optgroupOrder){l=y.settings.optgroupOrder;for(n=0;n<l.length;n++)a[l[n]]=[]}else l=[];for(n=0;s>n;n++){u=y.options[b.items[n].id];c=y.render("option",u);p=u[y.settings.optgroupField]||"";d=e.isArray(p)?p:[p];for(i=0,o=d&&d.length;o>i;i++){p=d[i];y.optgroups.hasOwnProperty(p)||(p="");if(!a.hasOwnProperty(p)){a[p]=[];l.push(p)}a[p].push(c)}}f=[];for(n=0,s=l.length;s>n;n++){p=l[n];if(y.optgroups.hasOwnProperty(p)&&a[p].length){h=y.render("optgroup_header",y.optgroups[p])||"";h+=a[p].join("");f.push(y.render("optgroup",e.extend({},y.optgroups[p],{html:h})))}else f.push(a[p].join(""))}T.html(f.join(""));if(y.settings.highlight&&b.query.length&&b.tokens.length)for(n=0,s=b.tokens.length;s>n;n++)r(T,b.tokens[n].regex);if(!y.settings.hideSelected)for(n=0,s=y.items.length;s>n;n++)y.getOption(y.items[n]).addClass("selected");g=y.canCreate(x);if(g){T.prepend(y.render("option_create",{input:x}));E=e(T[0].childNodes[0])}y.hasOptions=b.items.length>0||g;if(y.hasOptions){if(b.items.length>0){v=S&&y.getOption(S);v&&v.length?m=v:"single"===y.settings.mode&&y.items.length&&(m=y.getOption(y.items[0]));m&&m.length||(m=E&&!y.settings.addPrecedence?y.getAdjacentOption(E,1):T.find("[data-selectable]:first"))}else m=E;y.setActiveOption(m);t&&!y.isOpen&&y.open()}else{y.setActiveOption(null);t&&y.isOpen&&y.close()}},addOption:function(t){var n,r,i,o=this;if(e.isArray(t))for(n=0,r=t.length;r>n;n++)o.addOption(t[n]);else{i=N(t[o.settings.valueField]);if("string"==typeof i&&!o.options.hasOwnProperty(i)){o.userOptions[i]=!0;o.options[i]=t;o.lastQuery=null;o.trigger("option_add",i,t)}}},addOptionGroup:function(e,t){this.optgroups[e]=t;this.trigger("optgroup_add",e,t)},updateOption:function(t,n){var r,i,o,s,a,l,u=this;t=N(t);o=N(n[u.settings.valueField]);if(null!==t&&u.options.hasOwnProperty(t)){if("string"!=typeof o)throw new Error("Value must be set in option data");if(o!==t){delete u.options[t];s=u.items.indexOf(t);-1!==s&&u.items.splice(s,1,o)}u.options[o]=n;a=u.renderCache.item;l=u.renderCache.option;if(a){delete a[t];delete a[o]}if(l){delete l[t];delete l[o]}if(-1!==u.items.indexOf(o)){r=u.getItem(t);i=e(u.render("item",n));r.hasClass("active")&&i.addClass("active");r.replaceWith(i)}u.lastQuery=null;u.isOpen&&u.refreshOptions(!1)}},removeOption:function(e){var t=this;e=N(e);var n=t.renderCache.item,r=t.renderCache.option;n&&delete n[e];r&&delete r[e];
delete t.userOptions[e];delete t.options[e];t.lastQuery=null;t.trigger("option_remove",e);t.removeItem(e)},clearOptions:function(){var e=this;e.loadedSearches={};e.userOptions={};e.renderCache={};e.options=e.sifter.items={};e.lastQuery=null;e.trigger("option_clear");e.clear()},getOption:function(e){return this.getElementWithValue(e,this.$dropdown_content.find("[data-selectable]"))},getAdjacentOption:function(t,n){var r=this.$dropdown.find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()},getElementWithValue:function(t,n){t=N(t);if("undefined"!=typeof t&&null!==t)for(var r=0,i=n.length;i>r;r++)if(n[r].getAttribute("data-value")===t)return e(n[r]);return e()},getItem:function(e){return this.getElementWithValue(e,this.$control.children())},addItems:function(t){for(var n=e.isArray(t)?t:[t],r=0,i=n.length;i>r;r++){this.isPending=i-1>r;this.addItem(n[r])}},addItem:function(t){O(this,["change"],function(){var n,r,i,o,s,a=this,l=a.settings.mode;t=N(t);if(-1===a.items.indexOf(t)){if(a.options.hasOwnProperty(t)){"single"===l&&a.clear();if("multi"!==l||!a.isFull()){n=e(a.render("item",a.options[t]));s=a.isFull();a.items.splice(a.caretPos,0,t);a.insertAtCaret(n);(!a.isPending||!s&&a.isFull())&&a.refreshState();if(a.isSetup){i=a.$dropdown_content.find("[data-selectable]");if(!a.isPending){r=a.getOption(t);o=a.getAdjacentOption(r,1).attr("data-value");a.refreshOptions(a.isFocused&&"single"!==l);o&&a.setActiveOption(a.getOption(o))}!i.length||a.isFull()?a.close():a.positionDropdown();a.updatePlaceholder();a.trigger("item_add",t,n);a.updateOriginalInput()}}}}else"single"===l&&a.close()})},removeItem:function(e){var t,n,r,i=this;t="object"==typeof e?e:i.getItem(e);e=N(t.attr("data-value"));n=i.items.indexOf(e);if(-1!==n){t.remove();if(t.hasClass("active")){r=i.$activeItems.indexOf(t[0]);i.$activeItems.splice(r,1)}i.items.splice(n,1);i.lastQuery=null;!i.settings.persist&&i.userOptions.hasOwnProperty(e)&&i.removeOption(e);n<i.caretPos&&i.setCaret(i.caretPos-1);i.refreshState();i.updatePlaceholder();i.updateOriginalInput();i.positionDropdown();i.trigger("item_remove",e)}},createItem:function(t){var n=this,r=e.trim(n.$control_input.val()||""),i=n.caretPos;if(!n.canCreate(r))return!1;n.lock();"undefined"==typeof t&&(t=!0);var o="function"==typeof n.settings.create?this.settings.create:function(e){var t={};t[n.settings.labelField]=e;t[n.settings.valueField]=e;return t},s=w(function(e){n.unlock();if(e&&"object"==typeof e){var r=N(e[n.settings.valueField]);if("string"==typeof r){n.setTextboxValue("");n.addOption(e);n.setCaret(i);n.addItem(r);n.refreshOptions(t&&"single"!==n.settings.mode)}}}),a=o.apply(this,[r,s]);"undefined"!=typeof a&&s(a);return!0},refreshItems:function(){this.lastQuery=null;if(this.isSetup)for(var e=0;e<this.items.length;e++)this.addItem(this.items);this.refreshState();this.updateOriginalInput()},refreshState:function(){var e,t=this;if(t.isRequired){t.items.length&&(t.isInvalid=!1);t.$control_input.prop("required",e)}t.refreshClasses()},refreshClasses:function(){var t=this,n=t.isFull(),r=t.isLocked;t.$wrapper.toggleClass("rtl",t.rtl);t.$control.toggleClass("focus",t.isFocused).toggleClass("disabled",t.isDisabled).toggleClass("required",t.isRequired).toggleClass("invalid",t.isInvalid).toggleClass("locked",r).toggleClass("full",n).toggleClass("not-full",!n).toggleClass("input-active",t.isFocused&&!t.isInputHidden).toggleClass("dropdown-active",t.isOpen).toggleClass("has-options",!e.isEmptyObject(t.options)).toggleClass("has-items",t.items.length>0);t.$control_input.data("grow",!n&&!r)},isFull:function(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems},updateOriginalInput:function(){var e,t,n,r=this;if(r.tagType===b){n=[];for(e=0,t=r.items.length;t>e;e++)n.push('<option value="'+C(r.items[e])+'" selected="selected"></option>');n.length||this.$input.attr("multiple")||n.push('<option value="" selected="selected"></option>');r.$input.html(n.join(""))}else{r.$input.val(r.getValue());r.$input.attr("value",r.$input.val())}r.isSetup&&r.trigger("change",r.$input.val())},updatePlaceholder:function(){if(this.settings.placeholder){var e=this.$control_input;this.items.length?e.removeAttr("placeholder"):e.attr("placeholder",this.settings.placeholder);e.triggerHandler("update",{force:!0})}},open:function(){var e=this;if(!(e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull())){e.focus();e.isOpen=!0;e.refreshState();e.$dropdown.css({visibility:"hidden",display:"block"});e.positionDropdown();e.$dropdown.css({visibility:"visible"});e.trigger("dropdown_open",e.$dropdown)}},close:function(){var e=this,t=e.isOpen;"single"===e.settings.mode&&e.items.length&&e.hideInput();e.isOpen=!1;e.$dropdown.hide();e.setActiveOption(null);e.refreshState();t&&e.trigger("dropdown_close",e.$dropdown)},positionDropdown:function(){var e=this.$control,t="body"===this.settings.dropdownParent?e.offset():e.position();t.top+=e.outerHeight(!0);this.$dropdown.css({width:e.outerWidth(),top:t.top,left:t.left})},clear:function(){var e=this;if(e.items.length){e.$control.children(":not(input)").remove();e.items=[];e.lastQuery=null;e.setCaret(0);e.setActiveItem(null);e.updatePlaceholder();e.updateOriginalInput();e.refreshState();e.showInput();e.trigger("clear")}},insertAtCaret:function(t){var n=Math.min(this.caretPos,this.items.length);0===n?this.$control.prepend(t):e(this.$control[0].childNodes[n]).before(t);this.setCaret(n+1)},deleteSelection:function(t){var n,r,i,o,s,a,l,u,c,p=this;i=t&&t.keyCode===g?-1:1;o=D(p.$control_input[0]);p.$activeOption&&!p.settings.hideSelected&&(l=p.getAdjacentOption(p.$activeOption,-1).attr("data-value"));s=[];if(p.$activeItems.length){c=p.$control.children(".active:"+(i>0?"last":"first"));a=p.$control.children(":not(input)").index(c);i>0&&a++;for(n=0,r=p.$activeItems.length;r>n;n++)s.push(e(p.$activeItems[n]).attr("data-value"));if(t){t.preventDefault();t.stopPropagation()}}else(p.isFocused||"single"===p.settings.mode)&&p.items.length&&(0>i&&0===o.start&&0===o.length?s.push(p.items[p.caretPos-1]):i>0&&o.start===p.$control_input.val().length&&s.push(p.items[p.caretPos]));if(!s.length||"function"==typeof p.settings.onDelete&&p.settings.onDelete.apply(p,[s])===!1)return!1;"undefined"!=typeof a&&p.setCaret(a);for(;s.length;)p.removeItem(s.pop());p.showInput();p.positionDropdown();p.refreshOptions(!0);if(l){u=p.getOption(l);u.length&&p.setActiveOption(u)}return!0},advanceSelection:function(e,t){var n,r,i,o,s,a,l=this;if(0!==e){l.rtl&&(e*=-1);n=e>0?"last":"first";r=D(l.$control_input[0]);if(l.isFocused&&!l.isInputHidden){o=l.$control_input.val().length;s=0>e?0===r.start&&0===r.length:r.start===o;s&&!o&&l.advanceCaret(e,t)}else{a=l.$control.children(".active:"+n);if(a.length){i=l.$control.children(":not(input)").index(a);l.setActiveItem(null);l.setCaret(e>0?i+1:i)}}}},advanceCaret:function(e,t){var n,r,i=this;if(0!==e){n=e>0?"next":"prev";if(i.isShiftDown){r=i.$control_input[n]();if(r.length){i.hideInput();i.setActiveItem(r);t&&t.preventDefault()}}else i.setCaret(i.caretPos+e)}},setCaret:function(t){var n=this;t="single"===n.settings.mode?n.items.length:Math.max(0,Math.min(n.items.length,t));if(!n.isPending){var r,i,o,s;o=n.$control.children(":not(input)");for(r=0,i=o.length;i>r;r++){s=e(o[r]).detach();t>r?n.$control_input.before(s):n.$control.append(s)}}n.caretPos=t},lock:function(){this.close();this.isLocked=!0;this.refreshState()},unlock:function(){this.isLocked=!1;this.refreshState()},disable:function(){var e=this;e.$input.prop("disabled",!0);e.isDisabled=!0;e.lock()},enable:function(){var e=this;e.$input.prop("disabled",!1);e.isDisabled=!1;e.unlock()},destroy:function(){var t=this,n=t.eventNS,r=t.revertSettings;t.trigger("destroy");t.off();t.$wrapper.remove();t.$dropdown.remove();t.$input.html("").append(r.$children).removeAttr("tabindex").removeClass("selectized").attr({tabindex:r.tabindex}).show();t.$control_input.removeData("grow");t.$input.removeData("selectize");e(window).off(n);e(document).off(n);e(document.body).off(n);delete t.$input[0].selectize},render:function(e,t){var n,r,i="",o=!1,s=this,a=/^[\t ]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;if("option"===e||"item"===e){n=N(t[s.settings.valueField]);o=!!n}if(o){S(s.renderCache[e])||(s.renderCache[e]={});if(s.renderCache[e].hasOwnProperty(n))return s.renderCache[e][n]}i=s.settings.render[e].apply(this,[t,C]);("option"===e||"option_create"===e)&&(i=i.replace(a,"<$1 data-selectable"));if("optgroup"===e){r=t[s.settings.optgroupValueField]||"";i=i.replace(a,'<$1 data-group="'+L(C(r))+'"')}("option"===e||"item"===e)&&(i=i.replace(a,'<$1 data-value="'+L(C(n||""))+'"'));o&&(s.renderCache[e][n]=i);return i},clearCache:function(e){var t=this;"undefined"==typeof e?t.renderCache={}:delete t.renderCache[e]},canCreate:function(e){var t=this;if(!t.settings.create)return!1;var n=t.settings.createFilter;return!(!e.length||"function"==typeof n&&!n.apply(t,[e])||"string"==typeof n&&!new RegExp(n).test(e)||n instanceof RegExp&&!n.test(e))}});M.count=0;M.defaults={plugins:[],delimiter:",",persist:!0,diacritics:!0,create:!1,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,maxOptions:1e3,maxItems:null,hideSelected:null,addPrecedence:!1,selectOnTab:!1,preload:!1,allowEmptyOption:!1,scrollDuration:60,loadThrottle:300,dataAttr:"data-data",optgroupField:"optgroup",valueField:"value",labelField:"text",optgroupLabelField:"label",optgroupValueField:"value",optgroupOrder:null,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"selectize-control",inputClass:"selectize-input",dropdownClass:"selectize-dropdown",dropdownContentClass:"selectize-dropdown-content",dropdownParent:null,copyClassesToDropdown:!0,render:{}};e.fn.selectize=function(t){var n=e.fn.selectize.defaults,r=e.extend({},n,t),i=r.dataAttr,o=r.labelField,s=r.valueField,a=r.optgroupField,l=r.optgroupLabelField,u=r.optgroupValueField,c=function(t,n){var i,a,l,u,c=e.trim(t.val()||"");if(r.allowEmptyOption||c.length){l=c.split(r.delimiter);for(i=0,a=l.length;a>i;i++){u={};u[o]=l[i];u[s]=l[i];n.options[l[i]]=u}n.items=l}},p=function(t,n){var c,p,d,f,h=0,g=n.options,m=function(e){var t=i&&e.attr(i);return"string"==typeof t&&t.length?JSON.parse(t):null},v=function(t,i){var l,u;t=e(t);l=t.attr("value")||"";if(l.length||r.allowEmptyOption)if(g.hasOwnProperty(l))i&&(g[l].optgroup?e.isArray(g[l].optgroup)?g[l].optgroup.push(i):g[l].optgroup=[g[l].optgroup,i]:g[l].optgroup=i);else{u=m(t)||{};u[o]=u[o]||t.text();u[s]=u[s]||l;u[a]=u[a]||i;u.$order=++h;g[l]=u;t.is(":selected")&&n.items.push(l)}},E=function(t){var r,i,o,s,a;t=e(t);o=t.attr("label");if(o){s=m(t)||{};s[l]=o;s[u]=o;n.optgroups[o]=s}a=e("option",t);for(r=0,i=a.length;i>r;r++)v(a[r],o)};n.maxItems=t.attr("multiple")?null:1;f=t.children();for(c=0,p=f.length;p>c;c++){d=f[c].tagName.toLowerCase();"optgroup"===d?E(f[c]):"option"===d&&v(f[c])}};return this.each(function(){if(!this.selectize){var i,o=e(this),s=this.tagName.toLowerCase(),a=o.attr("placeholder")||o.attr("data-placeholder");a||r.allowEmptyOption||(a=o.children('option[value=""]').text());var l={placeholder:a,options:{},optgroups:{},items:[]};"select"===s?p(o,l):c(o,l);i=new M(o,e.extend(!0,{},n,l,t))}})};e.fn.selectize.defaults=M.defaults;M.define("drag_drop",function(){if(!e.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');if("multi"===this.settings.mode){var t=this;t.lock=function(){var e=t.lock;return function(){var n=t.$control.data("sortable");n&&n.disable();return e.apply(t,arguments)}}();t.unlock=function(){var e=t.unlock;return function(){var n=t.$control.data("sortable");n&&n.enable();return e.apply(t,arguments)}}();t.setup=function(){var n=t.setup;return function(){n.apply(this,arguments);var r=t.$control.sortable({items:"[data-value]",forcePlaceholderSize:!0,disabled:t.isLocked,start:function(e,t){t.placeholder.css("width",t.helper.css("width"));r.css({overflow:"visible"})},stop:function(){r.css({overflow:"hidden"});var n=t.$activeItems?t.$activeItems.slice():null,i=[];r.children("[data-value]").each(function(){i.push(e(this).attr("data-value"))});t.setValue(i);t.setActiveItem(n)}})}}()}});M.define("dropdown_header",function(t){var n=this;t=e.extend({title:"Untitled",headerClass:"selectize-dropdown-header",titleRowClass:"selectize-dropdown-header-title",labelClass:"selectize-dropdown-header-label",closeClass:"selectize-dropdown-header-close",html:function(e){return'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a href="javascript:void(0)" class="'+e.closeClass+'">×</a></div></div>'}},t);n.setup=function(){var r=n.setup;return function(){r.apply(n,arguments);n.$dropdown_header=e(t.html(t));n.$dropdown.prepend(n.$dropdown_header)}}()});M.define("optgroup_columns",function(t){var n=this;t=e.extend({equalizeWidth:!0,equalizeHeight:!0},t);this.getAdjacentOption=function(t,n){var r=t.closest("[data-group]").find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()};this.onKeyDown=function(){var e=n.onKeyDown;return function(t){var r,i,o,s;if(!this.isOpen||t.keyCode!==u&&t.keyCode!==d)return e.apply(this,arguments);n.ignoreHover=!0;s=this.$activeOption.closest("[data-group]");r=s.find("[data-selectable]").index(this.$activeOption);s=t.keyCode===u?s.prev("[data-group]"):s.next("[data-group]");o=s.find("[data-selectable]");i=o.eq(Math.min(o.length-1,r));i.length&&this.setActiveOption(i)}}();var r=function(){var e,t=r.width,n=document;if("undefined"==typeof t){e=n.createElement("div");e.innerHTML='<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';e=e.firstChild;n.body.appendChild(e);t=r.width=e.offsetWidth-e.clientWidth;n.body.removeChild(e)}return t},i=function(){var i,o,s,a,l,u,c;c=e("[data-group]",n.$dropdown_content);o=c.length;if(o&&n.$dropdown_content.width()){if(t.equalizeHeight){s=0;for(i=0;o>i;i++)s=Math.max(s,c.eq(i).height());c.css({height:s})}if(t.equalizeWidth){u=n.$dropdown_content.innerWidth()-r();a=Math.round(u/o);c.css({width:a});if(o>1){l=u-a*(o-1);c.eq(o-1).css({width:l})}}}};if(t.equalizeHeight||t.equalizeWidth){A.after(this,"positionDropdown",i);A.after(this,"refreshOptions",i)}});M.define("remove_button",function(t){if("single"!==this.settings.mode){t=e.extend({label:"×",title:"Remove",className:"remove",append:!0},t);var n=this,r='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+C(t.title)+'">'+t.label+"</a>",i=function(e,t){var n=e.search(/(<\/[^>]+>\s*)$/);return e.substring(0,n)+t+e.substring(n)};this.setup=function(){var o=n.setup;return function(){if(t.append){var s=n.settings.render.item;n.settings.render.item=function(){return i(s.apply(this,arguments),r)}}o.apply(this,arguments);this.$control.on("click","."+t.className,function(t){t.preventDefault();if(!n.isLocked){var r=e(t.currentTarget).parent();n.setActiveItem(r);n.deleteSelection()&&n.setCaret(n.items.length)}})}}()}});M.define("restore_on_backspace",function(e){var t=this;e.text=e.text||function(e){return e[this.settings.labelField]};this.onKeyDown=function(){var n=t.onKeyDown;return function(t){var r,i;if(t.keyCode===g&&""===this.$control_input.val()&&!this.$activeItems.length){r=this.caretPos-1;if(r>=0&&r<this.items.length){i=this.options[this.items[r]];if(this.deleteSelection(t)){this.setTextboxValue(e.text.apply(this,[i]));this.refreshOptions(!0)}t.preventDefault();return}}return n.apply(this,arguments)}}()});return M})},{jquery:4,microplugin:5,sifter:7}],7:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.Sifter=i()})(this,function(){var e=function(e,t){this.items=e;this.settings=t||{diacritics:!0}};e.prototype.tokenize=function(e){e=r(String(e||"").toLowerCase());if(!e||!e.length)return[];var t,n,o,a,l=[],u=e.split(/ +/);for(t=0,n=u.length;n>t;t++){o=i(u[t]);if(this.settings.diacritics)for(a in s)s.hasOwnProperty(a)&&(o=o.replace(new RegExp(a,"g"),s[a]));l.push({string:u[t],regex:new RegExp(o,"i")})}return l};e.prototype.iterator=function(e,t){var n;n=o(e)?Array.prototype.forEach||function(e){for(var t=0,n=this.length;n>t;t++)e(this[t],t,this)}:function(e){for(var t in this)this.hasOwnProperty(t)&&e(this[t],t,this)};n.apply(e,[t])};e.prototype.getScoreFunction=function(e,t){var n,r,i,o;n=this;e=n.prepareSearch(e,t);i=e.tokens;r=e.options.fields;o=i.length;var s=function(e,t){var n,r;if(!e)return 0;e=String(e||"");r=e.search(t.regex);if(-1===r)return 0;n=t.string.length/e.length;0===r&&(n+=.5);return n},a=function(){var e=r.length;return e?1===e?function(e,t){return s(t[r[0]],e)}:function(t,n){for(var i=0,o=0;e>i;i++)o+=s(n[r[i]],t);return o/e}:function(){return 0}}();return o?1===o?function(e){return a(i[0],e)}:"and"===e.options.conjunction?function(e){for(var t,n=0,r=0;o>n;n++){t=a(i[n],e);if(0>=t)return 0;r+=t}return r/o}:function(e){for(var t=0,n=0;o>t;t++)n+=a(i[t],e);return n/o}:function(){return 0}};e.prototype.getSortFunction=function(e,n){var r,i,o,s,a,l,u,c,p,d,f;o=this;e=o.prepareSearch(e,n);f=!e.query&&n.sort_empty||n.sort;p=function(e,t){return"$score"===e?t.score:o.items[t.id][e]};a=[];if(f)for(r=0,i=f.length;i>r;r++)(e.query||"$score"!==f[r].field)&&a.push(f[r]);if(e.query){d=!0;for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){d=!1;break}d&&a.unshift({field:"$score",direction:"desc"})}else for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){a.splice(r,1);break}c=[];for(r=0,i=a.length;i>r;r++)c.push("desc"===a[r].direction?-1:1);l=a.length;if(l){if(1===l){s=a[0].field;u=c[0];return function(e,n){return u*t(p(s,e),p(s,n))}}return function(e,n){var r,i,o;for(r=0;l>r;r++){o=a[r].field;i=c[r]*t(p(o,e),p(o,n));if(i)return i}return 0}}return null};e.prototype.prepareSearch=function(e,t){if("object"==typeof e)return e;t=n({},t);var r=t.fields,i=t.sort,s=t.sort_empty;r&&!o(r)&&(t.fields=[r]);i&&!o(i)&&(t.sort=[i]);s&&!o(s)&&(t.sort_empty=[s]);return{options:t,query:String(e||"").toLowerCase(),tokens:this.tokenize(e),total:0,items:[]}};e.prototype.search=function(e,t){var n,r,i,o,s=this;r=this.prepareSearch(e,t);t=r.options;e=r.query;o=t.score||s.getScoreFunction(r);e.length?s.iterator(s.items,function(e,i){n=o(e);(t.filter===!1||n>0)&&r.items.push({score:n,id:i})}):s.iterator(s.items,function(e,t){r.items.push({score:1,id:t})});i=s.getSortFunction(r,t);i&&r.items.sort(i);r.total=r.items.length;"number"==typeof t.limit&&(r.items=r.items.slice(0,t.limit));return r};var t=function(e,t){if("number"==typeof e&&"number"==typeof t)return e>t?1:t>e?-1:0;e=String(e||"").toLowerCase();t=String(t||"").toLowerCase();return e>t?1:t>e?-1:0},n=function(e){var t,n,r,i;for(t=1,n=arguments.length;n>t;t++){i=arguments[t];if(i)for(r in i)i.hasOwnProperty(r)&&(e[r]=i[r])}return e},r=function(e){return(e+"").replace(/^\s+|\s+$|/g,"")},i=function(e){return(e+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")},o=Array.isArray||$&&$.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s={a:"[aÀÁÂÃÄÅàáâãäåĀā]",c:"[cÇçćĆčČ]",d:"[dđĐďĎ]",e:"[eÈÉÊËèéêëěĚĒē]",i:"[iÌÍÎÏìíîïĪī]",n:"[nÑñňŇ]",o:"[oÒÓÔÕÕÖØòóôõöøŌō]",r:"[rřŘ]",s:"[sŠš]",t:"[tťŤ]",u:"[uÙÚÛÜùúûüůŮŪū]",y:"[yŸÿýÝ]",z:"[zŽž]"};return e})},{}],8:[function(t,n){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function i(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,n){if(null==n){n=t;t=null}null==t&&(t={});var r=s.get(e,t);n(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var n=s.deserialize(o.getItem(e));return void 0===n?t:n};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var n=o.key(t);e(n,s.get(n))}}}else if(a.documentElement.addBehavior){var c,p;try{p=new ActiveXObject("htmlfile");p.open();p.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');p.close();c=p.w.frames[0].document;o=c.createElement("div")}catch(d){o=a.createElement("div");c=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);c.appendChild(o);o.addBehavior("#default#userData");o.load(l);var n=e.apply(s,t);c.removeChild(o);return n}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,n){t=i(t);if(void 0===n)return s.remove(t);e.setAttribute(t,s.serialize(n));e.save(l);return n});s.get=f(function(e,t,n){t=i(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?n:r});s.remove=f(function(e,t){t=i(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var n,r=0;n=t[r];r++)e.removeAttribute(n.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=f(function(e,t){for(var n,r=e.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)t(n.name,s.deserialize(e.getAttribute(n.name)))})}try{var g="__storejs__";s.set(g,g);s.get(g)!=g&&(s.disabled=!0);s.remove(g)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],9:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"[email protected]",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"[email protected]",dist:{shasum:"56f463556922fe4f0eb97f650bb8cfe9700061a7"},_from:"[email protected]",_resolved:"https://registry.npmjs.org/yasgui-utils/-/yasgui-utils-1.5.0.tgz"}},{}],10:[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":9,"./storage.js":11,"./svg.js":12}],11:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){if(t){"string"==typeof i&&(i=r[i]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));n.set(e,{val:t,exp:i,time:(new Date).getTime()})}},remove:function(e){n.remove(e)},get:function(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:8}],12:[function(e,t){t.exports={draw:function(e,n){if(e){var r=t.exports.getElement(n);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,n=t.parseFromString(e,"text/xml"),r=n.documentElement,i=document.createElement("div");i.className="svgImg";i.appendChild(r);return i}return!1}}},{}],13:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,n){var r={},i={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,c=0,p=l.split("]["),d=p.length-1;if(/\[/.test(p[0])&&/\]$/.test(p[d])){p[d]=p[d].replace(/\]$/,"");p=p.shift().split("[").concat(p);d=p.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);n&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==i[s]?i[s]:s);if(d)for(;d>=c;c++){l=""===p[c]?u.length:p[c];u=u[l]=d>c?u[l]||(p[c+1]&&isNaN(p[c+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=n?void 0:"")});return r}},{jquery:26}],14:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,n="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",i=r+"|_",o="("+i+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+i+"|[0-9])("+i+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,c="("+r+")((("+o+")|\\.)*("+o+"))?",p="[0-9A-Fa-f]",d="(%"+p+p+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+i+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+i+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+i+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var g="("+c+")?:",m=g+e,v="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",E="[eE][\\+-]?[0-9]+",y="[0-9]+",x="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",b="(([0-9]+\\.[0-9]*"+E+")|(\\.[0-9]+"+E+")|([0-9]+"+E+"))",T="\\+"+y,S="\\+"+x,N="\\+"+b,C="-"+y,L="-"+x,A="-"+b,I="\\\\[tbnrf\\\\\"']",w="'(([^\\x27\\x5C\\x0A\\x0D])|"+I+")*'",R='"(([^\\x22\\x5C\\x0A\\x0D])|'+I+')*"',O="'''(('|'')?([^'\\\\]|"+I+"))*'''",_='"""(("|"")?([^"\\\\]|'+I+'))*"""',D="[\\x20\\x09\\x0D\\x0A]",F="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",k="("+D+"|("+F+"))*",P="\\("+k+"\\)",M="\\["+k+"\\]",j={terminal:[{name:"WS",regex:new RegExp("^"+D+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+F),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+n),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+v),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+b),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+x),style:"number"},{name:"INTEGER",regex:new RegExp("^"+y),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+N),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+L),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+O),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+_),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+w),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+R),style:"string"},{name:"NIL",regex:new RegExp("^"+P),style:"punc"},{name:"ANON",regex:new RegExp("^"+M),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+g),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return j}function n(e){var t=[],n=o[e];if(void 0!=n)for(var r in n)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,n=0;n<f.length;++n){t=e.match(f[n].regex,!0,!1);if(t)return{cat:f[n].name,style:f[n].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function i(){var n=e.column();t.errorStartPos=n;t.errorEndPos=n+p.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 c(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var p=r();if("<invalid_token>"==p.cat){if(1==t.OK){t.OK=!1;i()}t.complete=!1;return p.style}if("WS"==p.cat||"COMMENT"==p.cat){t.possibleCurrent=t.possibleNext;return p.style}for(var d,h=!1,g=p.cat;t.stack.length>0&&g&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][g];if(void 0!=m&&c(d)){for(var v=m.length-1;v>=0;--v)t.stack.push(m[v]);u(d)}else{t.OK=!1;t.complete=!1;i();t.stack.push(d)}}else if(d==g){h=!0;l(d);for(var E=!0,y=t.stack.length;y>0;--y){var x=o[t.stack[y-1]];x&&x.$||(E=!1)}t.complete=E;if(t.storeProperty&&"punc"!=g.cat){t.lastProperty=p.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;i()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;i()}t.possibleCurrent=t.possibleNext;t.possibleNext=n(t.stack[t.stack.length-1]);return p.style}function i(t,n){var r=0,i=t.stack.length-1;if(/^[\}\]\)]/.test(n)){for(var o=n.substr(0,1);i>=0;--i)if(t.stack[i]==o){--i;break}}else{var s=h[t.stack[i]];if(s){r+=s;--i}}for(;i>=0;--i){var s=g[t.stack[i]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",c="sparql11",p=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},g={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:p,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:n(c),possibleNext:n(c),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[c]}},indent:i,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:25}],15:[function(e,t){var n=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};n.prototype={insert:function(e,t){if(0!=e.length){var r,i,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new n);i=o.children[r];i.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var n,r,i=this;void 0===t&&(t=0);if(void 0!==i)if(t!==e.length){i.prefixes--;n=e[t];r=i.children[n];r.remove(e,t+1)}else i.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.words;n=e[t];r=i.children[n];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.prefixes;var n=e[t];r=i.children[n];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,n,r=this,i=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&i.push(e);for(t in r.children){n=r.children[t];i=i.concat(n.getAllWords(e+t))}return i},autoComplete:function(e,t){var n,r,i=this;if(0==e.length)return void 0===t?i.getAllWords(e):[];void 0===t&&(t=0);n=e[t];r=i.children[n];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],16:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(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 n(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var n=e.state.fullScreenRestore;t.style.width=n.width;t.style.height=n.height;window.scrollTo(n.scrollLeft,n.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,i,o){o==e.Init&&(o=!1);!o!=!i&&(i?t(r):n(r))})})},{"../../lib/codemirror":25}],17:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){function t(e,t,r,i){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 c=">"==u.charAt(1)?1:-1;if(r&&c>0!=(l==t.ch))return null;var p=e.getTokenTypeAt(s(t.line,l+1)),d=n(e,s(t.line,l+(c>0?1:0)),c,p||null,i);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:c>0}}function n(e,t,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],c=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,p=n>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=p;d+=n){var f=e.getLine(d);if(f){var h=n>0?0:f.length-1,g=n>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>n?1:0));for(;h!=g;h+=n){var m=f.charAt(h);if(c.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var v=a[m];if(">"==v.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-n==(n>0?e.lastLine():e.firstLine())?!1:null}function r(e,n,r){for(var i=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&t(e,l[u].head,!1,r);if(c&&e.getLine(c.from.line).length<=i){var p=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(c.from,s(c.from.line,c.from.ch+1),{className:p}));c.to&&e.getLine(c.to.line).length<=i&&a.push(e.markText(c.to,s(c.to.line,c.to.ch+1),{className:p}))}}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(!n)return d;setTimeout(d,800)}}function i(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,n,r){r&&r!=e.Init&&t.off("cursorActivity",i);if(n){t.state.matchBrackets="object"==typeof n?n:{};t.on("cursorActivity",i)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,n,r){return t(this,e,n,r)});e.defineExtension("scanForBracket",function(e,t,r,i){return n(this,e,t,r,i)})})},{"../../lib/codemirror":25}],18:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,n){function r(r){for(var i=n.ch,l=0;;){var u=0>=i?-1:a.lastIndexOf(r,i-1);if(-1!=u){if(1==l&&u<n.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;i=u-1}else{if(1==l)break;l=1;i=a.length}}}var i,o,s=n.line,a=t.getLine(s),l="{",u="}",i=r("{");if(null==i){l="[",u="]";i=r("[")}if(null!=i){var c,p,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var g=t.getLine(h),m=h==s?i:0;;){var v=g.indexOf(l,m),E=g.indexOf(u,m);0>v&&(v=g.length);0>E&&(E=g.length);m=Math.min(v,E);if(m==g.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==v)++d;else if(!--d){c=h;p=m;break e}++m}if(null!=c&&(s!=c||p!=i))return{from:e.Pos(s,i),to:e.Pos(c,p)}}});e.registerHelper("fold","import",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(t.lastLine(),n+10);o>=i;++i){var s=t.getLine(i),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(i,a)}}}var i,n=n.line,o=r(n);if(!o||r(n-1)||(i=r(n-2))&&i.end.line==n-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(n,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var n=n.line,i=r(n);if(null==i||null!=r(n-1))return null;for(var o=n;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(n,i+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":25}],19:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(t,i,o,s){function a(e){var n=l(t,i);if(!n||n.to.line-n.from.line<u)return null;for(var r=t.findMarksAt(n.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;n.cleared=!0;r[o].clear()}return n}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof i&&(i=e.Pos(i,0));var u=r(t,o,"minFoldSize"),c=a(!0);if(r(t,o,"scanUp"))for(;!c&&i.line>t.firstLine();){i=e.Pos(i.line-1,0);c=a(!1)}if(c&&!c.cleared&&"unfold"!==s){var p=n(t,o);e.on(p,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(c.from,c.to,{replacedWith:p,clearOnEnter:!0,__isFold:!0});d.on("clear",function(n,r){e.signal(t,"unfold",t,n,r)});e.signal(t,"fold",t,c.from,c.to)}}function n(e,t){var n=r(e,t,"widget");if("string"==typeof n){var i=document.createTextNode(n);n=document.createElement("span");n.appendChild(i);n.className="CodeMirror-foldmarker"}return n}function r(e,t,n){if(t&&void 0!==t[n])return t[n];var r=e.options.foldOptions;return r&&void 0!==r[n]?r[n]:i[n]}e.newFoldFunction=function(e,n){return function(r,i){t(r,i,{rangeFinder:e,widget:n})}};e.defineExtension("foldCode",function(e,n,r){t(this,e,n,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),n=0;n<t.length;++n)if(t[n].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,n){for(var r=0;r<e.length;++r){var i=e[r](t,n);if(i)return i}}});e.registerHelper("fold","auto",function(e,t){for(var n=e.getHelpers(t,"fold"),r=0;r<n.length;r++){var i=n[r](e,t);if(i)return i}});var i={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":25}],20:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],i):i(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function n(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var n=e.findMarksAt(p(t)),r=0;r<n.length;++r)if(n[r].__isFold&&n[r].find().from.line==t)return!0}function i(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,n){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,n,function(t){var n=null;if(r(e,s))n=i(o.indicatorFolded);else{var u=p(s,0),c=l&&l(e,u);c&&c.to.line-c.from.line>=a&&(n=i(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,n);++s})}function s(e){var t=e.getViewport(),n=e.state.foldGutter;if(n){e.operation(function(){o(e,t.from,t.to)});n.from=t.from;n.to=t.to}}function a(e,t,n){var r=e.state.foldGutter.options;n==r.gutter&&e.foldCode(p(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},n.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var n=e.getViewport();t.from==t.to||n.from-t.to>20||t.from-n.to>20?s(e):e.operation(function(){if(n.from<t.from){o(e,n.from,t.from);t.from=n.from}if(n.to>t.to){o(e,t.to,n.to);t.to=n.to}})},n.updateViewportTimeSpan||400)}function c(e,t){var n=e.state.foldGutter,r=t.line;r>=n.from&&r<n.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,i,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",c);r.off("unfold",c);r.off("swapDoc",s)}if(i){r.state.foldGutter=new t(n(i));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",c);r.on("unfold",c);r.on("swapDoc",s)}});var p=e.Pos})},{"../../lib/codemirror":25,"./foldcode":19}],21:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function n(e,t,n,r){this.line=t;this.ch=n;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var n=e.cm.getTokenTypeAt(d(e.line,t));return n&&/\btag\b/.test(n)}function i(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(i(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),o=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){g.lastIndex=t;e.ch=t;var n=g.exec(e.text);if(n&&n.index==t)return n}else e.ch=t}}function l(e){for(;;){g.lastIndex=e.ch;var t=g.exec(e.text);if(!t){if(i(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),i=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return i?"selfClose":"regular"}e.ch=t}}function c(e,t){for(var n=[];;){var r,i=l(e),o=e.line,a=e.ch-(i?i[0].length:0);if(!i||!(r=s(e)))return;if("selfClose"!=r)if(i[1]){for(var u=n.length-1;u>=0;--u)if(n[u]==i[2]){n.length=u;break}if(0>u&&(!t||t==i[2]))return{tag:i[2],from:d(o,a),to:d(e.line,e.ch)}}else n.push(i[2])}}function p(e,t){for(var n=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var i=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])n.push(s[2]);else{for(var l=n.length-1;l>=0;--l)if(n[l]==s[2]){n.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(i,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",g=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new n(e,t.line,0);;){var i,o=l(r);if(!o||r.line!=t.line||!(i=s(r)))return;if(!o[1]&&"selfClose"!=i){var t=d(r.line,r.ch),a=c(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,i){var o=new n(e,r.line,r.ch,i);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:p(o,f[2]),close:h,at:"close"};o=new n(e,u.line,u.ch,i);return{open:h,close:c(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var i=new n(e,t.line,t.ch,r);;){var o=p(i);if(!o)break;var s=new n(e,t.line,t.ch,r),a=c(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,i){var o=new n(e,t.line,t.ch,i?{from:0,to:i}:null);return c(o,r)}})},{"../../lib/codemirror":25}],22:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function n(e){return"string"==typeof e?e:e.text}function r(e,t){function n(e,n){var i;i="string"!=typeof n?function(e){return n(e,t)}:r.hasOwnProperty(n)?r[n]:n;o[e]=i}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},i=e.options.customKeys,o=i?{}:r;if(i)for(var s in i)i.hasOwnProperty(s)&&n(s,i[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&n(s,a[s]);return o}function i(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,c=this.hints=document.createElement("ul");c.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var p=o.list,d=0;d<p.length;++d){var f=c.appendChild(document.createElement("li")),h=p[d],g=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(g=h.className+" "+g);f.className=g;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||n(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),v=m.left,E=m.bottom,y=!0;c.style.left=v+"px";c.style.top=E+"px";var x=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),b=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(c);var T=c.getBoundingClientRect(),S=T.bottom-b;if(S>0){var N=T.bottom-T.top,C=m.top-(m.bottom-T.top);if(C-N>0){c.style.top=(E=m.top-N)+"px";y=!1}else if(N>b){c.style.height=b-5+"px";c.style.top=(E=m.bottom-T.top)+"px";var L=u.getCursor();if(o.from.ch!=L.ch){m=u.cursorCoords(L);c.style.left=(v=m.left)+"px";T=c.getBoundingClientRect()}}}var A=T.right-x;if(A>0){if(T.right-T.left>x){c.style.width=x-5+"px";A-=T.right-T.left-x}c.style.left=(v=m.left-A)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:p.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var I;u.on("blur",this.onBlur=function(){I=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(I)})}var w=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),n=u.getWrapperElement().getBoundingClientRect(),r=E+w.top-e.top,i=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);y||(i+=c.offsetHeight);if(i<=n.top||i>=n.bottom)return t.close();c.style.top=r+"px";c.style.left=v+w.left-e.left+"px"});e.on(c,"dblclick",function(e){var t=i(c,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(c,"click",function(e){var n=i(c,e.target||e.srcElement);if(n&&null!=n.hintId){l.changeActive(n.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(c,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",p[0],c.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var r={hint:t};if(n)for(var i in n)r[i]=n[i];return e.showHint(r)};e.defineExtension("showHint",function(n){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,n),i=r.options.hint;if(i){e.signal(this,"startCompletion",this);if(!i.async)return r.showHints(i(this,r.options));i(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var i=t.list[r];i.hint?i.hint(this.cm,t,i):this.cm.replaceRange(n(i),i.from||t.from,i.to||t.to,"complete");e.signal(t,"pick",i);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function n(){if(!l){l=!0;c.close();c.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var n=c.options.hint;n.async?n(c.cm,i,c.options):i(n(c.cm,c.options))}}function i(e){t=e;if(!l){if(!t||!t.list.length)return n();c.widget&&c.widget.close();c.widget=new o(c,t)}}function s(){if(u){g(u);u=0}}function a(){s();var e=c.cm.getCursor(),t=c.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||c.cm.somethingSelected()||e.ch&&p.test(t.charAt(e.ch-1)))c.close();else{u=h(r);c.widget&&c.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,c=this,p=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},g=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=n},buildOptions:function(e){var t=this.cm.options.hintOptions,n={};for(var r in l)n[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(n[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(n[r]=e[r]);return n}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,n){t>=this.data.list.length?t=n?this.data.list.length-1:0:0>t&&(t=n?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,n){var r,i=t.getHelpers(t.getCursor(),"hint");if(i.length)for(var o=0;o<i.length;o++){var s=i[o](t,n);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,n)});e.registerHelper("hint","fromList",function(t,n){for(var r=t.getCursor(),i=t.getTokenAt(r),o=[],s=0;s<n.words.length;s++){var a=n.words[s];a.slice(0,i.string.length)==i.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,i.start),to:e.Pos(r.line,i.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":25}],23:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.runMode=function(t,n,r,i){var o=e.getMode(e.defaults,n),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=i&&i.tabSize||e.defaults.tabSize,u=r,c=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var n="",r=0;;){var i=e.indexOf(" ",r);if(-1==i){n+=e.slice(r);c+=e.length-r;break}c+=i-r;n+=e.slice(r,i);var o=l-c%l;c+=o;for(var s=0;o>s;++s)n+=" ";r=i+1}if(t){var p=u.appendChild(document.createElement("span"));p.className="cm-"+t.replace(/ +/g," cm-");p.appendChild(document.createTextNode(n))}else u.appendChild(document.createTextNode(n))}else{u.appendChild(document.createTextNode(a?"\r":e));c=0}}}for(var p=e.splitLines(t),d=i&&i.state||e.startState(o),f=0,h=p.length;h>f;++f){f&&r("\n");var g=new e.StringStream(p[f]);!g.string&&o.blankLine&&o.blankLine(d);for(;!g.eol();){var m=o.token(g,d);r(g.current(),m,f,g.start,d);g.start=g.pos}}}})},{"../../lib/codemirror":25}],24:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t,i,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);i=i?e.clipPos(i):r(0,0);this.pos={from:i,to:i};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(n,i){if(n){t.lastIndex=0;for(var o,s,a=e.getLine(i.line).slice(0,i.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var c=o&&o[0].length||0;c||(0==s&&0==a.length?o=void 0:s!=e.getLine(i.line).length&&c++)}else{t.lastIndex=i.ch;var a=e.getLine(i.line),o=t.exec(a),c=o&&o[0].length||0,s=o&&o.index;s+c==a.length||c||(c=1)}return o&&c?{from:r(i.line,s),to:r(i.line,s+c),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(i,o){if(i){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),c=u.lastIndexOf(t);if(c>-1){c=n(l,u,c);return{from:r(o.line,c),to:r(o.line,c+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),c=u.indexOf(t);if(c>-1){c=n(l,u,c)+o.ch;return{from:r(o.line,c),to:r(o.line,c+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,n){var i=l.length-1;if(t){if(n.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(n.line).slice(0,u[i].length))!=l[l.length-1])return;for(var o=r(n.line,u[i].length),s=n.line-1,c=i-1;c>=1;--c,--s)if(l[c]!=a(e.getLine(s)))return;var p=e.getLine(s),d=p.length-u[0].length;if(a(p.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(n.line+(l.length-1)>e.lastLine())){var p=e.getLine(n.line),d=p.length-u[0].length;if(a(p.slice(d))==l[0]){for(var f=r(n.line,d),s=n.line+1,c=1;i>c;++c,++s)if(l[c]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[i].length))==l[i])return{from:f,to:r(s,u[i].length)}}}}}}}function n(e,t,n){if(e.length==t.length)return n;for(var r=Math.min(n,e.length);;){var i=e.slice(0,r).toLowerCase().length;if(n>i)++r;else{if(!(i>n))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);n.pos={from:t,to:t};n.atOccurrence=!1;return!1}for(var n=this,i=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,i)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!i.line)return t(0);i=r(i.line-1,this.doc.getLine(i.line-1).length)}else{var o=this.doc.lineCount();if(i.line==o-1)return t(o);i=r(i.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 n=e.splitLines(t);this.doc.replaceRange(n,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+n.length-1,n[n.length-1].length+(1==n.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,n,r){return new t(this.doc,e,n,r)});e.defineDocExtension("getSearchCursor",function(e,n,r){return new t(this,e,n,r)});e.defineExtension("selectMatches",function(t,n){for(var r,i=[],o=this.getSearchCursor(t,this.getCursor("from"),n);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)i.push({anchor:o.from(),head:o.to()});i.length&&this.setSelections(i,0)})})},{"../../lib/codemirror":25}],25:[function(t,n,r){(function(t){if("object"==typeof r&&"object"==typeof n)n.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(n,r){if(!(this instanceof e))return new e(n,r);this.options=r=r?No(r):{};No(Gs,r,!1);f(r);var i=r.value;"string"==typeof i&&(i=new ua(i,r.mode));this.doc=i;var o=this.display=new t(n,i);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!gs&&On(this);v(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new vo,keySeq:null};is&&11>os&&setTimeout(Co(Rn,this,!0),20);Fn(this);Mo();on(this);this.curOp.forceUpdate=!0;Mi(this,i);r.autofocus&&!gs||Do()==o.input?setTimeout(Co(ir,this),20):or(this);for(var s in Us)Us.hasOwnProperty(s)&&Us[s](this,r[s],Bs);T(this);for(var l=0;l<Ws.length;++l)Ws[l](this);an(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var n=this,r=n.input=wo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");n.inputDiv=wo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");n.scrollbarFiller=wo("div",null,"CodeMirror-scrollbar-filler");n.scrollbarFiller.setAttribute("not-content","true");n.gutterFiller=wo("div",null,"CodeMirror-gutter-filler");n.gutterFiller.setAttribute("not-content","true");n.lineDiv=wo("div",null,"CodeMirror-code");n.selectionDiv=wo("div",null,null,"position: relative; z-index: 1");n.cursorDiv=wo("div",null,"CodeMirror-cursors");n.measure=wo("div",null,"CodeMirror-measure");n.lineMeasure=wo("div",null,"CodeMirror-measure");n.lineSpace=wo("div",[n.measure,n.lineMeasure,n.selectionDiv,n.cursorDiv,n.lineDiv],null,"position: relative; outline: none");n.mover=wo("div",[wo("div",[n.lineSpace],"CodeMirror-lines")],null,"position: relative");n.sizer=wo("div",[n.mover],"CodeMirror-sizer");n.sizerWidth=null;n.heightForcer=wo("div",null,null,"position: absolute; height: "+ya+"px; width: 1px;");n.gutters=wo("div",null,"CodeMirror-gutters");n.lineGutter=null;n.scroller=wo("div",[n.sizer,n.heightForcer,n.gutters],"CodeMirror-scroll");n.scroller.setAttribute("tabIndex","-1");n.wrapper=wo("div",[n.inputDiv,n.scrollbarFiller,n.gutterFiller,n.scroller],"CodeMirror");if(is&&8>os){n.gutters.style.zIndex=-1;n.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(n.scroller.draggable=!0);if(ps){n.inputDiv.style.height="1px";n.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(n.wrapper):e(n.wrapper));n.viewFrom=n.viewTo=t.first;n.reportedViewFrom=n.reportedViewTo=t.first;n.view=[];n.renderedView=null;n.externalMeasured=null;n.viewOffset=0;n.lastWrapHeight=n.lastWrapWidth=0;n.updateLineNumbers=null;n.nativeBarWidth=n.barHeight=n.barWidth=0;n.scrollbarsClipped=!1;n.lineNumWidth=n.lineNumInnerWidth=n.lineNumChars=null;n.prevInput="";n.alignWidgets=!1;n.pollingFast=!1;n.poll=new vo;n.cachedCharWidth=n.cachedTextHeight=n.cachedPaddingH=null;n.inaccurateSelection=!1;n.maxLine=null;n.maxLineLength=0;n.maxLineChanged=!1;n.wheelDX=n.wheelDY=n.wheelStartX=n.wheelStartY=null;n.shift=!1;n.selForContextMenu=null}function n(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;Nt(e,100);e.state.modeGen++;e.curOp&&xn(e)}function i(e){if(e.options.lineWrapping){Fa(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{Da(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xn(e);Wt(e);setTimeout(function(){E(e)},100)}function o(e){var t=nn(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/rn(e.display)-3);return function(i){if(ui(e.doc,i))return 0;var o=0;if(i.widgets)for(var s=0;s<i.widgets.length;s++)i.widgets[s].height&&(o+=i.widgets[s].height);return n?o+(Math.ceil(i.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,n=o(e);t.iter(function(e){var t=n(e);t!=e.height&&Bi(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");Wt(e)}function l(e){u(e);xn(e);setTimeout(function(){b(e)
},20)}function u(e){var t=e.display.gutters,n=e.options.gutters;Ro(t);for(var r=0;r<n.length;++r){var i=n[r],o=t.appendChild(wo("div",null,"CodeMirror-gutter "+i));if("CodeMirror-linenumbers"==i){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";c(e)}function c(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function p(e){if(0==e.height)return 0;for(var t,n=e.text.length,r=e;t=ni(r);){var i=t.find(0,!0);r=i.from.line;n+=i.from.ch-i.to.ch}r=e;for(;t=ri(r);){var i=t.find(0,!0);n-=r.text.length-i.from.ch;r=i.to.line;n+=r.text.length-i.to.ch}return n}function d(e){var t=e.display,n=e.doc;t.maxLine=ji(n,n.first);t.maxLineLength=p(t.maxLine);t.maxLineChanged=!0;n.iter(function(e){var n=p(e);if(n>t.maxLineLength){t.maxLineLength=n;t.maxLine=e}})}function f(e){var t=bo(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,n=t.gutters.offsetWidth,r=Math.round(e.doc.height+wt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+Ot(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}function g(e,t,n){this.cm=n;var r=this.vert=wo("div",[wo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=wo("div",[wo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(i);ga(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});ga(i,"scroll",function(){i.clientWidth&&t(i.scrollLeft,"horizontal")});this.checkedOverlay=!1;is&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function v(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&Da(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);ga(e,"mousedown",function(){t.state.focused&&setTimeout(Co(On,t),0)});e.setAttribute("not-content","true")},function(e,n){"horizontal"==n?$n(t,e):zn(t,e)},t);t.display.scrollbars.addClass&&Fa(t.display.wrapper,t.display.scrollbars.addClass)}function E(e,t){t||(t=h(e));var n=e.display.barWidth,r=e.display.barHeight;y(e,t);for(var i=0;4>i&&n!=e.display.barWidth||r!=e.display.barHeight;i++){n!=e.display.barWidth&&e.options.lineWrapping&&O(e);y(e,h(e));n=e.display.barWidth;r=e.display.barHeight}}function y(e,t){var n=e.display,r=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px";n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px";if(r.right&&r.bottom){n.scrollbarFiller.style.display="block";n.scrollbarFiller.style.height=r.bottom+"px";n.scrollbarFiller.style.width=r.right+"px"}else n.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){n.gutterFiller.style.display="block";n.gutterFiller.style.height=r.bottom+"px";n.gutterFiller.style.width=t.gutterWidth+"px"}else n.gutterFiller.style.display=""}function x(e,t,n){var r=n&&null!=n.top?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-It(e));var i=n&&null!=n.bottom?n.bottom:r+e.wrapper.clientHeight,o=Hi(t,r),s=Hi(t,i);if(n&&n.ensure){var a=n.ensure.from.line,l=n.ensure.to.line;if(o>a){o=a;s=Hi(t,Vi(ji(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=Hi(t,Vi(ji(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function b(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=N(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",s=0;s<n.length;s++)if(!n[s].hidden){e.options.fixedGutter&&n[s].gutter&&(n[s].gutter.style.left=o);var a=n[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+i+"px")}}function T(e){if(!e.options.lineNumbers)return!1;var t=e.doc,n=S(e.options,t.first+t.size-1),r=e.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(wo("div",[wo("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,s=i.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?n.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";c(e);return!0}return!1}function S(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function N(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function C(e,t,n){var r=e.display;this.viewport=t;this.visible=x(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=_t(e);this.force=n;this.dims=D(e)}function L(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Ot(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Ot(e)+"px";t.scrollbarsClipped=!0}}function A(e,t){var n=e.display,r=e.doc;if(t.editorIsHidden){Tn(e);return!1}if(!t.force&&t.visible.from>=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==Ln(e))return!1;if(T(e)){Tn(e);t.dims=D(e)}var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom));n.viewTo>s&&n.viewTo-s<20&&(s=Math.min(i,n.viewTo));if(Ts){o=ai(e.doc,o);s=li(e.doc,s)}var a=o!=n.viewFrom||s!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;Cn(e,o,s);n.viewOffset=Vi(ji(e.doc,n.viewFrom));e.display.mover.style.top=n.viewOffset+"px";var l=Ln(e);if(!a&&0==l&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=Do();l>4&&(n.lineDiv.style.display="none");F(e,n.updateLineNumbers,t.dims);l>4&&(n.lineDiv.style.display="");n.renderedView=n.view;u&&Do()!=u&&u.offsetHeight&&u.focus();Ro(n.cursorDiv);Ro(n.selectionDiv);n.gutters.style.height=0;if(a){n.lastWrapHeight=t.wrapperHeight;n.lastWrapWidth=t.wrapperWidth;Nt(e,400)}n.updateLineNumbers=null;return!0}function I(e,t){for(var n=t.force,r=t.viewport,i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldDisplayWidth!=_t(e))n=!0;else{n=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+wt(e.display)-Dt(e),r.top)});t.visible=x(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!A(e,t))break;O(e);var o=h(e);xt(e);R(e,o);E(e,o)}co(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){co(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function w(e,t){var n=new C(e,t);if(A(e,n)){O(e);I(e,n);var r=h(e);xt(e);R(e,r);E(e,r)}}function R(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var n=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=n+"px";e.display.gutters.style.height=Math.max(n+Ot(e),t.clientHeight)+"px"}function O(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var i,o=t.view[r];if(!o.hidden){if(is&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;i=s-n;n=s}else{var a=o.node.getBoundingClientRect();i=a.bottom-a.top}var l=o.line.height-i;2>i&&(i=nn(t));if(l>.001||-.001>l){Bi(o.line,i);_(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)_(o.rest[u])}}}}function _(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function D(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){n[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+i;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:N(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function F(e,t,n){function r(t){var n=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return n}for(var i=e.display,o=e.options.lineNumbers,s=i.lineDiv,a=s.firstChild,l=i.view,u=i.viewFrom,c=0;c<l.length;c++){var p=l[c];if(p.hidden);else if(p.node){for(;a!=p.node;)a=r(a);var d=o&&null!=t&&u>=t&&p.lineNumber;if(p.changes){bo(p.changes,"gutter")>-1&&(d=!1);k(e,p,u,n)}if(d){Ro(p.lineNumber);p.lineNumber.appendChild(document.createTextNode(S(e.options,u)))}a=p.node.nextSibling}else{var f=H(e,p,u,n);s.insertBefore(f,a)}u+=p.size}for(;a;)a=r(a)}function k(e,t,n,r){for(var i=0;i<t.changes.length;i++){var o=t.changes[i];"text"==o?G(e,t):"gutter"==o?B(e,t,n,r):"class"==o?U(t):"widget"==o&&q(t,r)}t.changes=null}function P(e){if(e.node==e.text){e.node=wo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);is&&8>os&&(e.node.style.zIndex=2)}return e.node}function M(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var n=P(e);e.background=n.insertBefore(wo("div",null,t),n.firstChild)}}function j(e,t){var n=e.display.externalMeasured;if(n&&n.line==t.line){e.display.externalMeasured=null;t.measure=n.measure;return n.built}return Ci(e,t)}function G(e,t){var n=t.text.className,r=j(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;U(t)}else n&&(t.text.className=n)}function U(e){M(e);e.line.wrapClass?P(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 B(e,t,n,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var i=t.line.gutterMarkers;if(e.options.lineNumbers||i){var o=P(t),s=t.gutter=o.insertBefore(wo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(wo("div",S(e.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(i)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=i.hasOwnProperty(l)&&i[l];u&&s.appendChild(wo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function q(e,t){e.alignable&&(e.alignable=null);for(var n,r=e.node.firstChild;r;r=n){var n=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}V(e,t)}function H(e,t,n,r){var i=j(e,t);t.text=t.node=i.pre;i.bgClass&&(t.bgClass=i.bgClass);i.textClass&&(t.textClass=i.textClass);U(t);B(e,t,n,r);V(t,r);return t.node}function V(e,t){W(e.line,e,t,!0);if(e.rest)for(var n=0;n<e.rest.length;n++)W(e.rest[n],e,t,!1)}function W(e,t,n,r){if(e.widgets)for(var i=P(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=wo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,n);r&&a.above?i.insertBefore(l,t.gutter||t.text):i.appendChild(l);co(a,"redraw")}}function z(e,t,n,r){if(e.noHScroll){(n.alignable||(n.alignable=[])).push(t);var i=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){i-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=i+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function $(e){return Ss(e.line,e.ch)}function X(e,t){return Ns(e,t)<0?t:e}function Y(e,t){return Ns(e,t)<0?e:t}function K(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function J(e,t){var n=e[t];e.sort(function(e,t){return Ns(e.from(),t.from())});t=bo(e,n);for(var r=1;r<e.length;r++){var i=e[r],o=e[r-1];if(Ns(o.to(),i.from())>=0){var s=Y(o.from(),i.from()),a=X(o.to(),i.to()),l=o.empty()?i.from()==i.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new K(e,t)}function Z(e,t){return new K([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Ss(e.first,0);var n=e.first+e.size-1;return t.line>n?Ss(n,ji(e,n).text.length):nt(t,ji(e,t.line).text.length)}function nt(e,t){var n=e.ch;return null==n||n>t?Ss(e.line,t):0>n?Ss(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function it(e,t){for(var n=[],r=0;r<t.length;r++)n[r]=tt(e,t[r]);return n}function ot(e,t,n,r){if(e.cm&&e.cm.display.shift||e.extend){var i=t.anchor;if(r){var o=Ns(n,i)<0;if(o!=Ns(r,i)<0){i=n;n=r}else o!=Ns(n,r)<0&&(n=r)}return new Q(i,n)}return new Q(r||n,n)}function st(e,t,n,r){dt(e,new K([ot(e,e.sel.primary(),t,n)],0),r)}function at(e,t,n){for(var r=[],i=0;i<e.sel.ranges.length;i++)r[i]=ot(e,e.sel.ranges[i],t[i],null);var o=J(r,e.sel.primIndex);dt(e,o,n)}function lt(e,t,n,r){var i=e.sel.ranges.slice(0);i[t]=n;dt(e,J(i,e.sel.primIndex),r)}function ut(e,t,n,r){dt(e,Z(t,n),r)}function ct(e,t){var n={ranges:t.ranges,update:function(t){this.ranges=[];for(var n=0;n<t.length;n++)this.ranges[n]=new Q(tt(e,t[n].anchor),tt(e,t[n].head))}};va(e,"beforeSelectionChange",e,n);e.cm&&va(e.cm,"beforeSelectionChange",e.cm,n);return n.ranges!=t.ranges?J(n.ranges,n.ranges.length-1):t}function pt(e,t,n){var r=e.history.done,i=xo(r);if(i&&i.ranges){r[r.length-1]=t;ft(e,t,n)}else dt(e,t,n)}function dt(e,t,n){ft(e,t,n);Ji(e,e.sel,e.cm?e.cm.curOp.id:0/0,n)}function ft(e,t,n){(go(e,"beforeSelectionChange")||e.cm&&go(e.cm,"beforeSelectionChange"))&&(t=ct(e,t));var r=n&&n.bias||(Ns(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));n&&n.scroll===!1||!e.cm||Cr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}co(e,"cursorActivity",e)}}function gt(e){ht(e,mt(e,e.sel,null,!1),ba)}function mt(e,t,n,r){for(var i,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=vt(e,s.anchor,n,r),l=vt(e,s.head,n,r);if(i||a!=s.anchor||l!=s.head){i||(i=t.ranges.slice(0,o));i[o]=new Q(a,l)}}return i?J(i,t.primIndex):t}function vt(e,t,n,r){var i=!1,o=t,s=n||1;e.cantEdit=!1;e:for(;;){var a=ji(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],c=u.marker;if((null==u.from||(c.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(c.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){va(c,"beforeCursorEnter");if(c.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!c.atomic)continue;var p=c.find(0>s?-1:1);if(0==Ns(p,o)){p.ch+=s;p.ch<0?p=p.line>e.first?tt(e,Ss(p.line-1)):null:p.ch>a.text.length&&(p=p.line<e.first+e.size-1?Ss(p.line+1,0):null);if(!p){if(i){if(!r)return vt(e,t,n,!0);e.cantEdit=!0;return Ss(e.first,0)}i=!0;p=t;s=-s}}o=p;continue e}}return o}}function Et(e){for(var t=e.display,n=e.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<n.sel.ranges.length;s++){var a=n.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&bt(e,a,i);l||Tt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,n.sel.primary().head,"div"),c=t.wrapper.getBoundingClientRect(),p=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+p.top-c.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+p.left-c.left))}return r}function yt(e,t){Oo(e.display.cursorDiv,t.cursors);Oo(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function xt(e){yt(e,Et(e))}function bt(e,t,n){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),i=n.appendChild(wo("div"," ","CodeMirror-cursor"));i.style.left=r.left+"px";i.style.top=r.top+"px";i.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=n.appendChild(wo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Tt(e,t,n){function r(e,t,n,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(wo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==n?c-e:n)+"px; height: "+(r-t)+"px"))}function i(t,n,i){function o(n,r){return Kt(e,Ss(t,n),"div",p,r)}var a,l,p=ji(s,t),d=p.text.length;qo(Wi(p),n||0,null==i?d:i,function(e,t,s){var p,f,h,g=o(e,"left");if(e==t){p=g;f=h=g.left}else{p=o(t-1,"right");if("rtl"==s){var m=g;g=p;p=m}f=g.left;h=p.right}null==n&&0==e&&(f=u);if(p.top-g.top>3){r(f,g.top,null,g.bottom);f=u;g.bottom<p.top&&r(f,g.bottom,null,p.top)}null==i&&t==d&&(h=c);(!a||g.top<a.top||g.top==a.top&&g.left<a.left)&&(a=g);(!l||p.bottom>l.bottom||p.bottom==l.bottom&&p.right>l.right)&&(l=p);u+1>f&&(f=u);r(f,p.top,h-f,p.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Rt(e.display),u=l.left,c=Math.max(o.sizerWidth,_t(e)-o.sizer.offsetLeft)-l.right,p=t.from(),d=t.to();if(p.line==d.line)i(p.line,p.ch,d.ch);else{var f=ji(s,p.line),h=ji(s,d.line),g=oi(f)==oi(h),m=i(p.line,p.ch,g?f.text.length+1:null).end,v=i(d.line,g?0:null,d.ch).start;if(g)if(m.top<v.top-2){r(m.right,m.top,null,m.bottom);r(u,v.top,v.left,v.bottom)}else r(m.right,m.top,v.left-m.right,m.bottom);m.bottom<v.top&&r(u,m.bottom,null,v.top)}n.appendChild(a)}function St(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var n=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function Nt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Co(Ct,e))}function Ct(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var n=+new Date+e.options.workTime,r=$s(t.mode,At(e,t.frontier)),i=[];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=bi(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var c=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),p=0;!c&&p<s.length;++p)c=s[p]!=o.styles[p];c&&i.push(t.frontier);o.stateAfter=$s(t.mode,r)}else{Si(e,o.text,r);o.stateAfter=t.frontier%5==0?$s(t.mode,r):null}++t.frontier;if(+new Date>n){Nt(e,e.options.workDelay);return!0}});i.length&&hn(e,function(){for(var t=0;t<i.length;t++)bn(e,i[t],"text")})}}function Lt(e,t,n){for(var r,i,o=e.doc,s=n?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=ji(o,a-1);if(l.stateAfter&&(!n||a<=o.frontier))return a;var u=Na(l.text,null,e.options.tabSize);if(null==i||r>u){i=a-1;r=u}}return i}function At(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return!0;var o=Lt(e,t,n),s=o>r.first&&ji(r,o-1).stateAfter;s=s?$s(r.mode,s):Xs(r.mode);r.iter(o,t,function(n){Si(e,n.text,s);var a=o==t-1||o%5==0||o>=i.viewFrom&&o<i.viewTo;n.stateAfter=a?$s(r.mode,s):null;++o});n&&(r.frontier=o);return s}function It(e){return e.lineSpace.offsetTop}function wt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Rt(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Oo(e.measure,wo("pre","x")),n=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Ot(e){return ya-e.display.nativeBarWidth}function _t(e){return e.display.scroller.clientWidth-Ot(e)-e.display.barWidth}function Dt(e){return e.display.scroller.clientHeight-Ot(e)-e.display.barHeight}function Ft(e,t,n){var r=e.options.lineWrapping,i=r&&_t(e);if(!t.measure.heights||r&&t.measure.width!=i){var o=t.measure.heights=[];if(r){t.measure.width=i;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-n.top)}}o.push(n.bottom-n.top)}}function kt(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(qi(e.rest[r])>n)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Pt(e,t){t=oi(t);var n=qi(t),r=e.display.externalMeasured=new En(e.doc,t,n);r.lineN=n;var i=r.built=Ci(e,r);r.text=i.pre;Oo(e.display.lineMeasure,i.pre);return r}function Mt(e,t,n,r){return Ut(e,Gt(e,t),n,r)}function jt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Sn(e,t)];var n=e.display.externalMeasured;return n&&t>=n.lineN&&t<n.lineN+n.size?n:void 0}function Gt(e,t){var n=qi(t),r=jt(e,n);r&&!r.text?r=null:r&&r.changes&&k(e,r,n,D(e));r||(r=Pt(e,t));var i=kt(r,t,n);return{line:t,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Ut(e,t,n,r,i){t.before&&(n=-1);var o,s=n+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){Ft(e,t.view,t.rect);t.hasHeights=!0}o=Bt(e,t,n,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}function Bt(e,t,n,r){for(var i,o,s,a,l=t.map,u=0;u<l.length;u+=3){var c=l[u],p=l[u+1];if(c>n){o=0;s=1;a="left"}else if(p>n){o=n-c;s=o+1}else if(u==l.length-3||n==p&&l[u+3]>n){s=p-c;o=s-1;n>=p&&(a="right")}if(null!=o){i=l[u+2];c==p&&r==(i.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){i=l[(u-=3)+2];a="left"}if("right"==r&&o==p-c)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){i=l[(u+=3)+2];a="right"}break}}var d;if(3==i.nodeType){for(var u=0;4>u;u++){for(;o&&Io(t.line.text.charAt(c+o));)--o;for(;p>c+s&&Io(t.line.text.charAt(c+s));)++s;if(is&&9>os&&0==o&&s==p-c)d=i.parentNode.getBoundingClientRect();else if(is&&e.options.lineWrapping){var f=Aa(i,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Is}else d=Aa(i,o,s).getBoundingClientRect()||Is;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}is&&11>os&&(d=qt(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=i.getClientRects()).length>1?f["right"==r?f.length-1:0]:i.getBoundingClientRect()}if(is&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=i.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+rn(e.display),top:h.top,bottom:h.bottom}:Is}for(var g=d.top-t.rect.top,m=d.bottom-t.rect.top,v=(g+m)/2,E=t.view.measure.heights,u=0;u<E.length-1&&!(v<E[u]);u++);var y=u?E[u-1]:0,x=E[u],b={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:y,bottom:x};d.left||d.right||(b.bogus=!0);if(!e.options.singleCursorHeightPerLine){b.rtop=g;b.rbottom=m}return b}function qt(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Bo(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*r,bottom:t.bottom*r}}function Ht(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Vt(e){e.display.externalMeasure=null;Ro(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)Ht(e.display.view[t])}function Wt(e){Vt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function $t(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Xt(e,t,n,r){if(t.widgets)for(var i=0;i<t.widgets.length;++i)if(t.widgets[i].above){var o=di(t.widgets[i]);n.top+=o;n.bottom+=o}if("line"==r)return n;r||(r="local");var s=Vi(t);"local"==r?s+=It(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:$t());var l=a.left+("window"==r?0:zt());n.left+=l;n.right+=l}n.top+=s;n.bottom+=s;return n}function Yt(e,t,n){if("div"==n)return t;var r=t.left,i=t.top;if("page"==n){r-=zt();i-=$t()}else if("local"==n||!n){var o=e.display.sizer.getBoundingClientRect();r+=o.left;i+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:i-s.top}}function Kt(e,t,n,r,i){r||(r=ji(e.doc,t.line));return Xt(e,r,Mt(e,r,t.ch,i),n)}function Qt(e,t,n,r,i,o){function s(t,s){var a=Ut(e,i,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Xt(e,r,a,n)}function a(e,t){var n=l[t],r=n.level%2;if(e==Ho(n)&&t&&n.level<l[t-1].level){n=l[--t];e=Vo(n)-(n.level%2?0:1);r=!0}else if(e==Vo(n)&&t<l.length-1&&n.level<l[t+1].level){n=l[++t];e=Ho(n)-n.level%2;r=!1}return r&&e==n.to&&e>n.from?s(e-1):s(e,r)}r=r||ji(e.doc,t.line);i||(i=Gt(e,r));var l=Wi(r),u=t.ch;if(!l)return s(u);var c=Qo(l,u),p=a(u,c);null!=qa&&(p.other=a(u,qa));return p}function Jt(e,t){var n=0,t=tt(e.doc,t);e.options.lineWrapping||(n=rn(e.display)*t.ch);var r=ji(e.doc,t.line),i=Vi(r)+It(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Zt(e,t,n,r){var i=Ss(e,t);i.xRel=r;n&&(i.outside=!0);return i}function en(e,t,n){var r=e.doc;n+=e.display.viewOffset;if(0>n)return Zt(r.first,0,!0,-1);var i=Hi(r,n),o=r.first+r.size-1;if(i>o)return Zt(r.first+r.size-1,ji(r,o).text.length,!0,1);0>t&&(t=0);for(var s=ji(r,i);;){var a=tn(e,s,i,t,n),l=ri(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;i=qi(s=u.to.line)}}function tn(e,t,n,r,i){function o(r){var i=Qt(e,Ss(n,r),"line",t,u);a=!0;if(s>i.bottom)return i.left-l;if(s<i.top)return i.left+l;a=!1;return i.left}var s=i-Vi(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Gt(e,t),c=Wi(t),p=t.text.length,d=Wo(t),f=zo(t),h=o(d),g=a,m=o(f),v=a;if(r>m)return Zt(n,f,v,1);for(;;){if(c?f==d||f==Zo(t,d,1):1>=f-d){for(var E=h>r||m-r>=r-h?d:f,y=r-(E==d?h:m);Io(t.text.charAt(E));)++E;var x=Zt(n,E,E==d?g:v,-1>y?-1:y>1?1:0);return x}var b=Math.ceil(p/2),T=d+b;if(c){T=d;for(var S=0;b>S;++S)T=Zo(t,T,1)}var N=o(T);if(N>r){f=T;m=N;(v=a)&&(m+=1e3);p=b}else{d=T;h=N;g=a;p-=b}}}function nn(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Cs){Cs=wo("pre");for(var t=0;49>t;++t){Cs.appendChild(document.createTextNode("x"));Cs.appendChild(wo("br"))}Cs.appendChild(document.createTextNode("x"))}Oo(e.measure,Cs);var n=Cs.offsetHeight/50;n>3&&(e.cachedTextHeight=n);Ro(e.measure);return n||1}function rn(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=wo("span","xxxxxxxxxx"),n=wo("pre",[t]);Oo(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;i>2&&(e.cachedCharWidth=i);return i||10}function on(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:++Rs};ws?ws.ops.push(e.curOp):e.curOp.ownsGroup=ws={ops:[e.curOp],delayedCallbacks:[]}}function sn(e){var t=e.delayedCallbacks,n=0;do{for(;n<t.length;n++)t[n]();for(var r=0;r<e.ops.length;r++){var i=e.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++](i.cm)}}while(n<t.length)}function an(e){var t=e.curOp,n=t.ownsGroup;if(n)try{sn(n)}finally{ws=null;for(var r=0;r<n.ops.length;r++)n.ops[r].cm.curOp=null;ln(n)}}function ln(e){for(var t=e.ops,n=0;n<t.length;n++)un(t[n]);for(var n=0;n<t.length;n++)cn(t[n]);for(var n=0;n<t.length;n++)pn(t[n]);for(var n=0;n<t.length;n++)dn(t[n]);for(var n=0;n<t.length;n++)fn(t[n])}function un(e){var t=e.cm,n=t.display;L(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<n.viewFrom||e.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new C(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function cn(e){e.updatedDisplay=e.mustUpdate&&A(e.cm,e.update)}function pn(e){var t=e.cm,n=t.display;e.updatedDisplay&&O(t);e.barMeasure=h(t);if(n.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Mt(t,n.maxLine,n.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+Ot(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-_t(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=Et(t))}function dn(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&$n(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&yt(t,e.newSelectionNodes);e.updatedDisplay&&R(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&E(t,e.barMeasure);e.selectionChanged&&St(t);t.state.focused&&e.updateInput&&Rn(t,e.typing)}function fn(e){var t=e.cm,n=t.display,r=t.doc;e.updatedDisplay&&I(t,e.update);null==n.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(n.wheelStartX=n.wheelStartY=null);if(null!=e.scrollTop&&(n.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,e.scrollTop));n.scrollbars.setScrollTop(r.scrollTop);n.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(n.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(n.scroller.scrollWidth-_t(t),e.scrollLeft));n.scrollbars.setScrollLeft(r.scrollLeft);n.scroller.scrollLeft=r.scrollLeft;b(t)}if(e.scrollToPos){var i=br(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,i)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||va(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&va(s[a],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&va(t,"changes",t,e.changeObjs)}function hn(e,t){if(e.curOp)return t();on(e);try{return t()}finally{an(e)}}function gn(e,t){return function(){if(e.curOp)return t.apply(e,arguments);on(e);try{return t.apply(e,arguments)}finally{an(e)}}}function mn(e){return function(){if(this.curOp)return e.apply(this,arguments);on(this);try{return e.apply(this,arguments)}finally{an(this)}}}function vn(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);on(t);try{return e.apply(this,arguments)}finally{an(t)}}}function En(e,t,n){this.line=t;this.rest=si(t);this.size=this.rest?qi(xo(this.rest))-n+1:1;this.node=this.text=null;this.hidden=ui(e,t)}function yn(e,t,n){for(var r,i=[],o=t;n>o;o=r){var s=new En(e.doc,ji(e.doc,o),o);r=o+s.size;i.push(s)}return i}function xn(e,t,n,r){null==t&&(t=e.doc.first);null==n&&(n=e.doc.first+e.doc.size);r||(r=0);var i=e.display;r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>t)&&(i.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=i.viewTo)Ts&&ai(e.doc,t)<i.viewTo&&Tn(e);else if(n<=i.viewFrom)if(Ts&&li(e.doc,n+r)>i.viewFrom)Tn(e);
else{i.viewFrom+=r;i.viewTo+=r}else if(t<=i.viewFrom&&n>=i.viewTo)Tn(e);else if(t<=i.viewFrom){var o=Nn(e,n,n+r,1);if(o){i.view=i.view.slice(o.index);i.viewFrom=o.lineN;i.viewTo+=r}else Tn(e)}else if(n>=i.viewTo){var o=Nn(e,t,t,-1);if(o){i.view=i.view.slice(0,o.index);i.viewTo=o.lineN}else Tn(e)}else{var s=Nn(e,t,t,-1),a=Nn(e,n,n+r,1);if(s&&a){i.view=i.view.slice(0,s.index).concat(yn(e,s.lineN,a.lineN)).concat(i.view.slice(a.index));i.viewTo+=r}else Tn(e)}var l=i.externalMeasured;l&&(n<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(i.externalMeasured=null))}function bn(e,t,n){e.curOp.viewChanged=!0;var r=e.display,i=e.display.externalMeasured;i&&t>=i.lineN&&t<i.lineN+i.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Sn(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==bo(s,n)&&s.push(n)}}}function Tn(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Sn(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var n=e.display.view,r=0;r<n.length;r++){t-=n[r].size;if(0>t)return r}}function Nn(e,t,n,r){var i,o=Sn(e,t),s=e.display.view;if(!Ts||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;i=l+s[o].size-t;o++}else i=l-t;t+=i;n+=i}for(;ai(e.doc,n)!=n;){if(o==(0>r?0:s.length-1))return null;n+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:n}}function Cn(e,t,n){var r=e.display,i=r.view;if(0==i.length||t>=r.viewTo||n<=r.viewFrom){r.view=yn(e,t,n);r.viewFrom=t}else{r.viewFrom>t?r.view=yn(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Sn(e,t)));r.viewFrom=t;r.viewTo<n?r.view=r.view.concat(yn(e,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,Sn(e,n)))}r.viewTo=n}function Ln(e){for(var t=e.display.view,n=0,r=0;r<t.length;r++){var i=t[r];i.hidden||i.node&&!i.changes||++n}return n}function An(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){wn(e);e.state.focused&&An(e)})}function In(e){function t(){var r=wn(e);if(r||n){e.display.pollingFast=!1;An(e)}else{n=!0;e.display.poll.set(60,t)}}var n=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function wn(e){var t=e.display.input,n=e.display.prevInput,r=e.doc;if(!e.state.focused||ja(t)&&!n||Dn(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var i=t.value;if(i==n&&!e.somethingSelected())return!1;if(is&&os>=9&&e.display.inputHasSelection===i||ms&&/[\uf700-\uf7ff]/.test(i)){Rn(e);return!1}var o=!e.curOp;o&&on(e);e.display.shift=!1;8203!=i.charCodeAt(0)||r.sel!=e.display.selForContextMenu||n||(n="");for(var s=0,a=Math.min(n.length,i.length);a>s&&n.charCodeAt(s)==i.charCodeAt(s);)++s;var l=i.slice(s),u=Ma(l),c=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Os&&Os.join("\n")==l?c=r.sel.ranges.length%Os.length==0&&To(Os,Ma):u.length==r.sel.ranges.length&&(c=To(u,function(e){return[e]})));for(var p=r.sel.ranges.length-1;p>=0;p--){var d=r.sel.ranges[p],f=d.from(),h=d.to();s<n.length?f=Ss(f.line,f.ch-(n.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Ss(h.line,Math.min(ji(r,h.line).text.length,h.ch+xo(u).length)));var g=e.curOp.updateInput,m={from:f,to:h,text:c?c[p%c.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};fr(e.doc,m);co(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!p||r.sel.ranges[p-1].head.line!=d.head.line)){var v=e.getModeAt(d.head),E=js(m);if(v.electricChars){for(var y=0;y<v.electricChars.length;y++)if(l.indexOf(v.electricChars.charAt(y))>-1){Ar(e,E.line,"smart");break}}else v.electricInput&&v.electricInput.test(ji(r,E.line).text.slice(0,E.ch))&&Ar(e,E.line,"smart")}}Cr(e);e.curOp.updateInput=g;e.curOp.typing=!0;i.length>1e3||i.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=i;o&&an(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function Rn(e,t){if(!e.display.contextMenuPending){var n,r,i=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=i.sel.primary();n=Ga&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=n?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&La(e.display.input);is&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";is&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=n}}function On(e){"nocursor"==e.options.readOnly||gs&&Do()==e.display.input||e.display.input.focus()}function _n(e){if(!e.state.focused){On(e);ir(e)}}function Dn(e){return e.options.readOnly||e.doc.cantEdit}function Fn(e){function t(t){fo(e,t)||ha(t)}function n(t){if(e.somethingSelected()){Os=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Os.join("\n");La(r.input)}}else{for(var n=[],i=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Ss(s,0),head:Ss(s+1,0)};i.push(a);n.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(i,null,ba);else{r.prevInput="";r.input.value=n.join("\n");La(r.input)}Os=n}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;ga(r.scroller,"mousedown",gn(e,jn));is&&11>os?ga(r.scroller,"dblclick",gn(e,function(t){if(!fo(e,t)){var n=Mn(e,t);if(n&&!Hn(e,t)&&!Pn(e.display,t)){da(t);var r=e.findWordAt(n);st(e.doc,r.anchor,r.head)}}})):ga(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});ga(r.lineSpace,"selectstart",function(e){Pn(r,e)||da(e)});xs||ga(r.scroller,"contextmenu",function(t){sr(e,t)});ga(r.scroller,"scroll",function(){if(r.scroller.clientHeight){zn(e,r.scroller.scrollTop);$n(e,r.scroller.scrollLeft,!0);va(e,"scroll",e)}});ga(r.scroller,"mousewheel",function(t){Xn(e,t)});ga(r.scroller,"DOMMouseScroll",function(t){Xn(e,t)});ga(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});ga(r.input,"keyup",function(t){nr.call(e,t)});ga(r.input,"input",function(){is&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);wn(e)});ga(r.input,"keydown",gn(e,er));ga(r.input,"keypress",gn(e,rr));ga(r.input,"focus",Co(ir,e));ga(r.input,"blur",Co(or,e));if(e.options.dragDrop){ga(r.scroller,"dragstart",function(t){Wn(e,t)});ga(r.scroller,"dragenter",t);ga(r.scroller,"dragover",t);ga(r.scroller,"drop",gn(e,Vn))}ga(r.scroller,"paste",function(t){if(!Pn(r,t)){e.state.pasteIncoming=!0;On(e);In(e)}});ga(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,n=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=n;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;In(e)});ga(r.input,"cut",n);ga(r.input,"copy",n);ps&&ga(r.sizer,"mouseup",function(){Do()==r.input&&r.input.blur();On(e)})}function kn(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Pn(e,t){for(var n=lo(t);n!=e.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==e.sizer&&n!=e.mover)return!0}function Mn(e,t,n,r){var i=e.display;if(!n&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=i.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=en(e,o,s);if(r&&1==u.xRel&&(l=ji(e.doc,u.line).text).length==u.ch){var c=Na(l,l.length,e.options.tabSize)-l.length;u=Ss(u.line,Math.max(0,Math.round((o-Rt(e.display).left)/rn(e.display))-c))}return u}function jn(e){if(!fo(this,e)){var t=this,n=t.display;n.shift=e.shiftKey;if(Pn(n,e)){if(!ss){n.scroller.draggable=!1;setTimeout(function(){n.scroller.draggable=!0},100)}}else if(!Hn(t,e)){var r=Mn(t,e);window.focus();switch(uo(e)){case 1:r?Gn(t,e,r):lo(e)==n.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Co(On,t),20);da(e);break;case 3:xs&&sr(t,e)}}}}function Gn(e,t,n){setTimeout(Co(_n,e),0);var r,i=+new Date;if(As&&As.time>i-400&&0==Ns(As.pos,n))r="triple";else if(Ls&&Ls.time>i-400&&0==Ns(Ls.pos,n)){r="double";As={time:i,pos:n}}else{r="single";Ls={time:i,pos:n}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&Pa&&!Dn(e)&&"single"==r&&(o=s.contains(n))>-1&&!s.ranges[o].empty()?Un(e,t,n,a):Bn(e,t,n,r,a)}function Un(e,t,n,r){var i=e.display,o=gn(e,function(s){ss&&(i.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(i.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,n);On(e);is&&9==os&&setTimeout(function(){document.body.focus();On(e)},20)}});ss&&(i.scroller.draggable=!0);e.state.draggingText=o;i.scroller.dragDrop&&i.scroller.dragDrop();ga(document,"mouseup",o);ga(i.scroller,"drop",o)}function Bn(e,t,n,r,i){function o(t){if(0!=Ns(m,t)){m=t;if("rect"==r){for(var i=[],o=e.options.tabSize,s=Na(ji(u,n.line).text,n.ch,o),a=Na(ji(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(n.line,t.line),g=Math.min(e.lastLine(),Math.max(n.line,t.line));g>=h;h++){var v=ji(u,h).text,E=Eo(v,l,o);l==f?i.push(new Q(Ss(h,E),Ss(h,E))):v.length>E&&i.push(new Q(Ss(h,E),Ss(h,Eo(v,f,o))))}i.length||i.push(new Q(n,n));dt(u,J(d.ranges.slice(0,p).concat(i),p),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var y=c,x=y.anchor,b=t;if("single"!=r){if("double"==r)var T=e.findWordAt(t);else var T=new Q(Ss(t.line,0),tt(u,Ss(t.line+1,0)));if(Ns(T.anchor,x)>0){b=T.head;x=Y(y.from(),T.anchor)}else{b=T.anchor;x=X(y.to(),T.head)}}var i=d.ranges.slice(0);i[p]=new Q(tt(u,x),b);dt(u,J(i,p),Ta)}}}function s(t){var n=++E,i=Mn(e,t,!0,"rect"==r);if(i)if(0!=Ns(i,m)){_n(e);o(i);var a=x(l,u);(i.line>=a.to||i.line<a.from)&&setTimeout(gn(e,function(){E==n&&s(t)}),150)}else{var c=t.clientY<v.top?-20:t.clientY>v.bottom?20:0;c&&setTimeout(gn(e,function(){if(E==n){l.scroller.scrollTop+=c;s(t)}}),50)}}function a(t){E=1/0;da(t);On(e);ma(document,"mousemove",y);ma(document,"mouseup",b);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var c,p,d=u.sel,f=d.ranges;if(i&&!t.shiftKey){p=u.sel.contains(n);c=p>-1?f[p]:new Q(n,n)}else c=u.sel.primary();if(t.altKey){r="rect";i||(c=new Q(n,n));n=Mn(e,t,!0,!0);p=-1}else if("double"==r){var h=e.findWordAt(n);c=e.display.shift||u.extend?ot(u,c,h.anchor,h.head):h}else if("triple"==r){var g=new Q(Ss(n.line,0),tt(u,Ss(n.line+1,0)));c=e.display.shift||u.extend?ot(u,c,g.anchor,g.head):g}else c=ot(u,c,n);if(i)if(-1==p){p=f.length;dt(u,J(f.concat([c]),p),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[p].empty()&&"single"==r){dt(u,J(f.slice(0,p).concat(f.slice(p+1)),0));d=u.sel}else lt(u,p,c,Ta);else{p=0;dt(u,new K([c],0),Ta);d=u.sel}var m=n,v=l.wrapper.getBoundingClientRect(),E=0,y=gn(e,function(e){uo(e)?s(e):a(e)}),b=gn(e,a);ga(document,"mousemove",y);ga(document,"mouseup",b)}function qn(e,t,n,r,i){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!go(e,n))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var c=a.gutters.childNodes[u];if(c&&c.getBoundingClientRect().right>=o){var p=Hi(e.doc,s),d=e.options.gutters[u];i(e,n,e,p,d,t);return ao(t)}}}function Hn(e,t){return qn(e,t,"gutterClick",!0,co)}function Vn(e){var t=this;if(!fo(t,e)&&!Pn(t.display,e)){da(e);is&&(_s=+new Date);var n=Mn(t,e,!0),r=e.dataTransfer.files;if(n&&!Dn(t))if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),s=0,a=function(e,r){var a=new FileReader;a.onload=gn(t,function(){o[r]=a.result;if(++s==i){n=tt(t.doc,n);var e={from:n,to:n,text:Ma(o.join("\n")),origin:"paste"};fr(t.doc,e);pt(t.doc,Z(n,js(e)))}});a.readAsText(e)},l=0;i>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(n)>-1){t.state.draggingText(e);setTimeout(Co(On,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,Z(n,n));if(u)for(var l=0;l<u.length;++l)yr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");On(t)}}catch(e){}}}}function Wn(e,t){if(is&&(!e.state.draggingText||+new Date-_s<100))ha(t);else if(!fo(e,t)&&!Pn(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!cs){var n=wo("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){n.width=n.height=1;e.display.wrapper.appendChild(n);n._top=n.offsetTop}t.dataTransfer.setDragImage(n,0,0);us&&n.parentNode.removeChild(n)}}}function zn(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||w(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&w(e);Nt(e,100)}}function $n(e,t,n){if(!(n?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;b(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xn(e,t){var n=ks(t),r=n.x,i=n.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||i&&s.scrollHeight>s.clientHeight){if(i&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==Fs){if(i&&null!=Fs){var c=i*Fs,p=e.doc.scrollTop,d=p+o.wrapper.clientHeight;0>c?p=Math.max(0,p+c-50):d=Math.min(e.doc.height,d+c+50);w(e,{top:p,bottom:d})}if(20>Ds)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=i;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,n=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(n){Fs=(Fs*Ds+n)/(Ds+1);++Ds}}},200)}else{o.wheelDX+=r;o.wheelDY+=i}}else{i&&zn(e,Math.max(0,Math.min(s.scrollTop+i*Fs,s.scrollHeight-s.clientHeight)));$n(e,Math.max(0,Math.min(s.scrollLeft+r*Fs,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yn(e,t,n){if("string"==typeof t){t=Ys[t];if(!t)return!1}e.display.pollingFast&&wn(e)&&(e.display.pollingFast=!1);var r=e.display.shift,i=!1;try{Dn(e)&&(e.state.suppressEdits=!0);n&&(e.display.shift=!1);i=t(e)!=xa}finally{e.display.shift=r;e.state.suppressEdits=!1}return i}function Kn(e,t,n){for(var r=0;r<e.state.keyMaps.length;r++){var i=Qs(t,e.state.keyMaps[r],n,e);if(i)return i}return e.options.extraKeys&&Qs(t,e.options.extraKeys,n,e)||Qs(t,e.options.keyMap,n,e)}function Qn(e,t,n,r){var i=e.state.keySeq;if(i){if(Js(t))return"handled";Ps.set(50,function(){if(e.state.keySeq==i){e.state.keySeq=null;Rn(e)}});t=i+" "+t}var o=Kn(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&co(e,"keyHandled",e,t,n);if("handled"==o||"multi"==o){da(n);St(e)}if(i&&!o&&/\'$/.test(t)){da(n);return!0}return!!o}function Jn(e,t){var n=Zs(t,!0);return n?t.shiftKey&&!e.state.keySeq?Qn(e,"Shift-"+n,t,function(t){return Yn(e,t,!0)})||Qn(e,n,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yn(e,t):void 0}):Qn(e,n,t,function(t){return Yn(e,t)}):!1}function Zn(e,t,n){return Qn(e,"'"+n+"'",t,function(t){return Yn(e,t,!0)})}function er(e){var t=this;_n(t);if(!fo(t,e)){is&&11>os&&27==e.keyCode&&(e.returnValue=!1);var n=e.keyCode;t.display.shift=16==n||e.shiftKey;var r=Jn(t,e);if(us){Ms=r?n:null;!r&&88==n&&!Ga&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=n||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||tr(t)}}function tr(e){function t(e){if(18==e.keyCode||!e.altKey){Da(n,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var n=e.display.lineDiv;Fa(n,"CodeMirror-crosshair");ga(document,"keyup",t);ga(document,"mouseover",t)}function nr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function rr(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var n=e.keyCode,r=e.charCode;if(us&&n==Ms){Ms=null;da(e)}else if(!(us&&(!e.which||e.which<10)||ps)||!Jn(t,e)){var i=String.fromCharCode(null==r?n:r);if(!Zn(t,e,i)){is&&os>=9&&(t.display.inputHasSelection=null);In(t)}}}}function ir(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){va(e,"focus",e);e.state.focused=!0;Fa(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){Rn(e);ss&&setTimeout(Co(Rn,e,!0),0)}}An(e);St(e)}}function or(e){if(e.state.focused){va(e,"blur",e);e.state.focused=!1;Da(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function sr(e,t){function n(){if(null!=i.input.selectionStart){var t=e.somethingSelected(),n=i.input.value=""+(t?i.input.value:"");i.prevInput=t?"":"";i.input.selectionStart=1;i.input.selectionEnd=n.length;i.selForContextMenu=e.doc.sel}}function r(){i.contextMenuPending=!1;i.inputDiv.style.position="relative";i.input.style.cssText=l;is&&9>os&&i.scrollbars.setScrollTop(i.scroller.scrollTop=s);An(e);if(null!=i.input.selectionStart){(!is||is&&9>os)&&n();var t=0,r=function(){i.selForContextMenu==e.doc.sel&&0==i.input.selectionStart?gn(e,Ys.selectAll)(e):t++<10?i.detectingSelectAll=setTimeout(r,500):Rn(e)};i.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var i=e.display;if(!Pn(i,t)&&!ar(e,t)){var o=Mn(e,t),s=i.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&gn(e,dt)(e.doc,Z(o),ba);var l=i.input.style.cssText;i.inputDiv.style.position="absolute";i.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(is?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;On(e);ss&&window.scrollTo(null,u);Rn(e);e.somethingSelected()||(i.input.value=i.prevInput=" ");i.contextMenuPending=!0;i.selForContextMenu=e.doc.sel;clearTimeout(i.detectingSelectAll);is&&os>=9&&n();if(xs){ha(t);var c=function(){ma(window,"mouseup",c);setTimeout(r,20)};ga(window,"mouseup",c)}else setTimeout(r,50)}}}}function ar(e,t){return go(e,"gutterContextMenu")?qn(e,t,"gutterContextMenu",!1,va):!1}function lr(e,t){if(Ns(e,t.from)<0)return e;if(Ns(e,t.to)<=0)return js(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=js(t).ch-t.to.ch);return Ss(n,r)}function ur(e,t){for(var n=[],r=0;r<e.sel.ranges.length;r++){var i=e.sel.ranges[r];n.push(new Q(lr(i.anchor,t),lr(i.head,t)))}return J(n,e.sel.primIndex)}function cr(e,t,n){return e.line==t.line?Ss(n.line,e.ch-t.ch+n.ch):Ss(n.line+(e.line-t.line),e.ch)}function pr(e,t,n){for(var r=[],i=Ss(e.first,0),o=i,s=0;s<t.length;s++){var a=t[s],l=cr(a.from,i,o),u=cr(js(a),i,o);i=a.to;o=u;if("around"==n){var c=e.sel.ranges[s],p=Ns(c.head,c.anchor)<0;r[s]=new Q(p?u:l,p?l:u)}else r[s]=new Q(l,l)}return new K(r,e.sel.primIndex)}function dr(e,t,n){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};n&&(r.update=function(t,n,r,i){t&&(this.from=tt(e,t));n&&(this.to=tt(e,n));r&&(this.text=r);void 0!==i&&(this.origin=i)});va(e,"beforeChange",e,r);e.cm&&va(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function fr(e,t,n){if(e.cm){if(!e.cm.curOp)return gn(e.cm,fr)(e,t,n);if(e.cm.state.suppressEdits)return}if(go(e,"beforeChange")||e.cm&&go(e.cm,"beforeChange")){t=dr(e,t,!0);if(!t)return}var r=bs&&!n&&Yr(e,t.from,t.to);if(r)for(var i=r.length-1;i>=0;--i)hr(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text});else hr(e,t)}function hr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=Ns(t.from,t.to)){var n=ur(e,t);Ki(e,t,n,e.cm?e.cm.curOp.id:0/0);vr(e,t,n,zr(e,t));var r=[];Pi(e,function(e,n){if(!n&&-1==bo(r,e.history)){so(e.history,t);r.push(e.history)}vr(e,t,null,zr(e,t))})}}function gr(e,t,n){if(!e.cm||!e.cm.state.suppressEdits){for(var r,i=e.history,o=e.sel,s="undo"==t?i.done:i.undone,a="undo"==t?i.undone:i.done,l=0;l<s.length;l++){r=s[l];if(n?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){i.lastOrigin=i.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Zi(r,a);if(n&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Zi(o,a);a.push({changes:u,generation:i.generation});i.generation=r.generation||++i.maxGeneration;for(var c=go(e,"beforeChange")||e.cm&&go(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var p=r.changes[l];p.origin=t;if(c&&!dr(e,p,!1)){s.length=0;return}u.push($i(e,p));var d=l?ur(e,p):xo(s);vr(e,p,d,Xr(e,p));!l&&e.cm&&e.cm.scrollIntoView({from:p.from,to:js(p)});var f=[];Pi(e,function(e,t){if(!t&&-1==bo(f,e.history)){so(e.history,p);f.push(e.history)}vr(e,p,null,Xr(e,p))})}}}}function mr(e,t){if(0!=t){e.first+=t;e.sel=new K(To(e.sel.ranges,function(e){return new Q(Ss(e.anchor.line+t,e.anchor.ch),Ss(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xn(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;r<n.viewTo;r++)bn(e.cm,r,"gutter")}}}function vr(e,t,n,r){if(e.cm&&!e.cm.curOp)return gn(e.cm,vr)(e,t,n,r);if(t.to.line<e.first)mr(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var i=t.text.length-1-(e.first-t.from.line);mr(e,i);t={from:Ss(e.first,0),to:Ss(t.to.line+i,t.to.ch),text:[xo(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Ss(o,ji(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Gi(e,t.from,t.to);n||(n=ur(e,t));e.cm?Er(e.cm,t,r):Di(e,t,r);ft(e,n,ba)}}function Er(e,t,n){var r=e.doc,i=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=qi(oi(ji(r,s.line)));r.iter(u,a.line+1,function(e){if(e==i.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);Di(r,t,n,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=p(e);if(t>i.maxLineLength){i.maxLine=e;i.maxLineLength=t;i.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);Nt(e,400);var c=t.text.length-(a.line-s.line)-1;t.full?xn(e):s.line!=a.line||1!=t.text.length||_i(e.doc,t)?xn(e,s.line,a.line+1,c):bn(e,s.line,"text");var d=go(e,"changes"),f=go(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&co(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function yr(e,t,n,r,i){r||(r=n);if(Ns(r,n)<0){var o=r;r=n;n=o}"string"==typeof t&&(t=Ma(t));fr(e,{from:n,to:r,text:t,origin:i})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1);if(null!=i&&!fs){var o=wo("div","",null,"position: absolute; top: "+(t.top-n.viewOffset-It(e.display))+"px; height: "+(t.bottom-t.top+Ot(e)+n.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(i);e.display.lineSpace.removeChild(o)}}}function br(e,t,n,r){null==r&&(r=0);for(var i=0;5>i;i++){var o=!1,s=Qt(e,t),a=n&&n!=t?Qt(e,n):s,l=Sr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,c=e.doc.scrollLeft;if(null!=l.scrollTop){zn(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){$n(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-c)>1&&(o=!0)}if(!o)break}return s}function Tr(e,t,n,r,i){var o=Sr(e,t,n,r,i);null!=o.scrollTop&&zn(e,o.scrollTop);null!=o.scrollLeft&&$n(e,o.scrollLeft)}function Sr(e,t,n,r,i){var o=e.display,s=nn(e.display);0>n&&(n=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=Dt(e),u={};i-n>l&&(i=n+l);var c=e.doc.height+wt(o),p=s>n,d=i>c-s;if(a>n)u.scrollTop=p?0:n;else if(i>a+l){var f=Math.min(n,(d?c:i)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,g=_t(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>g;m&&(r=t+g);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>g+h-3&&(u.scrollLeft=r+(m?0:10)-g);return u}function Nr(e,t,n){(null!=t||null!=n)&&Lr(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=n&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+n)}function Cr(e){Lr(e);var t=e.getCursor(),n=t,r=t;if(!e.options.lineWrapping){n=t.ch?Ss(t.line,t.ch-1):t;r=Ss(t.line,t.ch+1)}e.curOp.scrollToPos={from:n,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Lr(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var n=Jt(e,t.from),r=Jt(e,t.to),i=Sr(e,Math.min(n.left,r.left),Math.min(n.top,r.top)-t.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+t.margin);e.scrollTo(i.scrollLeft,i.scrollTop)}}function Ar(e,t,n,r){var i,o=e.doc;null==n&&(n="add");"smart"==n&&(o.mode.indent?i=At(e,t):n="prev");var s=e.options.tabSize,a=ji(o,t),l=Na(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,c=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==n){u=o.mode.indent(i,a.text.slice(c.length),a.text);if(u==xa||u>150){if(!r)return;n="prev"}}}else{u=0;n="not"}"prev"==n?u=t>o.first?Na(ji(o,t-1).text,null,s):0:"add"==n?u=l+e.options.indentUnit:"subtract"==n?u=l-e.options.indentUnit:"number"==typeof n&&(u=l+n);u=Math.max(0,u);var p="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;p+=" "}u>d&&(p+=yo(u-d));if(p!=c)yr(o,p,Ss(t,0),Ss(t,c.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<c.length){var d=Ss(t,c.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Ir(e,t,n,r){var i=t,o=t;"number"==typeof t?o=ji(e,et(e,t)):i=qi(t);if(null==i)return null;r(o,i)&&e.cm&&bn(e.cm,i,n);return o}function wr(e,t){for(var n=e.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=t(n[i]);r.length&&Ns(o.from,xo(r).to)<=0;){var s=r.pop();if(Ns(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}hn(e,function(){for(var t=r.length-1;t>=0;t--)yr(e.doc,"",r[t].from,r[t].to,"+delete");Cr(e)})}function Rr(e,t,n,r,i){function o(){var t=a+n;if(t<e.first||t>=e.first+e.size)return p=!1;a=t;return c=ji(e,t)}function s(e){var t=(i?Zo:es)(c,l,n,!0);if(null==t){if(e||!o())return p=!1;l=i?(0>n?zo:Wo)(c):0>n?c.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=n,c=ji(e,a),p=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),g=!0;!(0>n)||s(!g);g=!1){var m=c.text.charAt(l)||"\n",v=Lo(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||g||v||(v="s");if(d&&d!=v){if(0>n){n=1;s()}break}v&&(d=v);if(n>0&&!s(!g))break}var E=vt(e,Ss(a,l),u,!0);p||(E.hitSide=!0);return E}function Or(e,t,n,r){var i,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);i=t.top+n*(a-(0>n?1.5:.5)*nn(e.display))}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(;;){var l=en(e,s,i);if(!l.outside)break;if(0>n?0>=i:i>=o.height){l.hitSide=!0;break}i+=5*n}return l}function _r(t,n,r,i){e.defaults[t]=n;r&&(Us[t]=i?function(e,t,n){n!=Bs&&r(e,t,n)}:r)}function Dr(e){for(var t,n,r,i,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))i=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))n=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);n&&(e="Ctrl-"+e);i&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function Fr(e){return"string"==typeof e?Ks[e]:e}function kr(e,t,n,r,i){if(r&&r.shared)return Pr(e,t,n,r,i);if(e.cm&&!e.cm.curOp)return gn(e.cm,kr)(e,t,n,r,i);var o=new ta(e,i),s=Ns(t,n);r&&No(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=wo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(ii(e,t.line,t,n,o)||t.line!=n.line&&ii(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ts=!0}o.addToHistory&&Ki(e,{from:t,to:n,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,n.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&oi(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Bi(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==n.line?n.ch:null));++l});o.collapsed&&e.iter(t.line,n.line+1,function(t){ui(e,t)&&Bi(t,0)});o.clearOnEnter&&ga(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){bs=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++na;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xn(u,t.line,n.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var c=t.line;c<=n.line;c++)bn(u,c,"text");o.atomic&>(u.doc);co(u,"markerAdded",u,o)}return o}function Pr(e,t,n,r,i){r=No(r);r.shared=!1;var o=[kr(e,t,n,r,i)],s=o[0],a=r.widgetNode;Pi(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(kr(e,tt(e,t),tt(e,n),r,i));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=xo(o)});return new ra(o,s)}function Mr(e){return e.findMarks(Ss(e.first,0),e.clipPos(Ss(e.lastLine())),function(e){return e.parent})}function jr(e,t){for(var n=0;n<t.length;n++){var r=t[n],i=r.find(),o=e.clipPos(i.from),s=e.clipPos(i.to);if(Ns(o,s)){var a=kr(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Gr(e){for(var t=0;t<e.length;t++){var n=e[t],r=[n.primary.doc];Pi(n.primary.doc,function(e){r.push(e)});for(var i=0;i<n.markers.length;i++){var o=n.markers[i];if(-1==bo(r,o.doc)){o.parent=null;n.markers.splice(i--,1)}}}}function Ur(e,t,n){this.marker=e;this.from=t;this.to=n}function Br(e,t){if(e)for(var n=0;n<e.length;++n){var r=e[n];if(r.marker==t)return r}}function qr(e,t){for(var n,r=0;r<e.length;++r)e[r]!=t&&(n||(n=[])).push(e[r]);return n}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function Vr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function zr(e,t){if(t.full)return null;var n=rt(e,t.from.line)&&ji(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&ji(e,t.to.line).markedSpans;if(!n&&!r)return null;var i=t.from.ch,o=t.to.ch,s=0==Ns(t.from,t.to),a=Vr(n,i,s),l=Wr(r,o,s),u=1==t.text.length,c=xo(t.text).length+(u?i:0);if(a)for(var p=0;p<a.length;++p){var d=a[p];if(null==d.to){var f=Br(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+c):d.to=i}}if(l)for(var p=0;p<l.length;++p){var d=l[p];null!=d.to&&(d.to+=c);if(null==d.from){var f=Br(a,d.marker);if(!f){d.from=c;u&&(a||(a=[])).push(d)}}else{d.from+=c;u&&(a||(a=[])).push(d)}}a&&(a=$r(a));l&&l!=a&&(l=$r(l));var h=[a];if(!u){var g,m=t.text.length-2;if(m>0&&a)for(var p=0;p<a.length;++p)null==a[p].to&&(g||(g=[])).push(new Ur(a[p].marker,null,null));for(var p=0;m>p;++p)h.push(g);h.push(l)}return h}function $r(e){for(var t=0;t<e.length;++t){var n=e[t];null!=n.from&&n.from==n.to&&n.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var n=no(e,t),r=zr(e,t);
if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],s=r[i];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&&(n[i]=s)}return n}function Yr(e,t,n){var r=null;e.iter(t.line,n.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var n=e.markedSpans[t].marker;!n.readOnly||r&&-1!=bo(r,n)||(r||(r=[])).push(n)}});if(!r)return null;for(var i=[{from:t,to:n}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<i.length;++l){var u=i[l];if(!(Ns(u.to,a.from)<0||Ns(u.from,a.to)>0)){var c=[l,1],p=Ns(u.from,a.from),d=Ns(u.to,a.to);(0>p||!s.inclusiveLeft&&!p)&&c.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&c.push({from:a.to,to:u.to});i.splice.apply(i,c);l+=c.length-1}}return i}function Kr(e){var t=e.markedSpans;if(t){for(var n=0;n<t.length;++n)t[n].marker.detachLine(e);e.markedSpans=null}}function Qr(e,t){if(t){for(var n=0;n<t.length;++n)t[n].marker.attachLine(e);e.markedSpans=t}}function Jr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function ei(e,t){var n=e.lines.length-t.lines.length;if(0!=n)return n;var r=e.find(),i=t.find(),o=Ns(r.from,i.from)||Jr(e)-Jr(t);if(o)return-o;var s=Ns(r.to,i.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function ti(e,t){var n,r=Ts&&e.markedSpans;if(r)for(var i,o=0;o<r.length;++o){i=r[o];i.marker.collapsed&&null==(t?i.from:i.to)&&(!n||ei(n,i.marker)<0)&&(n=i.marker)}return n}function ni(e){return ti(e,!0)}function ri(e){return ti(e,!1)}function ii(e,t,n,r,i){var o=ji(e,t),s=Ts&&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),c=Ns(u.from,n)||Jr(l.marker)-Jr(i),p=Ns(u.to,r)||Zr(l.marker)-Zr(i);if(!(c>=0&&0>=p||0>=c&&p>=0)&&(0>=c&&(Ns(u.to,n)>0||l.marker.inclusiveRight&&i.inclusiveLeft)||c>=0&&(Ns(u.from,r)<0||l.marker.inclusiveLeft&&i.inclusiveRight)))return!0}}}function oi(e){for(var t;t=ni(e);)e=t.find(-1,!0).line;return e}function si(e){for(var t,n;t=ri(e);){e=t.find(1,!0).line;(n||(n=[])).push(e)}return n}function ai(e,t){var n=ji(e,t),r=oi(n);return n==r?t:qi(r)}function li(e,t){if(t>e.lastLine())return t;var n,r=ji(e,t);if(!ui(e,r))return t;for(;n=ri(r);)r=n.find(1,!0).line;return qi(r)+1}function ui(e,t){var n=Ts&&t.markedSpans;if(n)for(var r,i=0;i<n.length;++i){r=n[i];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&ci(e,t,r))return!0}}}function ci(e,t,n){if(null==n.to){var r=n.marker.find(1,!0);return ci(e,r.line,Br(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==t.text.length)return!0;for(var i,o=0;o<t.markedSpans.length;++o){i=t.markedSpans[o];if(i.marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&ci(e,t,i))return!0}}function pi(e,t,n){Vi(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Nr(e,null,n)}function di(e){if(null!=e.height)return e.height;if(!_o(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Oo(e.cm.display.measure,wo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fi(e,t,n,r){var i=new ia(e,n,r);i.noHScroll&&(e.display.alignWidgets=!0);Ir(e.doc,t,"widget",function(t){var n=t.widgets||(t.widgets=[]);null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i);i.line=t;if(!ui(e.doc,t)){var r=Vi(t)<e.doc.scrollTop;Bi(t,t.height+di(i));r&&Nr(e,null,i.height);e.curOp.forceUpdate=!0}return!0});return i}function hi(e,t,n,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);Qr(e,n);var i=r?r(e):1;i!=e.height&&Bi(e,i)}function gi(e){e.parent=null;Kr(e)}function mi(e,t){if(e)for(;;){var n=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;e=e.slice(0,n.index)+e.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==t[r]?t[r]=n[2]:new RegExp("(?:^|s)"+n[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+n[2])}return e}function vi(t,n){if(t.blankLine)return t.blankLine(n);if(t.innerMode){var r=e.innerMode(t,n);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function Ei(t,n,r,i){for(var o=0;10>o;o++){i&&(i[0]=e.innerMode(t,r).mode);var s=t.token(n,r);if(n.pos>n.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function yi(e,t,n,r){function i(e){return{start:p.start,end:p.pos,string:p.current(),type:o||null,state:e?$s(s.mode,c):c}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=ji(s,t.line),c=At(e,t.line,n),p=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||p.pos<t.ch)&&!p.eol();){p.start=p.pos;o=Ei(a,p,c);r&&l.push(i(!0))}return r?l:i()}function xi(e,t,n,r,i,o,s){var a=n.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,c=null,p=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mi(vi(n,r),o);for(;!p.eol();){if(p.pos>e.options.maxHighlightLength){a=!1;s&&Si(e,t,r,p.pos);p.pos=t.length;l=null}else l=mi(Ei(n,p,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||c!=l){for(;u<p.start;){u=Math.min(p.start,u+5e4);i(u,c)}c=l}p.start=p.pos}for(;u<p.pos;){var h=Math.min(p.pos,u+5e4);i(h,c);u=h}}function bi(e,t,n,r){var i=[e.state.modeGen],o={};xi(e,t.text,e.doc.mode,n,function(e,t){i.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;xi(e,t.text,a.mode,!0,function(e,t){for(var n=l;e>u;){var r=i[l];r>e&&i.splice(l,1,e,i[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){i.splice(n,l-n,e,"cm-overlay "+t);l=n+2}else for(;l>n;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:i,classes:o.bgClass||o.textClass?o:null}}function Ti(e,t,n){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=bi(e,t,t.stateAfter=At(e,qi(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);n===e.doc.frontier&&e.doc.frontier++}return t.styles}function Si(e,t,n,r){var i=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&vi(i,n);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){Ei(i,o,n);o.start=o.pos}}function Ni(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?aa:sa;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function Ci(e,t){var n=wo("span",null,null,ss?"padding-right: .1px":null),r={pre:wo("pre",[n]),content:n,col:0,pos:0,cm:e};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o,s=i?t.rest[i-1]:t.line;r.pos=0;r.addToken=Ai;(is||ss)&&e.getOption("lineWrapping")&&(r.addToken=Ii(r.addToken));Uo(e.display.measure)&&(o=Wi(s))&&(r.addToken=wi(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&qi(s);Oi(s,r,Ti(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=ko(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=ko(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Go(e.display.measure)));if(0==i){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");va(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=ko(r.pre.className,r.textClass||""));return r}function Li(e){var t=wo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Ai(e,t,n,r,i,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),c=0;;){a.lastIndex=c;var p=a.exec(t),d=p?p.index-c:t.length-c;if(d){var f=document.createTextNode(t.slice(c,c+d));u.appendChild(is&&9>os?wo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!p)break;c+=d+1;if(" "==p[0]){var h=e.cm.options.tabSize,g=h-e.col%h,f=u.appendChild(wo("span",yo(g),"cm-tab"));e.col+=g}else{var f=e.cm.options.specialCharPlaceholder(p[0]);u.appendChild(is&&9>os?wo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);is&&9>os&&(l=!0);e.pos+=t.length}if(n||r||i||l||s){var m=n||"";r&&(m+=r);i&&(m+=i);var v=wo("span",[u],m,s);o&&(v.title=o);return e.content.appendChild(v)}e.content.appendChild(u)}}function Ii(e){function t(e){for(var t=" ",n=0;n<e.length-2;++n)t+=n%2?" ":" ";t+=" ";return t}return function(n,r,i,o,s,a){e(n,r.replace(/ {3,}/g,t),i,o,s,a)}}function wi(e,t){return function(n,r,i,o,s,a){i=i?i+" cm-force-border":"cm-force-border";for(var l=n.pos,u=l+r.length;;){for(var c=0;c<t.length;c++){var p=t[c];if(p.to>l&&p.from<=l)break}if(p.to>=u)return e(n,r,i,o,s,a);e(n,r.slice(0,p.to-l),i,o,null,a);o=null;r=r.slice(p.to-l);l=p.to}}}function Ri(e,t,n,r){var i=!r&&n.widgetNode;if(i){e.map.push(e.pos,e.pos+t,i);e.content.appendChild(i)}e.pos+=t}function Oi(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var s,a,l,u,c,p,d,f=i.length,h=0,g=1,m="",v=0;;){if(v==h){l=u=c=p=a="";d=null;v=1/0;for(var E=[],y=0;y<r.length;++y){var x=r[y],b=x.marker;if(x.from<=h&&(null==x.to||x.to>h)){if(null!=x.to&&v>x.to){v=x.to;u=""}b.className&&(l+=" "+b.className);b.css&&(a=b.css);b.startStyle&&x.from==h&&(c+=" "+b.startStyle);b.endStyle&&x.to==v&&(u+=" "+b.endStyle);b.title&&!p&&(p=b.title);b.collapsed&&(!d||ei(d.marker,b)<0)&&(d=x)}else x.from>h&&v>x.from&&(v=x.from);"bookmark"==b.type&&x.from==h&&b.widgetNode&&E.push(b)}if(d&&(d.from||0)==h){Ri(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&E.length)for(var y=0;y<E.length;++y)Ri(t,0,E[y])}if(h>=f)break;for(var T=Math.min(f,v);;){if(m){var S=h+m.length;if(!d){var N=S>T?m.slice(0,T-h):m;t.addToken(t,N,s?s+l:l,c,h+N.length==v?u:"",p,a)}if(S>=T){m=m.slice(T-h);h=T;break}h=S;c=""}m=i.slice(o,o=n[g++]);s=Ni(n[g++],t.cm.options)}}else for(var g=1;g<n.length;g+=2)t.addToken(t,i.slice(o,o=n[g]),Ni(n[g+1],t.cm.options))}function _i(e,t){return 0==t.from.ch&&0==t.to.ch&&""==xo(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Di(e,t,n,r){function i(e){return n?n[e]:null}function o(e,n,i){hi(e,n,i,r);co(e,"change",e,t)}function s(e,t){for(var n=e,o=[];t>n;++n)o.push(new oa(u[n],i(n),r));return o}var a=t.from,l=t.to,u=t.text,c=ji(e,a.line),p=ji(e,l.line),d=xo(u),f=i(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(_i(e,t)){var g=s(0,u.length-1);o(p,p.text,f);h&&e.remove(a.line,h);g.length&&e.insert(a.line,g)}else if(c==p)if(1==u.length)o(c,c.text.slice(0,a.ch)+d+c.text.slice(l.ch),f);else{var g=s(1,u.length-1);g.push(new oa(d+c.text.slice(l.ch),f,r));o(c,c.text.slice(0,a.ch)+u[0],i(0));e.insert(a.line+1,g)}else if(1==u.length){o(c,c.text.slice(0,a.ch)+u[0]+p.text.slice(l.ch),i(0));e.remove(a.line+1,h)}else{o(c,c.text.slice(0,a.ch)+u[0],i(0));o(p,d+p.text.slice(l.ch),f);var g=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,g)}co(e,"change",e,t)}function Fi(e){this.lines=e;this.parent=null;for(var t=0,n=0;t<e.length;++t){e[t].parent=this;n+=e[t].height}this.height=n}function ki(e){this.children=e;for(var t=0,n=0,r=0;r<e.length;++r){var i=e[r];t+=i.chunkSize();n+=i.height;i.parent=this}this.size=t;this.height=n;this.parent=null}function Pi(e,t,n){function r(e,i,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=i){var l=o&&a.sharedHist;if(!n||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Mi(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);n(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xn(e)}function ji(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(o>t){n=i;break}t-=o}return n.lines[t]}function Gi(e,t,n){var r=[],i=t.line;e.iter(t.line,n.line+1,function(e){var o=e.text;i==n.line&&(o=o.slice(0,n.ch));i==t.line&&(o=o.slice(t.ch));r.push(o);++i});return r}function Ui(e,t,n){var r=[];e.iter(t,n,function(e){r.push(e.text)});return r}function Bi(e,t){var n=t-e.height;if(n)for(var r=e;r;r=r.parent)r.height+=n}function qi(e){if(null==e.parent)return null;for(var t=e.parent,n=bo(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var i=0;r.children[i]!=t;++i)n+=r.children[i].chunkSize();return n+t.first}function Hi(e,t){var n=e.first;e:do{for(var r=0;r<e.children.length;++r){var i=e.children[r],o=i.height;if(o>t){e=i;continue e}t-=o;n+=i.chunkSize()}return n}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return n+r}function Vi(e){e=oi(e);for(var t=0,n=e.parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==e)break;t+=i.height}for(var o=n.parent;o;n=o,o=n.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==n)break;t+=s.height}return t}function Wi(e){var t=e.order;null==t&&(t=e.order=Ha(e.text));return t}function zi(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 $i(e,t){var n={from:$(t.from),to:js(t),text:Gi(e,t.from,t.to)};eo(e,n,t.from.line,t.to.line+1);Pi(e,function(e){eo(e,n,t.from.line,t.to.line+1)},!0);return n}function Xi(e){for(;e.length;){var t=xo(e);if(!t.ranges)break;e.pop()}}function Yi(e,t){if(t){Xi(e.done);return xo(e.done)}if(e.done.length&&!xo(e.done).ranges)return xo(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return xo(e.done)}}function Ki(e,t,n,r){var i=e.history;i.undone.length=0;var o,s=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&i.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Yi(i,i.lastOp==r))){var a=xo(o.changes);0==Ns(t.from,t.to)&&0==Ns(t.from,a.to)?a.to=js(t):o.changes.push($i(e,t))}else{var l=xo(i.done);l&&l.ranges||Zi(e.sel,i.done);o={changes:[$i(e,t)],generation:i.generation};i.done.push(o);for(;i.done.length>i.undoDepth;){i.done.shift();i.done[0].ranges||i.done.shift()}}i.done.push(n);i.generation=++i.maxGeneration;i.lastModTime=i.lastSelTime=s;i.lastOp=i.lastSelOp=r;i.lastOrigin=i.lastSelOrigin=t.origin;a||va(e,"historyAdded")}function Qi(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Ji(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||Qi(e,o,xo(i.done),t))?i.done[i.done.length-1]=t:Zi(t,i.done);i.lastSelTime=+new Date;i.lastSelOrigin=o;i.lastSelOp=n;r&&r.clearRedo!==!1&&Xi(i.undone)}function Zi(e,t){var n=xo(t);n&&n.ranges&&n.equals(e)||t.push(e)}function eo(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans);++o})}function to(e){if(!e)return null;for(var t,n=0;n<e.length;++n)e[n].marker.explicitlyCleared?t||(t=e.slice(0,n)):t&&t.push(e[n]);return t?t.length?t:null:e}function no(e,t){var n=t["spans_"+e.id];if(!n)return null;for(var r=0,i=[];r<t.text.length;++r)i.push(to(n[r]));return i}function ro(e,t,n){for(var r=0,i=[];r<e.length;++r){var o=e[r];if(o.ranges)i.push(n?K.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];i.push({changes:a});for(var l=0;l<s.length;++l){var u,c=s[l];a.push({from:c.from,to:c.to,text:c.text});if(t)for(var p in c)if((u=p.match(/^spans_(\d+)$/))&&bo(t,Number(u[1]))>-1){xo(a)[p]=c[p];delete c[p]}}}}return i}function io(e,t,n,r){if(n<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i],s=!0;if(o.ranges){if(!o.copied){o=e[i]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){io(o.ranges[a].anchor,t,n,r);io(o.ranges[a].head,t,n,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(n<l.from.line){l.from=Ss(l.from.line+r,l.from.ch);l.to=Ss(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,i+1);i=0}}}}function so(e,t){var n=t.from.line,r=t.to.line,i=t.text.length-(r-n)-1;oo(e.done,n,r,i);oo(e.undone,n,r,i)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function co(e,t){function n(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var i,o=Array.prototype.slice.call(arguments,2);if(ws)i=ws.delayedCallbacks;else if(Ea)i=Ea;else{i=Ea=[];setTimeout(po,0)}for(var s=0;s<r.length;++s)i.push(n(r[s]))}}function po(){var e=Ea;Ea=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,n){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});va(e,n||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var n=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==bo(n,t[r])&&n.push(t[r])}function go(e,t){var n=e._handlers&&e._handlers[t];return n&&n.length>0}function mo(e){e.prototype.on=function(e,t){ga(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function vo(){this.id=null}function Eo(e,t,n){for(var r=0,i=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||i+s>=t)return r+Math.min(s,t-i);i+=o-r;i+=n-i%n;r=o+1;if(i>=t)return r}}function yo(e){for(;Ca.length<=e;)Ca.push(xo(Ca)+" ");return Ca[e]}function xo(e){return e[e.length-1]}function bo(e,t){for(var n=0;n<e.length;++n)if(e[n]==t)return n;return-1}function To(e,t){for(var n=[],r=0;r<e.length;r++)n[r]=t(e[r],r);return n}function So(e,t){var n;if(Object.create)n=Object.create(e);else{var r=function(){};r.prototype=e;n=new r}t&&No(t,n);return n}function No(e,t,n){t||(t={});for(var r in e)!e.hasOwnProperty(r)||n===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Co(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function Lo(e,t){return t?t.source.indexOf("\\w")>-1&&wa(e)?!0:t.test(e):wa(e)}function Ao(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Io(e){return e.charCodeAt(0)>=768&&Ra.test(e)}function wo(e,t,n,r){var i=document.createElement(e);n&&(i.className=n);r&&(i.style.cssText=r);if("string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)i.appendChild(t[o]);return i}function Ro(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Oo(e,t){return Ro(e).appendChild(t)}function _o(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function Do(){return document.activeElement}function Fo(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function ko(e,t){for(var n=e.split(" "),r=0;r<n.length;r++)n[r]&&!Fo(n[r]).test(t)&&(t+=" "+n[r]);return t}function Po(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),n=0;n<t.length;n++){var r=t[n].CodeMirror;r&&e(r)}}function Mo(){if(!ka){jo();ka=!0}}function jo(){var e;ga(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;Po(kn)},100))});ga(window,"blur",function(){Po(or)})}function Go(e){if(null==Oa){var t=wo("span","");Oo(e,wo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Oa=t.offsetWidth<=1&&t.offsetHeight>2&&!(is&&8>os))}return Oa?wo("span",""):wo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Uo(e){if(null!=_a)return _a;var t=Oo(e,document.createTextNode("AخA")),n=Aa(t,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=Aa(t,1,2).getBoundingClientRect();return _a=r.right-n.right<3}function Bo(e){if(null!=Ua)return Ua;var t=Oo(e,wo("span","x")),n=t.getBoundingClientRect(),r=Aa(t,0,1).getBoundingClientRect();return Ua=Math.abs(n.left-r.left)>1}function qo(e,t,n,r){if(!e)return r(t,n,"ltr");for(var i=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<n&&s.to>t||t==n&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,n),1==s.level?"rtl":"ltr");i=!0}}i||r(t,n,"ltr")}function Ho(e){return e.level%2?e.to:e.from}function Vo(e){return e.level%2?e.from:e.to}function Wo(e){var t=Wi(e);return t?Ho(t[0]):0}function zo(e){var t=Wi(e);return t?Vo(xo(t)):e.text.length}function $o(e,t){var n=ji(e.doc,t),r=oi(n);r!=n&&(t=qi(r));var i=Wi(r),o=i?i[0].level%2?zo(r):Wo(r):0;return Ss(t,o)}function Xo(e,t){for(var n,r=ji(e.doc,t);n=ri(r);){r=n.find(1,!0).line;t=null}var i=Wi(r),o=i?i[0].level%2?Wo(r):zo(r):r.text.length;return Ss(null==t?qi(r):t,o)}function Yo(e,t){var n=$o(e,t.line),r=ji(e.doc,n.line),i=Wi(r);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==n.line&&t.ch<=o&&t.ch;return Ss(n.line,s?0:o)}return n}function Ko(e,t,n){var r=e[0].level;return t==r?!0:n==r?!1:n>t}function Qo(e,t){qa=null;for(var n,r=0;r<e.length;++r){var i=e[r];if(i.from<t&&i.to>t)return r;if(i.from==t||i.to==t){if(null!=n){if(Ko(e,i.level,e[n].level)){i.from!=i.to&&(qa=n);return r}i.from!=i.to&&(qa=r);return n}n=r}}return n}function Jo(e,t,n,r){if(!r)return t+n;do t+=n;while(t>0&&Io(e.text.charAt(t)));return t}function Zo(e,t,n,r){var i=Wi(e);if(!i)return es(e,t,n,r);for(var o=Qo(i,t),s=i[o],a=Jo(e,t,s.level%2?-n:n,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(i,a)==o)return a;s=i[o+=n];return n>0==s.level%2?s.to:s.from}s=i[o+=n];if(!s)return null;a=n>0==s.level%2?Jo(e,s.to,-1,r):Jo(e,s.from,1,r)}}function es(e,t,n,r){var i=t+n;if(r)for(;i>0&&Io(e.text.charAt(i));)i+=n;return 0>i||i>e.text.length?null:i}var ts=/gecko\/\d/i.test(navigator.userAgent),ns=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),is=ns||rs,os=is&&(ns?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),cs=/Apple Computer/.test(navigator.vendor),ps=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),gs=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),vs=/win/i.test(navigator.platform),Es=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);Es&&(Es=Number(Es[1]));if(Es&&Es>=15){us=!1;ss=!0}var ys=ms&&(as||us&&(null==Es||12.11>Es)),xs=ts||is&&os>=9,bs=!1,Ts=!1;g.prototype=No({update:function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(n){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var i=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=n?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(n?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:n?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,n=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&gn(t.cm,jn)(e)};ga(this.vert,"mousedown",n);ga(this.horiz,"mousedown",n)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},g.prototype);m.prototype=No({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":g,"null":m};var Ss=e.Pos=function(e,t){if(!(this instanceof Ss))return new Ss(e,t);this.line=e;this.ch=t},Ns=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};K.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 n=this.ranges[t],r=e.ranges[t];if(0!=Ns(n.anchor,r.anchor)||0!=Ns(n.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q($(this.ranges[t].anchor),$(this.ranges[t].head));return new K(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 n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(Ns(t,r.from())>=0&&Ns(e,r.to())<=0)return n}return-1}};Q.prototype={from:function(){return Y(this.anchor,this.head)},to:function(){return X(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var Cs,Ls,As,Is={left:0,right:0,top:0,bottom:0},ws=null,Rs=0,Os=null,_s=0,Ds=0,Fs=null;is?Fs=-.53:ts?Fs=15:ls?Fs=-.7:cs&&(Fs=-1/3);var ks=function(e){var t=e.wheelDeltaX,n=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==n&&e.detail&&e.axis==e.VERTICAL_AXIS?n=e.detail:null==n&&(n=e.wheelDelta);return{x:t,y:n}};e.wheelEventPixels=function(e){var t=ks(e);t.x*=Fs;t.y*=Fs;return t};var Ps=new vo,Ms=null,js=e.changeEnd=function(e){return e.text?Ss(e.from.line+e.text.length-1,xo(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();On(this);In(this)},setOption:function(e,t){var n=this.options,r=n[e];if(n[e]!=t||"mode"==e){n[e]=t;Us.hasOwnProperty(e)&&gn(this,Us[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Fr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;n<t.length;++n)if(t[n]==e||t[n].name==e){t.splice(n,1);return!0}},addOverlay:mn(function(t,n){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:n&&n.opaque});this.state.modeGen++;xn(this)}),removeOverlay:mn(function(e){for(var t=this.state.overlays,n=0;n<t.length;++n){var r=t[n].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(n,1);this.state.modeGen++;xn(this);return}}}),indentLine:mn(function(e,t,n){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Ar(this,e,t,n)}),indentSelection:mn(function(e){for(var t=this.doc.sel.ranges,n=-1,r=0;r<t.length;r++){var i=t[r];if(i.empty()){if(i.head.line>n){Ar(this,i.head.line,e,!0);n=i.head.line;r==this.doc.sel.primIndex&&Cr(this)}}else{var o=i.from(),s=i.to(),a=Math.max(n,o.line);n=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;n>l;++l)Ar(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&<(this.doc,r,new Q(o,u[r].to()),ba)}}}),getTokenAt:function(e,t){return yi(this,e,t)},getLineTokens:function(e,t){return yi(this,Ss(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,n=Ti(this,ji(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var s=r+i>>1;if((s?n[2*s-1]:0)>=o)i=s;else{if(!(n[2*s+1]<o)){t=n[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var n=this.doc.mode;return n.innerMode?e.innerMode(n,this.getTokenAt(t).state).mode:n},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var n=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],i=this.getModeAt(e);if("string"==typeof i[t])r[i[t]]&&n.push(r[i[t]]);else if(i[t])for(var o=0;o<i[t].length;o++){var s=r[i[t][o]];s&&n.push(s)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(i,this)&&-1==bo(n,a.val)&&n.push(a.val)}return n},getStateAfter:function(e,t){var n=this.doc;e=et(n,null==e?n.first+n.size-1:e);return At(this,e+1,t)},cursorCoords:function(e,t){var n,r=this.doc.sel.primary();n=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,n,t||"page")},charCoords:function(e,t){return Kt(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Yt(this,e,t||"page");return en(this,e.left,e.top)},lineAtHeight:function(e,t){e=Yt(this,{top:e,left:0},t||"page").top;return Hi(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var n=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;n=!0}var i=ji(this.doc,e);return Xt(this,i,{top:0,left:0},t||"page").top+(n?this.doc.height-Vi(i):0)},defaultTextHeight:function(){return nn(this.display)},defaultCharWidth:function(){return rn(this.display)},setGutterMarker:mn(function(e,t,n){return Ir(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=n;!n&&Ao(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:mn(function(e){var t=this,n=t.doc,r=n.first;n.iter(function(n){if(n.gutterMarkers&&n.gutterMarkers[e]){n.gutterMarkers[e]=null;bn(t,r,"gutter");Ao(n.gutterMarkers)&&(n.gutterMarkers=null)}++r})}),addLineWidget:mn(function(e,t,n){return fi(this,e,t,n)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=ji(this.doc,e);if(!e)return null}else{var t=qi(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,n,r,i){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==i){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==i?a=0:"middle"==i&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}n&&Tr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:mn(er),triggerOnKeyPress:mn(rr),triggerOnKeyUp:nr,execCommand:function(e){return Ys.hasOwnProperty(e)?Ys[e](this):void 0},findPosH:function(e,t,n,r){var i=1;if(0>t){i=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=Rr(this.doc,s,i,n,r);if(s.hitSide)break}return s},moveH:mn(function(e,t){var n=this;n.extendSelectionsBy(function(r){return n.display.shift||n.doc.extend||r.empty()?Rr(n.doc,r.head,e,t,n.options.rtlMoveVisually):0>e?r.from():r.to()},Sa)}),deleteH:mn(function(e,t){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):wr(this,function(n){var i=Rr(r,n.head,e,t,!1);return 0>e?{from:i,to:n.head}:{from:n.head,to:i}})}),findPosV:function(e,t,n,r){var i=1,o=r;if(0>t){i=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,i,n);if(a.hitSide)break}return a},moveV:mn(function(e,t){var n=this,r=this.doc,i=[],o=!n.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(n,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);i.push(a.left);var l=Or(n,a,e,t);
"page"==t&&s==r.sel.primary()&&Nr(n,null,Kt(n,l,"div").top-a.top);return l},Sa);if(i.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=i[s]}),findWordAt:function(e){var t=this.doc,n=ji(t,e.line).text,r=e.ch,i=e.ch;if(n){var o=this.getHelper(e,"wordChars");(e.xRel<0||i==n.length)&&r?--r:++i;for(var s=n.charAt(r),a=Lo(s,o)?function(e){return Lo(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!Lo(e)};r>0&&a(n.charAt(r-1));)--r;for(;i<n.length&&a(n.charAt(i));)++i}return new Q(Ss(e.line,r),Ss(e.line,i))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?Fa(this.display.cursorDiv,"CodeMirror-overwrite"):Da(this.display.cursorDiv,"CodeMirror-overwrite");va(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return Do()==this.display.input},scrollTo:mn(function(e,t){(null!=e||null!=t)&&Lr(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Ot(this)-this.display.barHeight,width:e.scrollWidth-Ot(this)-this.display.barWidth,clientHeight:Dt(this),clientWidth:_t(this)}},scrollIntoView:mn(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Ss(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Lr(this);this.curOp.scrollToPos=e}else{var n=Sr(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(n.scrollLeft,n.scrollTop)}}),setSize:mn(function(e,t){function n(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=n(e));null!=t&&(r.display.wrapper.style.height=n(t));r.options.lineWrapping&&Vt(this);var i=r.display.viewFrom;r.doc.iter(i,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){bn(r,i,"widget");break}++i});r.curOp.forceUpdate=!0;va(r,"refresh",this)}),operation:function(e){return hn(this,e)},refresh:mn(function(){var e=this.display.cachedTextHeight;xn(this);this.curOp.forceUpdate=!0;Wt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);c(this);(null==e||Math.abs(e-nn(this.display))>.5)&&s(this);va(this,"refresh",this)}),swapDoc:mn(function(e){var t=this.doc;t.cm=null;Mi(this,e);Wt(this);Rn(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;co(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Gs=e.defaults={},Us=e.optionHandlers={},Bs=e.Init={toString:function(){return"CodeMirror.Init"}};_r("value","",function(e,t){e.setValue(t)},!0);_r("mode",null,function(e,t){e.doc.modeOption=t;n(e)},!0);_r("indentUnit",2,n,!0);_r("indentWithTabs",!1);_r("smartIndent",!0);_r("tabSize",4,function(e){r(e);Wt(e);xn(e)},!0);_r("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);_r("specialCharPlaceholder",Li,function(e){e.refresh()},!0);_r("electricChars",!0);_r("rtlMoveVisually",!vs);_r("wholeLineUpdateBefore",!0);_r("theme","default",function(e){a(e);l(e)},!0);_r("keyMap","default",function(t,n,r){var i=Fr(n),o=r!=e.Init&&Fr(r);o&&o.detach&&o.detach(t,i);i.attach&&i.attach(t,o||null)});_r("extraKeys",null);_r("lineWrapping",!1,i,!0);_r("gutters",[],function(e){f(e.options);l(e)},!0);_r("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?N(e.display)+"px":"0";e.refresh()},!0);_r("coverGutterNextToScrollbar",!1,function(e){E(e)},!0);_r("scrollbarStyle","native",function(e){v(e);E(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);_r("lineNumbers",!1,function(e){f(e.options);l(e)},!0);_r("firstLineNumber",1,l,!0);_r("lineNumberFormatter",function(e){return e},l,!0);_r("showCursorWhenSelecting",!1,xt,!0);_r("resetSelectionOnContextMenu",!0);_r("readOnly",!1,function(e,t){if("nocursor"==t){or(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||Rn(e)}});_r("disableInput",!1,function(e,t){t||Rn(e)},!0);_r("dragDrop",!0);_r("cursorBlinkRate",530);_r("cursorScrollMargin",0);_r("cursorHeight",1,xt,!0);_r("singleCursorHeightPerLine",!0,xt,!0);_r("workTime",100);_r("workDelay",100);_r("flattenSpans",!0,r,!0);_r("addModeClass",!1,r,!0);_r("pollInterval",100);_r("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});_r("historyEventDelay",1250);_r("viewportMargin",10,function(e){e.refresh()},!0);_r("maxHighlightLength",1e4,r,!0);_r("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});_r("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});_r("autofocus",null);var qs=e.modes={},Hs=e.mimeModes={};e.defineMode=function(t,n){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(n.dependencies=Array.prototype.slice.call(arguments,2));qs[t]=n};e.defineMIME=function(e,t){Hs[e]=t};e.resolveMode=function(t){if("string"==typeof t&&Hs.hasOwnProperty(t))t=Hs[t];else if(t&&"string"==typeof t.name&&Hs.hasOwnProperty(t.name)){var n=Hs[t.name];"string"==typeof n&&(n={name:n});t=So(n,t);t.name=n.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,n){var n=e.resolveMode(n),r=qs[n.name];if(!r)return e.getMode(t,"text/plain");var i=r(t,n);if(Vs.hasOwnProperty(n.name)){var o=Vs[n.name];for(var s in o)if(o.hasOwnProperty(s)){i.hasOwnProperty(s)&&(i["_"+s]=i[s]);i[s]=o[s]}}i.name=n.name;n.helperType&&(i.helperType=n.helperType);if(n.modeProps)for(var s in n.modeProps)i[s]=n.modeProps[s];return i};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Vs=e.modeExtensions={};e.extendMode=function(e,t){var n=Vs.hasOwnProperty(e)?Vs[e]:Vs[e]={};No(t,n)};e.defineExtension=function(t,n){e.prototype[t]=n};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=_r;var Ws=[];e.defineInitHook=function(e){Ws.push(e)};var zs=e.helpers={};e.registerHelper=function(t,n,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][n]=r};e.registerGlobalHelper=function(t,n,r,i){e.registerHelper(t,n,i);zs[t]._global.push({pred:r,val:i})};var $s=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([]));n[r]=i}return n},Xs=e.startState=function(e,t,n){return e.startState?e.startState(t,n):!0};e.innerMode=function(e,t){for(;e.innerMode;){var n=e.innerMode(t);if(!n||n.mode==e)break;t=n.state;e=n.mode}return n||{mode:e,state:t}};var Ys=e.commands={selectAll:function(e){e.setSelection(Ss(e.firstLine(),0),Ss(e.lastLine()),ba)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),ba)},killLine:function(e){wr(e,function(t){if(t.empty()){var n=ji(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line<e.lastLine()?{from:t.head,to:Ss(t.head.line+1,0)}:{from:t.head,to:Ss(t.head.line,n)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){wr(e,function(t){return{from:Ss(t.from().line,0),to:tt(e.doc,Ss(t.to().line+1,0))}})},delLineLeft:function(e){wr(e,function(e){return{from:Ss(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){wr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){wr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Ss(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Ss(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return $o(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div")},Sa)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:n},"div")},Sa)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return r.ch<e.getLine(r.line).search(/\S/)?Yo(e,t.head):r},Sa)},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=[],n=e.listSelections(),r=e.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),s=Na(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){hn(e,function(){for(var t=e.listSelections(),n=[],r=0;r<t.length;r++){var i=t[r].head,o=ji(e.doc,i.line).text;if(o){i.ch==o.length&&(i=new Ss(i.line,i.ch-1));if(i.ch>0){i=new Ss(i.line,i.ch+1);e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),Ss(i.line,i.ch-2),i,"+transpose")}else if(i.line>e.doc.first){var s=ji(e.doc,i.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Ss(i.line-1,s.length-1),Ss(i.line,1),"+transpose")}}n.push(new Q(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){hn(e,function(){for(var t=e.listSelections().length,n=0;t>n;n++){var r=e.listSelections()[n];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);Cr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ks=e.keyMap={};Ks.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"};Ks.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"};Ks.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"};Ks.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"]};Ks["default"]=ms?Ks.macDefault:Ks.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];if(/^(name|fallthrough|(de|at)tach)$/.test(n))continue;if("..."==r){delete e[n];continue}for(var i=To(n.split(" "),Dr),o=0;o<i.length;o++){var s,a;if(o==i.length-1){a=n;s=r}else{a=i.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[n]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,n,r){t=Fr(t);var i=t.call?t.call(e,r):t[e];if(i===!1)return"nothing";if("..."===i)return"multi";if(null!=i&&n(i))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,n,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],n,r);if(s)return s}}},Js=e.isModifierKey=function(e){var t="string"==typeof e?e:Ba[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Zs=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var n=Ba[e.keyCode],r=n;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=n&&(r="Alt-"+r);(ys?e.metaKey:e.ctrlKey)&&"Ctrl"!=n&&(r="Ctrl-"+r);(ys?e.ctrlKey:e.metaKey)&&"Cmd"!=n&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=n&&(r="Shift-"+r);return r};e.fromTextArea=function(t,n){function r(){t.value=u.getValue()}n||(n={});n.value=t.value;!n.tabindex&&t.tabindex&&(n.tabindex=t.tabindex);!n.placeholder&&t.placeholder&&(n.placeholder=t.placeholder);if(null==n.autofocus){var i=Do();n.autofocus=i==t||null!=t.getAttribute("autofocus")&&i==document.body}if(t.form){ga(t.form,"submit",r);if(!n.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},n);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var n=t==e;else var n=t&&(e.test?e.test(t):e(t));if(n){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=Na(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?Na(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return Na(this.string,null,this.tabSize)-(this.lineStart?Na(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,n){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var i=function(e){return n?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(i(o)==i(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&on(e);if(go(this,"clear")){var n=this.find();n&&co(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Br(s.markedSpans,this);if(e&&!this.collapsed)bn(e,qi(s),"text");else if(e){null!=a.to&&(i=qi(s));null!=a.from&&(r=qi(s))}s.markedSpans=qr(s.markedSpans,a);null==a.from&&this.collapsed&&!ui(this.doc,s)&&e&&Bi(s,nn(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=oi(this.lines[o]),u=p(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xn(e,r,i+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&>(e.doc)}e&&co(e,"markerCleared",e,this);t&&an(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var n,r,i=0;i<this.lines.length;++i){var o=this.lines[i],s=Br(o.markedSpans,this);if(null!=s.from){n=Ss(t?o:qi(o),s.from);if(-1==e)return n}if(null!=s.to){r=Ss(t?o:qi(o),s.to);if(1==e)return r}}return n&&{from:n,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,n=this.doc.cm;e&&n&&hn(n,function(){var r=e.line,i=qi(e.line),o=jt(n,i);if(o){Ht(o);n.curOp.selectionChanged=n.curOp.forceUpdate=!0}n.curOp.updateMaxLine=!0;if(!ui(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=di(t)-s;a&&Bi(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=bo(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(bo(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var na=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var n=0;n<e.length;++n)e[n].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();co(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var ia=e.LineWidget=function(e,t,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.cm=e;this.node=t};mo(ia);ia.prototype.clear=function(){var e=this.cm,t=this.line.widgets,n=this.line,r=qi(n);if(null!=r&&t){for(var i=0;i<t.length;++i)t[i]==this&&t.splice(i--,1);t.length||(n.widgets=null);var o=di(this);hn(e,function(){pi(e,n,-o);bn(e,r,"widget");Bi(n,Math.max(0,n.height-o))})}};ia.prototype.changed=function(){var e=this.height,t=this.cm,n=this.line;this.height=null;var r=di(this)-e;r&&hn(t,function(){t.curOp.forceUpdate=!0;pi(t,n,r);Bi(n,n.height+r)})};var oa=e.Line=function(e,t,n){this.text=e;Qr(this,t);this.height=n?n(this):1};mo(oa);oa.prototype.lineNo=function(){return qi(this)};var sa={},aa={};Fi.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n=e,r=e+t;r>n;++n){var i=this.lines[n];this.height-=i.height;gi(i);co(i,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,n){this.height+=n;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,n){for(var r=e+t;r>e;++e)if(n(this.lines[e]))return!0}};ki.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(i>e){var o=Math.min(t,i-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(i==o){this.children.splice(n--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=i}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof Fi))){var a=[];this.collapse(a);this.children=[new Fi(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,n){this.size+=t.length;this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>=e){i.insertInner(e,t,n);if(i.lines&&i.lines.length>50){for(;i.lines.length>50;){var s=i.lines.splice(i.lines.length-25,25),a=new Fi(s);i.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),n=new ki(t);if(e.parent){e.size-=n.size;e.height-=n.height;var r=bo(e.parent.children,e);e.parent.children.splice(r+1,0,n)}else{var i=new ki(e.children);i.parent=e;e.children=[i,n];e=i}n.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>e){var s=Math.min(t,o-e);if(i.iterN(e,s,n))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,n){if(!(this instanceof ua))return new ua(e,t,n);null==n&&(n=0);ki.call(this,[new Fi([new oa("",null)])]);this.first=n;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=n;var r=Ss(n,0);this.sel=Z(r);this.history=new zi(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ma(e));Di(this,{from:r,to:r,text:e});dt(this,Z(r),ba)};ua.prototype=So(ki.prototype,{constructor:ua,iter:function(e,t,n){n?this.iterN(e-this.first,t-e,n):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var n=0,r=0;r<t.length;++r)n+=t[r].height;this.insertInner(e-this.first,t,n)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ui(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:vn(function(e){var t=Ss(this.first,0),n=this.first+this.size-1;fr(this,{from:t,to:Ss(n,ji(this,n).text.length),text:Ma(e),origin:"setValue",full:!0},!0);dt(this,Z(t))}),replaceRange:function(e,t,n,r){t=tt(this,t);n=n?tt(this,n):t;yr(this,e,t,n,r)},getRange:function(e,t,n){var r=Gi(this,tt(this,e),tt(this,t));return n===!1?r:r.join(n||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?ji(this,e):void 0},getLineNumber:function(e){return qi(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=ji(this,e));return oi(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,n=this.sel.primary();t=null==e||"head"==e?n.head:"anchor"==e?n.anchor:"end"==e||"to"==e||e===!1?n.to():n.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:vn(function(e,t,n){ut(this,tt(this,"number"==typeof e?Ss(e,t||0):e),null,n)}),setSelection:vn(function(e,t,n){ut(this,tt(this,e),tt(this,t||e),n)}),extendSelection:vn(function(e,t,n){st(this,tt(this,e),t&&tt(this,t),n)}),extendSelections:vn(function(e,t){at(this,it(this,e,t))}),extendSelectionsBy:vn(function(e,t){at(this,To(this.sel.ranges,e),t)}),setSelections:vn(function(e,t,n){if(e.length){for(var r=0,i=[];r<e.length;r++)i[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,J(i,t),n)}}),addSelection:vn(function(e,t,n){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,J(r,r.length-1),n)}),getSelection:function(e){for(var t,n=this.sel.ranges,r=0;r<n.length;r++){var i=Gi(this,n[r].from(),n[r].to());t=t?t.concat(i):i}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=Gi(this,n[r].from(),n[r].to());e!==!1&&(i=i.join(e||"\n"));t[r]=i}return t},replaceSelection:function(e,t,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=e;this.replaceSelections(r,t,n||"+input")},replaceSelections:vn(function(e,t,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var s=i.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ma(e[o]),origin:n}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)fr(this,r[o]);a?pt(this,a):this.cm&&Cr(this.cm)}),undo:vn(function(){gr(this,"undo")}),redo:vn(function(){gr(this,"redo")}),undoSelection:vn(function(){gr(this,"undo",!0)}),redoSelection:vn(function(){gr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++n;return{undo:t,redo:n}},clearHistory:function(){this.history=new zi(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zi(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:vn(function(e,t,n){return Ir(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(Fo(n).test(e[r]))return!1;e[r]+=" "+n}else e[r]=n;return!0})}),removeLineClass:vn(function(e,t,n){return Ir(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",i=e[r];if(!i)return!1;if(null==n)e[r]=null;else{var o=i.match(Fo(n));if(!o)return!1;var s=o.index+o[0].length;e[r]=i.slice(0,o.index)+(o.index&&s!=i.length?" ":"")+i.slice(s)||null}return!0})}),markText:function(e,t,n){return kr(this,tt(this,e),tt(this,t),n,"range")},setBookmark:function(e,t){var n={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return kr(this,e,e,n,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],n=ji(this,e.line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=e.ch)&&(null==i.to||i.to>=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=tt(this,e);t=tt(this,t);var r=[],i=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];i==e.line&&e.ch>l.to||null==l.from&&i!=e.line||i==t.line&&l.from>t.ch||n&&!n(l.marker)||r.push(l.marker.parent||l.marker)}++i});return r},getAllMarks:function(){var e=[];this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&e.push(n[r].marker)});return e},posFromIndex:function(e){var t,n=this.first;this.iter(function(r){var i=r.text.length+1;if(i>e){t=e;return!0}e-=i;++n});return tt(this,Ss(n,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Ui(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,n=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<n&&(n=e.to);var r=new ua(Ui(this,t,n),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];jr(r,Mr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var n=0;n<this.linked.length;++n){var r=this.linked[n];if(r.doc==t){this.linked.splice(n,1);t.unlinkDoc(this);Gr(Mr(this));break}}if(t.history==this.history){var i=[t.id];Pi(t,function(e){i.push(e.id)},!0);t.history=new zi(null);t.history.done=ro(this.history.done,i);t.history.undone=ro(this.history.undone,i)}},iterLinkedDocs:function(e){Pi(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var ca="iter insert remove copy getEditor".split(" ");for(var pa in ua.prototype)ua.prototype.hasOwnProperty(pa)&&bo(ca,pa)<0&&(e.prototype[pa]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[pa]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},ga=e.on=function(e,t,n){if(e.addEventListener)e.addEventListener(t,n,!1);else if(e.attachEvent)e.attachEvent("on"+t,n);else{var r=e._handlers||(e._handlers={}),i=r[t]||(r[t]=[]);i.push(n)}},ma=e.off=function(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else if(e.detachEvent)e.detachEvent("on"+t,n);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var i=0;i<r.length;++i)if(r[i]==n){r.splice(i,1);break}}},va=e.signal=function(e,t){var n=e._handlers&&e._handlers[t];if(n)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)},Ea=null,ya=30,xa=e.Pass={toString:function(){return"CodeMirror.Pass"}},ba={scroll:!1},Ta={origin:"*mouse"},Sa={origin:"+move"};vo.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var Na=e.countColumn=function(e,t,n,r,i){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=i||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=n-s%n;o=a+1}},Ca=[""],La=function(e){e.select()};hs?La=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:is&&(La=function(e){try{e.select()}catch(t){}});var Aa,Ia=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,wa=e.isWordChar=function(e){return/\w/.test(e)||e>""&&(e.toUpperCase()!=e.toLowerCase()||Ia.test(e))},Ra=/[\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]/;
Aa=document.createRange?function(e,t,n){var r=document.createRange();r.setEnd(e,n);r.setStart(e,t);return r}:function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(i){return r}r.collapse(!0);r.moveEnd("character",n);r.moveStart("character",t);return r};is&&11>os&&(Do=function(){try{return document.activeElement}catch(e){return document.body}});var Oa,_a,Da=e.rmClass=function(e,t){var n=e.className,r=Fo(t).exec(n);if(r){var i=n.slice(r.index+r[0].length);e.className=n.slice(0,r.index)+(i?r[1]+i:"")}},Fa=e.addClass=function(e,t){var n=e.className;Fo(t).test(n)||(e.className+=(n?" ":"")+t)},ka=!1,Pa=function(){if(is&&9>os)return!1;var e=wo("div");return"draggable"in e||"dragDrop"in e}(),Ma=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;r>=t;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),s=o.indexOf("\r");if(-1!=s){n.push(o.slice(0,s));t+=s+1}else{n.push(o);t=i+1}}return n}:function(e){return e.split(/\r\n?|\n/)},ja=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ga=function(){var e=wo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Ua=null,Ba={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=Ba;(function(){for(var e=0;10>e;e++)Ba[e+48]=Ba[e+96]=String(e);for(var e=65;90>=e;e++)Ba[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Ba[e+111]=Ba[e+63235]="F"+e})();var qa,Ha=function(){function e(e){return 247>=e?n.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,n){this.level=e;this.from=t;this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(n){if(!i.test(n))return!1;for(var r,c=n.length,p=[],d=0;c>d;++d)p.push(r=e(n.charCodeAt(d)));for(var d=0,f=u;c>d;++d){var r=p[d];"m"==r?p[d]=f:f=r}for(var d=0,h=u;c>d;++d){var r=p[d];if("1"==r&&"r"==h)p[d]="n";else if(s.test(r)){h=r;"r"==r&&(p[d]="R")}}for(var d=1,f=p[0];c-1>d;++d){var r=p[d];"+"==r&&"1"==f&&"1"==p[d+1]?p[d]="1":","!=r||f!=p[d+1]||"1"!=f&&"n"!=f||(p[d]=f);f=r}for(var d=0;c>d;++d){var r=p[d];if(","==r)p[d]="N";else if("%"==r){for(var g=d+1;c>g&&"%"==p[g];++g);for(var m=d&&"!"==p[d-1]||c>g&&"1"==p[g]?"1":"N",v=d;g>v;++v)p[v]=m;d=g-1}}for(var d=0,h=u;c>d;++d){var r=p[d];"L"==h&&"1"==r?p[d]="L":s.test(r)&&(h=r)}for(var d=0;c>d;++d)if(o.test(p[d])){for(var g=d+1;c>g&&o.test(p[g]);++g);for(var E="L"==(d?p[d-1]:u),y="L"==(c>g?p[g]:u),m=E||y?"L":"R",v=d;g>v;++v)p[v]=m;d=g-1}for(var x,b=[],d=0;c>d;)if(a.test(p[d])){var T=d;for(++d;c>d&&a.test(p[d]);++d);b.push(new t(0,T,d))}else{var S=d,N=b.length;for(++d;c>d&&"L"!=p[d];++d);for(var v=S;d>v;)if(l.test(p[v])){v>S&&b.splice(N,0,new t(1,S,v));var C=v;for(++v;d>v&&l.test(p[v]);++v);b.splice(N,0,new t(2,C,v));S=v}else++v;d>S&&b.splice(N,0,new t(1,S,d))}if(1==b[0].level&&(x=n.match(/^\s+/))){b[0].from=x[0].length;b.unshift(new t(0,0,x[0].length))}if(1==xo(b).level&&(x=n.match(/\s+$/))){xo(b).to-=x[0].length;b.push(new t(0,c-x[0].length,c))}b[0].level!=xo(b).level&&b.push(new t(b[0].level,c,c));return b}}();e.version="4.12.0";return e})},{}],26:[function(e,t){t.exports=e(4)},{"/home/lrd900/yasgui/yasgui/node_modules/jquery/dist/jquery.js":4}],27:[function(e,t){t.exports=e(8)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":8}],28:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],29:[function(e,t,n){arguments[4][10][0].apply(n,arguments)},{"../package.json":28,"./storage.js":30,"./svg.js":31,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":10}],30:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){if(e&&t){"string"==typeof i&&(i=r[i]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));n.set(e,{val:t,exp:i,time:(new Date).getTime()})}},remove:function(e){e&&n.remove(e)},get:function(e){if(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:27}],31:[function(e,t){t.exports=e(12)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":12}],32:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.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.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],33:[function(e,t){"use strict";var n=e("jquery"),r=e("../utils.js"),i=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var i=n(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;i.is(":visible")&&(o=i.outerWidth());e.forEach(function(e){e.css("right",o)})}});var c=function(e,n){u[e.name]=new o;for(var s=0;s<n.length;s++)u[e.name].insert(n[s]);var a=r.getPersistencyId(t,e.persistent);a&&i.storage.set(a,n,"month")},p=function(e,n){var o=l[e]=new n(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&c(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=i.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var i=function(n){if(r&&(!n.autoShow||!n.bulk&&n.async))return!1;var i={closeCharacters:/(?=a)b/,completeSingle:!1};!n.bulk&&n.async&&(i.async=!0);{var o=function(e,t){return f(n,t)};e.showHint(t,o,i)}return!0};for(var o in l)if(-1!=n.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=i(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,n){var r=function(t){var n=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(n);else if("function"==typeof e.get&&0==e.async)r=e.get(n);else if("object"==typeof e.get)for(var i=n.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,i)==n&&r.push(s)}return h(r,e,t)},i=t.getCompleteToken();e.preProcessToken&&(i=e.preProcessToken(i));if(i){if(e.bulk||!e.async)return r(i);var o=function(t){n(h(t,e,i))};e.get(i,o)}},h=function(e,n,r){for(var i=[],o=0;o<e.length;o++){var a=e[o];n.postProcessToken&&(a=n.postProcessToken(r,a));i.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:i,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(n.callbacks)for(var c in n.callbacks)n.callbacks[c]&&t.on(u,c,n.callbacks[c]);return u};return{init:p,completers:l,notifications:{getEl:function(e){return n(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=n("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(n(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,n){n.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(n.text,t.from,t.to)}},{"../../lib/trie.js":15,"../utils.js":46,jquery:26,"yasgui-utils":29}],34:[function(e,t){"use strict";e("jquery");t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var n=e.getCursor(),r=e.getPreviousNonWsToken(n.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":37,"./utils.js":37,jquery:26}],35:[function(e,t){"use strict";var n=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){n.get("http://prefix.cc/popular/all.file.json",function(e){var n=[];for(var r in e)if("bif"!=r){var i=r+": <"+e[r]+">";n.push(i)}n.sort();t(n)})},preProcessToken:function(n){return t.exports.preprocessPrefixTokenForCompletion(e,n)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==n.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var i=e.getPreviousNonWsToken(t.line,r);return i&&"PREFIX"==i.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var n=e.getPreviousNonWsToken(e.getCursor().line,t);n&&n.string&&":"==n.string.slice(-1)&&(t={start:n.start,end:t.end,string:n.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var n=e.getCursor(),i=e.getTokenAt(n);if("prefixed"==r[i.type]){var o=i.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(n.line,i).string.toUpperCase(),a=e.getTokenAt({line:n.line,ch:i.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=i.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var c=e.autocompleters.getTrie(t).autoComplete(l);c.length>0&&e.addPrefixes(c[0])}}}}}}},{jquery:26}],36:[function(e,t){"use strict";var n=e("jquery");t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(n.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),i=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==i.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":37,"./utils.js":37,jquery:26}],37:[function(e,t){"use strict";var n=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),i=function(e,t){var n=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=n[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=n[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in n)if(0==t.string.indexOf(r)){t.autocompletionString=n[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,n){n=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+n.substring(t.tokenPrefixUri.length):"<"+n+">";return n},s=function(t,i,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(i).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==i.name?"class":"property";var u=[],c="",p=function(){c="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+n.param(l)};p();var d=function(){l.page++;p()},f=function(){n.get(c,function(e){for(var r=0;r<e.results.length;r++)u.push(n.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,i):t.autocompleters.notifications.getEl(i).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(i).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(i).empty().append(n("<span>Fetchting autocompletions </span>")).append(n(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:i,postprocessResourceTokenForCompletion:o}},{"../imgs.js":40,"./utils.js":37,jquery:26,"yasgui-utils":29}],38:[function(e,t){"use strict";var n=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};n(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var i=n(this).next(),o=i.attr("class");o&&i.attr("class").indexOf("cm-atom")>=0&&(e+=i.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var i=[];for(var o in r)i.push(o);i.sort();return i},async:!1,bulk:!1,autoShow:!0}}},{jquery:26}],39:[function(e,t){var n=e("jquery");t.exports={use:function(e){e.defaults=n.extend(!0,{},e.defaults,{mode:"sparql11",value:"SELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:e.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],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":e.executeQuery,"Cmd-Enter":e.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"yasqe_"+n(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})}}},{jquery:26}],40:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" ><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)"><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" ><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" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" ><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" /></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 ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}},{}],41:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var n=e("jquery"),r=e("codemirror"),i=(e("./sparql.js"),e("./utils.js")),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var i=n("<div>",{"class":"yasqe"}).appendTo(n(e));t=l(t);var o=u(r(i[0],t));d(o);return o},l=function(e){var t=n.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(n,r){return e("./tokenUtils.js").getCompleteToken(t,n,r)};t.getPreviousNonWsToken=function(n,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,n,r)};t.getNextNonWsToken=function(n,r){return e("./tokenUtils.js").getNextNonWsToken(t,n,r)
};t.query=function(e){a.executeQuery(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(n){return e("./prefixUtils.js").addPrefixes(t,n)};t.removePrefixes=function(n){return e("./prefixUtils.js").removePrefixes(t,n)};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){c(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){p(t.options,e)};return t},c=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},p=function(e,t){if("object"==typeof e.autocompleters){var r=n.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);p(e,t)}}},d=function(e){var t=i.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=n.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=n(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(i.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var i=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),i=u.state;t.queryType=i.queryType;if(0==i.OK){if(!t.options.syntaxErrorCheck){n(t.getWrapperElement).find(".sp-error").css("color","black");return}var c=o.svg.getElement(s.warning);i.possibleCurrent&&i.possibleCurrent.length>0&&e("./tooltip")(t,c,function(){var e=[];i.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+n("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});c.style.marginTop="2px";c.style.marginLeft="2px";c.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",c);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=i&&void 0!=i.stack){var p=i.stack,d=i.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=p[0]&&"?limitOffsetClauses"!=p[0]&&"?offsetClause"!=p[0]&&(t.queryValid=!1)}};n.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;c(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=n(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=n.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=n("<div class='yasqe_buttons'></div>").appendTo(n(e.getWrapperElement()));if(e.options.createShareLink){var t=n(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var i=n("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);n("html").click(function(){i&&i.remove()});i.click(function(e){e.stopPropagation()});var o=n("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+n.param(e.options.createShareLink(e)));o.focus(function(){var e=n(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});i.empty().append(o);var s=t.position();i.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-i.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=n("<div>",{"class":"fullscreenToggleBtns"}).append(n(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(n(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){n("<div>",{"class":"yasqe_queryButton"}).click(function(){if(n(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var g={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=n(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[g[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var i=(n("<div>",{"class":"yasqe"}).insertBefore(n(e)).append(n(e)),u(r.fromTextArea(e,t)));d(i);return i};a.storeQuery=function(e){var t=i.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,n=e.getCursor(!1).line,r=Math.min(t,n),i=Math.max(t,n),o=!0,s=r;i>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;i>=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(),n=e.lineCount();e.replaceRange("\n",{line:n-1,ch:e.getLine(n-1).length});for(var r=n;r>t.line;r--){var i=e.getLine(r-1);e.replaceRange(i,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var n=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:n,ch:r})}};var m=function(e,t,n){var r=e.indexFromPos(t),i=e.indexFromPos(n),o=v(e.getValue(),r,i);e.operation(function(){e.replaceRange(o,t,n);for(var i=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=i;s>=a;a++)e.indentLine(a,"smart")})},v=function(e,t,i){e=e.substring(t,i);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(p.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(""!=n.trim(c)&&e==a[t])return-1;return 0},u="",c="",p=[];r.runMode(e,"sparql11",function(e,t){p.push(t);var n=l(e,t);if(0!=n){if(1==n){u+=e+"\n";c=""}else{u+="\n"+e;c=e}p=[]}else{c+=e;u+=e}1==p.length&&"sp-ws"==p[0]&&(p=[])});return n.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js").use(a);e("./defaults.js").use(a);a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":13,"../lib/flint.js":14,"../package.json":32,"./autocompleters/autocompleterBase.js":33,"./autocompleters/classes.js":34,"./autocompleters/prefixes.js":35,"./autocompleters/properties.js":36,"./autocompleters/variables.js":38,"./defaults.js":39,"./imgs.js":40,"./prefixUtils.js":42,"./sparql.js":43,"./tokenUtils.js":44,"./tooltip":45,"./utils.js":46,codemirror:25,"codemirror/addon/display/fullscreen.js":16,"codemirror/addon/edit/matchbrackets.js":17,"codemirror/addon/fold/brace-fold.js":18,"codemirror/addon/fold/foldcode.js":19,"codemirror/addon/fold/foldgutter.js":20,"codemirror/addon/fold/xml-fold.js":21,"codemirror/addon/hint/show-hint.js":22,"codemirror/addon/runmode/runmode.js":23,"codemirror/addon/search/searchcursor.js":24,jquery:26,"yasgui-utils":29}],42:[function(e,t){"use strict";var n=function(e,t){var n=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var i in t)i in n||r(e,i+": <"+t[i]+">")},r=function(e,t){for(var n=null,r=0,i=e.lineCount(),o=0;i>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){n=a;r=o}}if(null==n)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},i=function(e,t){var n=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+n("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},n=!0,r=function(i,s){if(n){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(n=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var c=u.string;0==c.indexOf("<")&&(c=c.substring(1));">"==c.slice(-1)&&(c=c.substring(0,c.length-1));t[l.string.slice(0,-1)]=c;r(i,u.end+1)}else r(i,l.end+1)}else r(i,a.end+1)}else r(i,a.end+1)}}},i=e.lineCount(),o=0;i>o&&n;o++)r(o);return t},s=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:n,getPrefixesFromQuery:o,removePrefixes:i}},{}],43:[function(e,t){"use strict";var n=e("jquery");t.exports={use:function(e){e.executeQuery=function(t,i){var o="function"==typeof i?i:null,s="object"==typeof i?i:{},a=t.getQueryMode();t.options.sparql&&(s=n.extend({},t.options.sparql,s));s.handlers&&n.extend(!0,s.callbacks,s.handlers);if(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:r(t,s)}},u=!1;if(s.callbacks)for(var c in s.callbacks)if(s.callbacks[c]){u=!0;l[c]=s.callbacks[c]}if(u||o){o&&(l.complete=o);if(s.namedGraphs&&s.namedGraphs.length>0)for(var p="query"==a?"named-graph-uri":"using-named-graph-uri ",d=0;d<s.namedGraphs.length;d++)l.data.push({name:p,value:s.namedGraphs[d]});if(s.defaultGraphs&&s.defaultGraphs.length>0)for(var p="query"==a?"default-graph-uri":"using-graph-uri ",d=0;d<s.defaultGraphs.length;d++)l.data.push({name:p,value:s.defaultGraphs[d]});s.headers&&!n.isEmptyObject(s.headers)&&n.extend(l.headers,s.headers);s.args&&s.args.length>0&&n.merge(l.data,s.args);e.updateQueryButton(t,"busy");var f=function(){e.updateQueryButton(t)};l.complete=l.complete?[f,l.complete]:f;t.xhr=n.ajax(l)}}}}};var r=function(e,t){var n=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())n="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();n="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else n="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return n}},{jquery:26}],44:[function(e,t){"use strict";var n=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var i=e.getTokenAt({line:r.line,ch:t.start});if(null!=i.type&&"ws"!=i.type&&null!=t.type&&"ws"!=t.type){t.start=i.start;t.string=i.string+t.string;return n(e,t,{line:r.line,ch:i.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,n){var i=e.getTokenAt({line:t,ch:n.start});null!=i&&"ws"==i.type&&(i=r(e,t,i));return i},i=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||r.end<n?null:"ws"==r.type?i(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:n,getNextNonWsToken:i}},{}],45:[function(e,t){"use strict";{var n=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var i,t=n(t);t.hover(function(){"function"==typeof r&&(r=r());i=n("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){n(".yasqe_tooltip").remove()});var o=function(){if(n(e.getWrapperElement()).offset().top>=i.offset().top){i.css("bottom","auto");i.css("top","26px")}}}},{"./utils.js":46,jquery:26}],46:[function(e,t){"use strict";var n=e("jquery"),r=function(e,t){var n=!1;try{void 0!==e[t]&&(n=!0)}catch(r){}return n},i=function(e,t){var n=null;t&&(n="string"==typeof t?t:t(e));return n},o=function(){function e(e){var t,r,i;t=n(e).offset();r=n(e).width();i=n(e).height();return[[t.left,t.left+r],[t.top,t.top+i]]}function t(e,t){var n,r;n=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return n[1]>r[0]||n[0]===r[0]}return function(n,r){var i=e(n),o=e(r);return t(i[0],o[0])&&t(i[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:i,elementsOverlap:o}},{jquery:26}],47:[function(t,n,r){(function(n,i,o){(function(n){"use strict";"function"==typeof e&&e.amd?e("datatables",["jquery"],n):"object"==typeof r?n(t("jquery")):jQuery&&!jQuery.fn.dataTable&&n(jQuery)})(function(e){"use strict";function t(n){var r,i,o="a aa ai ao as b fn i m o s ",s={};e.each(n,function(e){r=e.match(/^([^A-Z]+?)([A-Z])/);if(r&&-1!==o.indexOf(r[1]+" ")){i=e.replace(r[0],r[2].toLowerCase());s[i]=e;"o"===r[1]&&t(n[e])}});n._hungarianMap=s}function r(n,i,s){n._hungarianMap||t(n);var a;e.each(i,function(t){a=n._hungarianMap[t];if(a!==o&&(s||i[a]===o))if("o"===a.charAt(0)){i[a]||(i[a]={});e.extend(!0,i[a],i[t]);r(n[a],i[a],s)}else i[a]=i[t]})}function s(e){var t=Xt.defaults.oLanguage,n=e.sZeroRecords;!e.sEmptyTable&&n&&"No data available in table"===t.sEmptyTable&&Mt(e,e,"sZeroRecords","sEmptyTable");!e.sLoadingRecords&&n&&"Loading..."===t.sLoadingRecords&&Mt(e,e,"sZeroRecords","sLoadingRecords");e.sInfoThousands&&(e.sThousands=e.sInfoThousands);var r=e.sDecimal;r&&zt(r)}function a(e){En(e,"ordering","bSort");En(e,"orderMulti","bSortMulti");En(e,"orderClasses","bSortClasses");En(e,"orderCellsTop","bSortCellsTop");En(e,"order","aaSorting");En(e,"orderFixed","aaSortingFixed");En(e,"paging","bPaginate");En(e,"pagingType","sPaginationType");En(e,"pageLength","iDisplayLength");En(e,"searching","bFilter");var t=e.aoSearchCols;if(t)for(var n=0,i=t.length;i>n;n++)t[n]&&r(Xt.models.oSearch,t[n])}function l(e){En(e,"orderable","bSortable");En(e,"orderData","aDataSort");En(e,"orderSequence","asSorting");En(e,"orderDataType","sortDataType")}function u(t){var n=t.oBrowser,r=e("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(e("<div/>").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(e('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),i=r.find(".test");n.bScrollOversize=100===i[0].offsetWidth;n.bScrollbarLeft=1!==i.offset().left;r.remove()}function c(e,t,n,r,i,s){var a,l=r,u=!1;if(n!==o){a=n;u=!0}for(;l!==i;)if(e.hasOwnProperty(l)){a=u?t(a,e[l],l,e):e[l];u=!0;l+=s}return a}function p(t,n){var r=Xt.defaults.column,o=t.aoColumns.length,s=e.extend({},Xt.models.oColumn,r,{nTh:n?n:i.createElement("th"),sTitle:r.sTitle?r.sTitle:n?n.innerHTML:"",aDataSort:r.aDataSort?r.aDataSort:[o],mData:r.mData?r.mData:o,idx:o});t.aoColumns.push(s);var a=t.aoPreSearchCols;a[o]=e.extend({},Xt.models.oSearch,a[o]);d(t,o,null)}function d(t,n,i){var s=t.aoColumns[n],a=t.oClasses,u=e(s.nTh);if(!s.sWidthOrig){s.sWidthOrig=u.attr("width")||null;var c=(u.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);c&&(s.sWidthOrig=c[1])}if(i!==o&&null!==i){l(i);r(Xt.defaults.column,i);i.mDataProp===o||i.mData||(i.mData=i.mDataProp);i.sType&&(s._sManualType=i.sType);i.className&&!i.sClass&&(i.sClass=i.className);e.extend(s,i);Mt(s,i,"sWidth","sWidthOrig");"number"==typeof i.iDataSort&&(s.aDataSort=[i.iDataSort]);Mt(s,i,"aDataSort")}var p=s.mData,d=A(p),f=s.mRender?A(s.mRender):null,h=function(e){return"string"==typeof e&&-1!==e.indexOf("@")};s._bAttrSrc=e.isPlainObject(p)&&(h(p.sort)||h(p.type)||h(p.filter));s.fnGetData=function(e,t,n){var r=d(e,t,o,n);return f&&t?f(r,t,e,n):r};s.fnSetData=function(e,t,n){return I(p)(e,t,n)};if(!t.oFeatures.bSort){s.bSortable=!1;u.addClass(a.sSortableNone)}var g=-1!==e.inArray("asc",s.asSorting),m=-1!==e.inArray("desc",s.asSorting);if(s.bSortable&&(g||m))if(g&&!m){s.sSortingClass=a.sSortableAsc;s.sSortingClassJUI=a.sSortJUIAscAllowed}else if(!g&&m){s.sSortingClass=a.sSortableDesc;s.sSortingClassJUI=a.sSortJUIDescAllowed}else{s.sSortingClass=a.sSortable;s.sSortingClassJUI=a.sSortJUI}else{s.sSortingClass=a.sSortableNone;s.sSortingClassJUI=""}}function f(e){if(e.oFeatures.bAutoWidth!==!1){var t=e.aoColumns;Et(e);for(var n=0,r=t.length;r>n;n++)t[n].nTh.style.width=t[n].sWidth}var i=e.oScroll;(""!==i.sY||""!==i.sX)&&mt(e);Bt(e,null,"column-sizing",[e])}function h(e,t){var n=v(e,"bVisible");return"number"==typeof n[t]?n[t]:null}function g(t,n){var r=v(t,"bVisible"),i=e.inArray(n,r);return-1!==i?i:null}function m(e){return v(e,"bVisible").length}function v(t,n){var r=[];e.map(t.aoColumns,function(e,t){e[n]&&r.push(t)});return r}function E(e){var t,n,r,i,s,a,l,u,c,p=e.aoColumns,d=e.aoData,f=Xt.ext.type.detect;for(t=0,n=p.length;n>t;t++){l=p[t];c=[];if(!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){for(r=0,i=f.length;i>r;r++){for(s=0,a=d.length;a>s;s++){c[s]===o&&(c[s]=N(e,s,t,"type"));u=f[r](c[s],e);if(!u||"html"===u)break}if(u){l.sType=u;break}}l.sType||(l.sType="string")}}}function y(t,n,r,i){var s,a,l,u,c,d,f,h=t.aoColumns;if(n)for(s=n.length-1;s>=0;s--){f=n[s];var g=f.targets!==o?f.targets:f.aTargets;e.isArray(g)||(g=[g]);for(l=0,u=g.length;u>l;l++)if("number"==typeof g[l]&&g[l]>=0){for(;h.length<=g[l];)p(t);i(g[l],f)}else if("number"==typeof g[l]&&g[l]<0)i(h.length+g[l],f);else if("string"==typeof g[l])for(c=0,d=h.length;d>c;c++)("_all"==g[l]||e(h[c].nTh).hasClass(g[l]))&&i(c,f)}if(r)for(s=0,a=r.length;a>s;s++)i(s,r[s])}function x(t,n,r,i){var o=t.aoData.length,s=e.extend(!0,{},Xt.models.oRow,{src:r?"dom":"data"});s._aData=n;t.aoData.push(s);for(var a=t.aoColumns,l=0,u=a.length;u>l;l++){r&&C(t,o,l,N(t,o,l));a[l].sType=null}t.aiDisplayMaster.push(o);(r||!t.oFeatures.bDeferRender)&&F(t,o,r,i);return o}function b(t,n){var r;n instanceof e||(n=e(n));return n.map(function(e,n){r=D(t,n);return x(t,r.data,n,r.cells)})}function T(e,t){return t._DT_RowIndex!==o?t._DT_RowIndex:null}function S(t,n,r){return e.inArray(r,t.aoData[n].anCells)}function N(e,t,n,r){var i=e.iDraw,s=e.aoColumns[n],a=e.aoData[t]._aData,l=s.sDefaultContent,u=s.fnGetData(a,r,{settings:e,row:t,col:n});if(u===o){if(e.iDrawError!=i&&null===l){Pt(e,0,"Requested unknown parameter "+("function"==typeof s.mData?"{function}":"'"+s.mData+"'")+" for row "+t,4);e.iDrawError=i}return l}if(u!==a&&null!==u||null===l){if("function"==typeof u)return u.call(a)}else u=l;return null===u&&"display"==r?"":u}function C(e,t,n,r){var i=e.aoColumns[n],o=e.aoData[t]._aData;i.fnSetData(o,r,{settings:e,row:t,col:n})}function L(t){return e.map(t.match(/(\\.|[^\.])+/g),function(e){return e.replace(/\\./g,".")})}function A(t){if(e.isPlainObject(t)){var n={};e.each(t,function(e,t){t&&(n[e]=A(t))});return function(e,t,r,i){var s=n[t]||n._;return s!==o?s(e,t,r,i):e}}if(null===t)return function(e){return e};if("function"==typeof t)return function(e,n,r,i){return t(e,n,r,i)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e){return e[t]};var r=function(e,t,n){var i,s,a,l;if(""!==n)for(var u=L(n),c=0,p=u.length;p>c;c++){i=u[c].match(yn);s=u[c].match(xn);if(i){u[c]=u[c].replace(yn,"");""!==u[c]&&(e=e[u[c]]);a=[];u.splice(0,c+1);l=u.join(".");for(var d=0,f=e.length;f>d;d++)a.push(r(e[d],t,l));var h=i[0].substring(1,i[0].length-1);e=""===h?a:a.join(h);break}if(s){u[c]=u[c].replace(xn,"");e=e[u[c]]()}else{if(null===e||e[u[c]]===o)return o;e=e[u[c]]}}return e};return function(e,n){return r(e,n,t)}}function I(t){if(e.isPlainObject(t))return I(t._);if(null===t)return function(){};if("function"==typeof t)return function(e,n,r){t(e,"set",n,r)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e,n){e[t]=n};var n=function(e,t,r){for(var i,s,a,l,u,c=L(r),p=c[c.length-1],d=0,f=c.length-1;f>d;d++){s=c[d].match(yn);a=c[d].match(xn);if(s){c[d]=c[d].replace(yn,"");e[c[d]]=[];i=c.slice();i.splice(0,d+1);u=i.join(".");for(var h=0,g=t.length;g>h;h++){l={};n(l,t[h],u);e[c[d]].push(l)}return}if(a){c[d]=c[d].replace(xn,"");e=e[c[d]](t)}(null===e[c[d]]||e[c[d]]===o)&&(e[c[d]]={});e=e[c[d]]}p.match(xn)?e=e[p.replace(xn,"")](t):e[p.replace(yn,"")]=t};return function(e,r){return n(e,r,t)}}function w(e){return fn(e.aoData,"_aData")}function R(e){e.aoData.length=0;e.aiDisplayMaster.length=0;e.aiDisplay.length=0}function O(e,t,n){for(var r=-1,i=0,s=e.length;s>i;i++)e[i]==t?r=i:e[i]>t&&e[i]--;-1!=r&&n===o&&e.splice(r,1)}function _(e,t,n,r){var i,s,a=e.aoData[t];if("dom"!==n&&(n&&"auto"!==n||"dom"!==a.src)){var l,u=a.anCells;if(u)for(i=0,s=u.length;s>i;i++){l=u[i];for(;l.childNodes.length;)l.removeChild(l.firstChild);u[i].innerHTML=N(e,t,i,"display")}}else a._aData=D(e,a).data;a._aSortData=null;a._aFilterData=null;var c=e.aoColumns;if(r!==o)c[r].sType=null;else for(i=0,s=c.length;s>i;i++)c[i].sType=null;k(a)}function D(t,n){var r,i,o,s,a=[],l=[],u=n.firstChild,c=0,p=t.aoColumns,d=function(e,t,n){if("string"==typeof e){var r=e.indexOf("@");if(-1!==r){var i=e.substring(r+1);o["@"+i]=n.getAttribute(i)}}},f=function(t){i=p[c];s=e.trim(t.innerHTML);if(i&&i._bAttrSrc){o={display:s};d(i.mData.sort,o,t);d(i.mData.type,o,t);d(i.mData.filter,o,t);a.push(o)}else a.push(s);c++};if(u)for(;u;){r=u.nodeName.toUpperCase();if("TD"==r||"TH"==r){f(u);l.push(u)}u=u.nextSibling}else{l=n.anCells;for(var h=0,g=l.length;g>h;h++)f(l[h])}return{data:a,cells:l}}function F(e,t,n,r){var o,s,a,l,u,c=e.aoData[t],p=c._aData,d=[];if(null===c.nTr){o=n||i.createElement("tr");c.nTr=o;c.anCells=d;o._DT_RowIndex=t;k(c);for(l=0,u=e.aoColumns.length;u>l;l++){a=e.aoColumns[l];s=n?r[l]:i.createElement(a.sCellType);d.push(s);(!n||a.mRender||a.mData!==l)&&(s.innerHTML=N(e,t,l,"display"));a.sClass&&(s.className+=" "+a.sClass);a.bVisible&&!n?o.appendChild(s):!a.bVisible&&n&&s.parentNode.removeChild(s);a.fnCreatedCell&&a.fnCreatedCell.call(e.oInstance,s,N(e,t,l),p,t,l)}Bt(e,"aoRowCreatedCallback",null,[o,p,t])}c.nTr.setAttribute("role","row")}function k(t){var n=t.nTr,r=t._aData;if(n){r.DT_RowId&&(n.id=r.DT_RowId);if(r.DT_RowClass){var i=r.DT_RowClass.split(" ");t.__rowc=t.__rowc?vn(t.__rowc.concat(i)):i;e(n).removeClass(t.__rowc.join(" ")).addClass(r.DT_RowClass)}r.DT_RowData&&e(n).data(r.DT_RowData)}}function P(t){var n,r,i,o,s,a=t.nTHead,l=t.nTFoot,u=0===e("th, td",a).length,c=t.oClasses,p=t.aoColumns;u&&(o=e("<tr/>").appendTo(a));for(n=0,r=p.length;r>n;n++){s=p[n];i=e(s.nTh).addClass(s.sClass);u&&i.appendTo(o);if(t.oFeatures.bSort){i.addClass(s.sSortingClass);if(s.bSortable!==!1){i.attr("tabindex",t.iTabIndex).attr("aria-controls",t.sTableId);Rt(t,s.nTh,n)}}s.sTitle!=i.html()&&i.html(s.sTitle);Ht(t,"header")(t,i,s,c)}u&&B(t.aoHeader,a);e(a).find(">tr").attr("role","row");e(a).find(">tr>th, >tr>td").addClass(c.sHeaderTH);e(l).find(">tr>th, >tr>td").addClass(c.sFooterTH);if(null!==l){var d=t.aoFooter[0];for(n=0,r=d.length;r>n;n++){s=p[n];s.nTf=d[n].cell;s.sClass&&e(s.nTf).addClass(s.sClass)}}}function M(t,n,r){var i,s,a,l,u,c,p,d,f,h=[],g=[],m=t.aoColumns.length;if(n){r===o&&(r=!1);for(i=0,s=n.length;s>i;i++){h[i]=n[i].slice();h[i].nTr=n[i].nTr;for(a=m-1;a>=0;a--)t.aoColumns[a].bVisible||r||h[i].splice(a,1);g.push([])}for(i=0,s=h.length;s>i;i++){p=h[i].nTr;if(p)for(;c=p.firstChild;)p.removeChild(c);for(a=0,l=h[i].length;l>a;a++){d=1;f=1;if(g[i][a]===o){p.appendChild(h[i][a].cell);g[i][a]=1;for(;h[i+d]!==o&&h[i][a].cell==h[i+d][a].cell;){g[i+d][a]=1;d++}for(;h[i][a+f]!==o&&h[i][a].cell==h[i][a+f].cell;){for(u=0;d>u;u++)g[i+u][a+f]=1;f++}e(h[i][a].cell).attr("rowspan",d).attr("colspan",f)}}}}}function j(t){var n=Bt(t,"aoPreDrawCallback","preDraw",[t]);if(-1===e.inArray(!1,n)){var r=[],i=0,s=t.asStripeClasses,a=s.length,l=(t.aoOpenRows.length,t.oLanguage),u=t.iInitDisplayStart,c="ssp"==Vt(t),p=t.aiDisplay;t.bDrawing=!0;if(u!==o&&-1!==u){t._iDisplayStart=c?u:u>=t.fnRecordsDisplay()?0:u;t.iInitDisplayStart=-1}var d=t._iDisplayStart,f=t.fnDisplayEnd();if(t.bDeferLoading){t.bDeferLoading=!1;t.iDraw++;ht(t,!1)}else if(c){if(!t.bDestroying&&!V(t))return}else t.iDraw++;if(0!==p.length)for(var h=c?0:d,g=c?t.aoData.length:f,v=h;g>v;v++){var E=p[v],y=t.aoData[E];null===y.nTr&&F(t,E);var x=y.nTr;if(0!==a){var b=s[i%a];if(y._sRowStripe!=b){e(x).removeClass(y._sRowStripe).addClass(b);y._sRowStripe=b}}Bt(t,"aoRowCallback",null,[x,y._aData,i,v]);r.push(x);i++}else{var T=l.sZeroRecords;1==t.iDraw&&"ajax"==Vt(t)?T=l.sLoadingRecords:l.sEmptyTable&&0===t.fnRecordsTotal()&&(T=l.sEmptyTable);r[0]=e("<tr/>",{"class":a?s[0]:""}).append(e("<td />",{valign:"top",colSpan:m(t),"class":t.oClasses.sRowEmpty}).html(T))[0]}Bt(t,"aoHeaderCallback","header",[e(t.nTHead).children("tr")[0],w(t),d,f,p]);Bt(t,"aoFooterCallback","footer",[e(t.nTFoot).children("tr")[0],w(t),d,f,p]);var S=e(t.nTBody);S.children().detach();S.append(e(r));Bt(t,"aoDrawCallback","draw",[t]);t.bSorted=!1;t.bFiltered=!1;t.bDrawing=!1}else ht(t,!1)}function G(e,t){var n=e.oFeatures,r=n.bSort,i=n.bFilter;r&&At(e);i?Y(e,e.oPreviousSearch):e.aiDisplay=e.aiDisplayMaster.slice();t!==!0&&(e._iDisplayStart=0);e._drawHold=t;j(e);e._drawHold=!1}function U(t){var n=t.oClasses,r=e(t.nTable),i=e("<div/>").insertBefore(r),o=t.oFeatures,s=e("<div/>",{id:t.sTableId+"_wrapper","class":n.sWrapper+(t.nTFoot?"":" "+n.sNoFooter)});t.nHolding=i[0];t.nTableWrapper=s[0];t.nTableReinsertBefore=t.nTable.nextSibling;for(var a,l,u,c,p,d,f=t.sDom.split(""),h=0;h<f.length;h++){a=null;l=f[h];if("<"==l){u=e("<div/>")[0];c=f[h+1];if("'"==c||'"'==c){p="";d=2;for(;f[h+d]!=c;){p+=f[h+d];d++}"H"==p?p=n.sJUIHeader:"F"==p&&(p=n.sJUIFooter);if(-1!=p.indexOf(".")){var g=p.split(".");u.id=g[0].substr(1,g[0].length-1);u.className=g[1]}else"#"==p.charAt(0)?u.id=p.substr(1,p.length-1):u.className=p;h+=d}s.append(u);s=e(u)}else if(">"==l)s=s.parent();else if("l"==l&&o.bPaginate&&o.bLengthChange)a=ct(t);else if("f"==l&&o.bFilter)a=X(t);else if("r"==l&&o.bProcessing)a=ft(t);else if("t"==l)a=gt(t);else if("i"==l&&o.bInfo)a=it(t);else if("p"==l&&o.bPaginate)a=pt(t);else if(0!==Xt.ext.feature.length)for(var m=Xt.ext.feature,v=0,E=m.length;E>v;v++)if(l==m[v].cFeature){a=m[v].fnInit(t);break}if(a){var y=t.aanFeatures;y[l]||(y[l]=[]);y[l].push(a);s.append(a)}}i.replaceWith(s)}function B(t,n){var r,i,o,s,a,l,u,c,p,d,f,h=e(n).children("tr"),g=function(e,t,n){for(var r=e[t];r[n];)n++;return n};t.splice(0,t.length);for(o=0,l=h.length;l>o;o++)t.push([]);for(o=0,l=h.length;l>o;o++){r=h[o];c=0;i=r.firstChild;for(;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase()){p=1*i.getAttribute("colspan");d=1*i.getAttribute("rowspan");p=p&&0!==p&&1!==p?p:1;d=d&&0!==d&&1!==d?d:1;u=g(t,o,c);f=1===p?!0:!1;for(a=0;p>a;a++)for(s=0;d>s;s++){t[o+s][u+a]={cell:i,unique:f};t[o+s].nTr=r}}i=i.nextSibling}}}function q(e,t,n){var r=[];if(!n){n=e.aoHeader;if(t){n=[];B(n,t)}}for(var i=0,o=n.length;o>i;i++)for(var s=0,a=n[i].length;a>s;s++)!n[i][s].unique||r[s]&&e.bSortCellsTop||(r[s]=n[i][s].cell);return r}function H(t,n,r){Bt(t,"aoServerParams","serverParams",[n]);if(n&&e.isArray(n)){var i={},o=/(.*?)\[\]$/;e.each(n,function(e,t){var n=t.name.match(o);if(n){var r=n[0];i[r]||(i[r]=[]);i[r].push(t.value)}else i[t.name]=t.value});n=i}var s,a=t.ajax,l=t.oInstance;if(e.isPlainObject(a)&&a.data){s=a.data;var u=e.isFunction(s)?s(n):s;n=e.isFunction(s)&&u?u:e.extend(!0,n,u);delete a.data}var c={data:n,success:function(e){var n=e.error||e.sError;n&&t.oApi._fnLog(t,0,n);t.json=e;Bt(t,null,"xhr",[t,e]);r(e)},dataType:"json",cache:!1,type:t.sServerMethod,error:function(e,n){var r=t.oApi._fnLog;"parsererror"==n?r(t,0,"Invalid JSON response",1):4===e.readyState&&r(t,0,"Ajax error",7);ht(t,!1)}};t.oAjaxData=n;Bt(t,null,"preXhr",[t,n]);if(t.fnServerData)t.fnServerData.call(l,t.sAjaxSource,e.map(n,function(e,t){return{name:t,value:e}}),r,t);else if(t.sAjaxSource||"string"==typeof a)t.jqXHR=e.ajax(e.extend(c,{url:a||t.sAjaxSource}));else if(e.isFunction(a))t.jqXHR=a.call(l,n,r,t);else{t.jqXHR=e.ajax(e.extend(c,a));a.data=s}}function V(e){if(e.bAjaxDataGet){e.iDraw++;ht(e,!0);H(e,W(e),function(t){z(e,t)});return!1}return!0}function W(t){var n,r,i,o,s=t.aoColumns,a=s.length,l=t.oFeatures,u=t.oPreviousSearch,c=t.aoPreSearchCols,p=[],d=Lt(t),f=t._iDisplayStart,h=l.bPaginate!==!1?t._iDisplayLength:-1,g=function(e,t){p.push({name:e,value:t})};g("sEcho",t.iDraw);g("iColumns",a);g("sColumns",fn(s,"sName").join(","));g("iDisplayStart",f);g("iDisplayLength",h);var m={draw:t.iDraw,columns:[],order:[],start:f,length:h,search:{value:u.sSearch,regex:u.bRegex}};for(n=0;a>n;n++){i=s[n];o=c[n];r="function"==typeof i.mData?"function":i.mData;m.columns.push({data:r,name:i.sName,searchable:i.bSearchable,orderable:i.bSortable,search:{value:o.sSearch,regex:o.bRegex}});g("mDataProp_"+n,r);if(l.bFilter){g("sSearch_"+n,o.sSearch);g("bRegex_"+n,o.bRegex);g("bSearchable_"+n,i.bSearchable)}l.bSort&&g("bSortable_"+n,i.bSortable)}if(l.bFilter){g("sSearch",u.sSearch);g("bRegex",u.bRegex)}if(l.bSort){e.each(d,function(e,t){m.order.push({column:t.col,dir:t.dir});g("iSortCol_"+e,t.col);g("sSortDir_"+e,t.dir)});g("iSortingCols",d.length)}var v=Xt.ext.legacy.ajax;return null===v?t.sAjaxSource?p:m:v?p:m}function z(e,t){var n=function(e,n){return t[e]!==o?t[e]:t[n]},r=n("sEcho","draw"),i=n("iTotalRecords","recordsTotal"),s=n("iTotalDisplayRecords","recordsFiltered");if(r){if(1*r<e.iDraw)return;e.iDraw=1*r}R(e);e._iRecordsTotal=parseInt(i,10);e._iRecordsDisplay=parseInt(s,10);for(var a=$(e,t),l=0,u=a.length;u>l;l++)x(e,a[l]);e.aiDisplay=e.aiDisplayMaster.slice();e.bAjaxDataGet=!1;j(e);e._bInitComplete||lt(e,t);e.bAjaxDataGet=!0;ht(e,!1)}function $(t,n){var r=e.isPlainObject(t.ajax)&&t.ajax.dataSrc!==o?t.ajax.dataSrc:t.sAjaxDataProp;return"data"===r?n.aaData||n[r]:""!==r?A(r)(n):n}function X(t){var n=t.oClasses,r=t.sTableId,o=t.oLanguage,s=t.oPreviousSearch,a=t.aanFeatures,l='<input type="search" class="'+n.sFilterInput+'"/>',u=o.sSearch;u=u.match(/_INPUT_/)?u.replace("_INPUT_",l):u+l;var c=e("<div/>",{id:a.f?null:r+"_filter","class":n.sFilter}).append(e("<label/>").append(u)),p=function(){var e=(a.f,this.value?this.value:"");if(e!=s.sSearch){Y(t,{sSearch:e,bRegex:s.bRegex,bSmart:s.bSmart,bCaseInsensitive:s.bCaseInsensitive});t._iDisplayStart=0;j(t)}},d=e("input",c).val(s.sSearch).attr("placeholder",o.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===Vt(t)?yt(p,400):p).bind("keypress.DT",function(e){return 13==e.keyCode?!1:void 0}).attr("aria-controls",r);e(t.nTable).on("search.dt.DT",function(e,n){if(t===n)try{d[0]!==i.activeElement&&d.val(s.sSearch)}catch(r){}});return c[0]}function Y(e,t,n){var r=e.oPreviousSearch,i=e.aoPreSearchCols,s=function(e){r.sSearch=e.sSearch;r.bRegex=e.bRegex;r.bSmart=e.bSmart;r.bCaseInsensitive=e.bCaseInsensitive},a=function(e){return e.bEscapeRegex!==o?!e.bEscapeRegex:e.bRegex};E(e);if("ssp"!=Vt(e)){J(e,t.sSearch,n,a(t),t.bSmart,t.bCaseInsensitive);s(t);for(var l=0;l<i.length;l++)Q(e,i[l].sSearch,l,a(i[l]),i[l].bSmart,i[l].bCaseInsensitive);K(e)}else s(t);e.bFiltered=!0;Bt(e,null,"search",[e])}function K(e){for(var t,n,r=Xt.ext.search,i=e.aiDisplay,o=0,s=r.length;s>o;o++){for(var a=[],l=0,u=i.length;u>l;l++){n=i[l];t=e.aoData[n];r[o](e,t._aFilterData,n,t._aData,l)&&a.push(n)}i.length=0;i.push.apply(i,a)}}function Q(e,t,n,r,i,o){if(""!==t)for(var s,a=e.aiDisplay,l=Z(t,r,i,o),u=a.length-1;u>=0;u--){s=e.aoData[a[u]]._aFilterData[n];l.test(s)||a.splice(u,1)}}function J(e,t,n,r,i,o){var s,a,l,u=Z(t,r,i,o),c=e.oPreviousSearch.sSearch,p=e.aiDisplayMaster;
0!==Xt.ext.search.length&&(n=!0);a=tt(e);if(t.length<=0)e.aiDisplay=p.slice();else{(a||n||c.length>t.length||0!==t.indexOf(c)||e.bSorted)&&(e.aiDisplay=p.slice());s=e.aiDisplay;for(l=s.length-1;l>=0;l--)u.test(e.aoData[s[l]]._sFilterRow)||s.splice(l,1)}}function Z(t,n,r,i){t=n?t:et(t);if(r){var o=e.map(t.match(/"[^"]+"|[^ ]+/g)||"",function(e){return'"'===e.charAt(0)?e.match(/^"(.*)"$/)[1]:e});t="^(?=.*?"+o.join(")(?=.*?")+").*$"}return new RegExp(t,i?"i":"")}function et(e){return e.replace(on,"\\$1")}function tt(e){var t,n,r,i,o,s,a,l,u=e.aoColumns,c=Xt.ext.type.search,p=!1;for(n=0,i=e.aoData.length;i>n;n++){l=e.aoData[n];if(!l._aFilterData){s=[];for(r=0,o=u.length;o>r;r++){t=u[r];if(t.bSearchable){a=N(e,n,r,"filter");c[t.sType]&&(a=c[t.sType](a));null===a&&(a="");"string"!=typeof a&&a.toString&&(a=a.toString())}else a="";if(a.indexOf&&-1!==a.indexOf("&")){bn.innerHTML=a;a=Tn?bn.textContent:bn.innerText}a.replace&&(a=a.replace(/[\r\n]/g,""));s.push(a)}l._aFilterData=s;l._sFilterRow=s.join(" ");p=!0}}return p}function nt(e){return{search:e.sSearch,smart:e.bSmart,regex:e.bRegex,caseInsensitive:e.bCaseInsensitive}}function rt(e){return{sSearch:e.search,bSmart:e.smart,bRegex:e.regex,bCaseInsensitive:e.caseInsensitive}}function it(t){var n=t.sTableId,r=t.aanFeatures.i,i=e("<div/>",{"class":t.oClasses.sInfo,id:r?null:n+"_info"});if(!r){t.aoDrawCallback.push({fn:ot,sName:"information"});i.attr("role","status").attr("aria-live","polite");e(t.nTable).attr("aria-describedby",n+"_info")}return i[0]}function ot(t){var n=t.aanFeatures.i;if(0!==n.length){var r=t.oLanguage,i=t._iDisplayStart+1,o=t.fnDisplayEnd(),s=t.fnRecordsTotal(),a=t.fnRecordsDisplay(),l=a?r.sInfo:r.sInfoEmpty;a!==s&&(l+=" "+r.sInfoFiltered);l+=r.sInfoPostFix;l=st(t,l);var u=r.fnInfoCallback;null!==u&&(l=u.call(t.oInstance,t,i,o,s,a,l));e(n).html(l)}}function st(e,t){var n=e.fnFormatNumber,r=e._iDisplayStart+1,i=e._iDisplayLength,o=e.fnRecordsDisplay(),s=-1===i;return t.replace(/_START_/g,n.call(e,r)).replace(/_END_/g,n.call(e,e.fnDisplayEnd())).replace(/_MAX_/g,n.call(e,e.fnRecordsTotal())).replace(/_TOTAL_/g,n.call(e,o)).replace(/_PAGE_/g,n.call(e,s?1:Math.ceil(r/i))).replace(/_PAGES_/g,n.call(e,s?1:Math.ceil(o/i)))}function at(e){var t,n,r,i=e.iInitDisplayStart,o=e.aoColumns,s=e.oFeatures;if(e.bInitialised){U(e);P(e);M(e,e.aoHeader);M(e,e.aoFooter);ht(e,!0);s.bAutoWidth&&Et(e);for(t=0,n=o.length;n>t;t++){r=o[t];r.sWidth&&(r.nTh.style.width=Nt(r.sWidth))}G(e);var a=Vt(e);if("ssp"!=a)if("ajax"==a)H(e,[],function(n){var r=$(e,n);for(t=0;t<r.length;t++)x(e,r[t]);e.iInitDisplayStart=i;G(e);ht(e,!1);lt(e,n)},e);else{ht(e,!1);lt(e)}}else setTimeout(function(){at(e)},200)}function lt(e,t){e._bInitComplete=!0;t&&f(e);Bt(e,"aoInitComplete","init",[e,t])}function ut(e,t){var n=parseInt(t,10);e._iDisplayLength=n;qt(e);Bt(e,null,"length",[e,n])}function ct(t){for(var n=t.oClasses,r=t.sTableId,i=t.aLengthMenu,o=e.isArray(i[0]),s=o?i[0]:i,a=o?i[1]:i,l=e("<select/>",{name:r+"_length","aria-controls":r,"class":n.sLengthSelect}),u=0,c=s.length;c>u;u++)l[0][u]=new Option(a[u],s[u]);var p=e("<div><label/></div>").addClass(n.sLength);t.aanFeatures.l||(p[0].id=r+"_length");p.children().append(t.oLanguage.sLengthMenu.replace("_MENU_",l[0].outerHTML));e("select",p).val(t._iDisplayLength).bind("change.DT",function(){ut(t,e(this).val());j(t)});e(t.nTable).bind("length.dt.DT",function(n,r,i){t===r&&e("select",p).val(i)});return p[0]}function pt(t){var n=t.sPaginationType,r=Xt.ext.pager[n],i="function"==typeof r,o=function(e){j(e)},s=e("<div/>").addClass(t.oClasses.sPaging+n)[0],a=t.aanFeatures;i||r.fnInit(t,s,o);if(!a.p){s.id=t.sTableId+"_paginate";t.aoDrawCallback.push({fn:function(e){if(i){var t,n,s=e._iDisplayStart,l=e._iDisplayLength,u=e.fnRecordsDisplay(),c=-1===l,p=c?0:Math.ceil(s/l),d=c?1:Math.ceil(u/l),f=r(p,d);for(t=0,n=a.p.length;n>t;t++)Ht(e,"pageButton")(e,a.p[t],t,f,p,d)}else r.fnUpdate(e,o)},sName:"pagination"})}return s}function dt(e,t,n){var r=e._iDisplayStart,i=e._iDisplayLength,o=e.fnRecordsDisplay();if(0===o||-1===i)r=0;else if("number"==typeof t){r=t*i;r>o&&(r=0)}else if("first"==t)r=0;else if("previous"==t){r=i>=0?r-i:0;0>r&&(r=0)}else"next"==t?o>r+i&&(r+=i):"last"==t?r=Math.floor((o-1)/i)*i:Pt(e,0,"Unknown paging action: "+t,5);var s=e._iDisplayStart!==r;e._iDisplayStart=r;if(s){Bt(e,null,"page",[e]);n&&j(e)}return s}function ft(t){return e("<div/>",{id:t.aanFeatures.r?null:t.sTableId+"_processing","class":t.oClasses.sProcessing}).html(t.oLanguage.sProcessing).insertBefore(t.nTable)[0]}function ht(t,n){t.oFeatures.bProcessing&&e(t.aanFeatures.r).css("display",n?"block":"none");Bt(t,null,"processing",[t,n])}function gt(t){var n=e(t.nTable);n.attr("role","grid");var r=t.oScroll;if(""===r.sX&&""===r.sY)return t.nTable;var i=r.sX,o=r.sY,s=t.oClasses,a=n.children("caption"),l=a.length?a[0]._captionSide:null,u=e(n[0].cloneNode(!1)),c=e(n[0].cloneNode(!1)),p=n.children("tfoot"),d="<div/>",f=function(e){return e?Nt(e):null};r.sX&&"100%"===n.attr("width")&&n.removeAttr("width");p.length||(p=null);var h=e(d,{"class":s.sScrollWrapper}).append(e(d,{"class":s.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:i?f(i):"100%"}).append(e(d,{"class":s.sScrollHeadInner}).css({"box-sizing":"content-box",width:r.sXInner||"100%"}).append(u.removeAttr("id").css("margin-left",0).append(n.children("thead")))).append("top"===l?a:null)).append(e(d,{"class":s.sScrollBody}).css({overflow:"auto",height:f(o),width:f(i)}).append(n));p&&h.append(e(d,{"class":s.sScrollFoot}).css({overflow:"hidden",border:0,width:i?f(i):"100%"}).append(e(d,{"class":s.sScrollFootInner}).append(c.removeAttr("id").css("margin-left",0).append(n.children("tfoot")))).append("bottom"===l?a:null));var g=h.children(),m=g[0],v=g[1],E=p?g[2]:null;i&&e(v).scroll(function(){var e=this.scrollLeft;m.scrollLeft=e;p&&(E.scrollLeft=e)});t.nScrollHead=m;t.nScrollBody=v;t.nScrollFoot=E;t.aoDrawCallback.push({fn:mt,sName:"scrolling"});return h[0]}function mt(t){var n,r,i,o,s,a,l,u,c,p=t.oScroll,d=p.sX,f=p.sXInner,g=p.sY,m=p.iBarWidth,v=e(t.nScrollHead),E=v[0].style,y=v.children("div"),x=y[0].style,b=y.children("table"),T=t.nScrollBody,S=e(T),N=T.style,C=e(t.nScrollFoot),L=C.children("div"),A=L.children("table"),I=e(t.nTHead),w=e(t.nTable),R=w[0],O=R.style,_=t.nTFoot?e(t.nTFoot):null,D=t.oBrowser,F=D.bScrollOversize,k=[],P=[],M=[],j=function(e){var t=e.style;t.paddingTop="0";t.paddingBottom="0";t.borderTopWidth="0";t.borderBottomWidth="0";t.height=0};w.children("thead, tfoot").remove();s=I.clone().prependTo(w);n=I.find("tr");i=s.find("tr");s.find("th, td").removeAttr("tabindex");if(_){a=_.clone().prependTo(w);r=_.find("tr");o=a.find("tr")}if(!d){N.width="100%";v[0].style.width="100%"}e.each(q(t,s),function(e,n){l=h(t,e);n.style.width=t.aoColumns[l].sWidth});_&&vt(function(e){e.style.width=""},o);p.bCollapse&&""!==g&&(N.height=S[0].offsetHeight+I[0].offsetHeight+"px");c=w.outerWidth();if(""===d){O.width="100%";F&&(w.find("tbody").height()>T.offsetHeight||"scroll"==S.css("overflow-y"))&&(O.width=Nt(w.outerWidth()-m))}else if(""!==f)O.width=Nt(f);else if(c==S.width()&&S.height()<w.height()){O.width=Nt(c-m);w.outerWidth()>c-m&&(O.width=Nt(c))}else O.width=Nt(c);c=w.outerWidth();vt(j,i);vt(function(t){M.push(t.innerHTML);k.push(Nt(e(t).css("width")))},i);vt(function(e,t){e.style.width=k[t]},n);e(i).height(0);if(_){vt(j,o);vt(function(t){P.push(Nt(e(t).css("width")))},o);vt(function(e,t){e.style.width=P[t]},r);e(o).height(0)}vt(function(e,t){e.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+M[t]+"</div>";e.style.width=k[t]},i);_&&vt(function(e,t){e.innerHTML="";e.style.width=P[t]},o);if(w.outerWidth()<c){u=T.scrollHeight>T.offsetHeight||"scroll"==S.css("overflow-y")?c+m:c;F&&(T.scrollHeight>T.offsetHeight||"scroll"==S.css("overflow-y"))&&(O.width=Nt(u-m));(""===d||""!==f)&&Pt(t,1,"Possible column misalignment",6)}else u="100%";N.width=Nt(u);E.width=Nt(u);_&&(t.nScrollFoot.style.width=Nt(u));g||F&&(N.height=Nt(R.offsetHeight+m));if(g&&p.bCollapse){N.height=Nt(g);var G=d&&R.offsetWidth>T.offsetWidth?m:0;R.offsetHeight<T.offsetHeight&&(N.height=Nt(R.offsetHeight+G))}var U=w.outerWidth();b[0].style.width=Nt(U);x.width=Nt(U);var B=w.height()>T.clientHeight||"scroll"==S.css("overflow-y"),H="padding"+(D.bScrollbarLeft?"Left":"Right");x[H]=B?m+"px":"0px";if(_){A[0].style.width=Nt(U);L[0].style.width=Nt(U);L[0].style[H]=B?m+"px":"0px"}S.scroll();!t.bSorted&&!t.bFiltered||t._drawHold||(T.scrollTop=0)}function vt(e,t,n){for(var r,i,o=0,s=0,a=t.length;a>s;){r=t[s].firstChild;i=n?n[s].firstChild:null;for(;r;){if(1===r.nodeType){n?e(r,i,o):e(r,o);o++}r=r.nextSibling;i=n?i.nextSibling:null}s++}}function Et(t){var r,i,o,s,a,l=t.nTable,u=t.aoColumns,c=t.oScroll,p=c.sY,d=c.sX,h=c.sXInner,g=u.length,E=v(t,"bVisible"),y=e("th",t.nTHead),x=l.getAttribute("width"),b=l.parentNode,T=!1;for(r=0;r<E.length;r++){i=u[E[r]];if(null!==i.sWidth){i.sWidth=xt(i.sWidthOrig,b);T=!0}}if(T||d||p||g!=m(t)||g!=y.length){var S=e(l).clone().empty().css("visibility","hidden").removeAttr("id").append(e(t.nTHead).clone(!1)).append(e(t.nTFoot).clone(!1)).append(e("<tbody><tr/></tbody>"));S.find("tfoot th, tfoot td").css("width","");var N=S.find("tbody tr");y=q(t,S.find("thead")[0]);for(r=0;r<E.length;r++){i=u[E[r]];y[r].style.width=null!==i.sWidthOrig&&""!==i.sWidthOrig?Nt(i.sWidthOrig):""}if(t.aoData.length)for(r=0;r<E.length;r++){o=E[r];i=u[o];e(Tt(t,o)).clone(!1).append(i.sContentPadding).appendTo(N)}S.appendTo(b);if(d&&h)S.width(h);else if(d){S.css("width","auto");S.width()<b.offsetWidth&&S.width(b.offsetWidth)}else p?S.width(b.offsetWidth):x&&S.width(x);bt(t,S[0]);if(d){var C=0;for(r=0;r<E.length;r++){i=u[E[r]];a=e(y[r]).outerWidth();C+=null===i.sWidthOrig?a:parseInt(i.sWidth,10)+a-e(y[r]).width()}S.width(Nt(C));l.style.width=Nt(C)}for(r=0;r<E.length;r++){i=u[E[r]];s=e(y[r]).width();s&&(i.sWidth=Nt(s))}l.style.width=Nt(S.css("width"));S.remove()}else for(r=0;g>r;r++)u[r].sWidth=Nt(y.eq(r).width());x&&(l.style.width=Nt(x));if((x||d)&&!t._reszEvt){e(n).bind("resize.DT-"+t.sInstance,yt(function(){f(t)}));t._reszEvt=!0}}function yt(e,t){var n,r,i=t||200;return function(){var t=this,s=+new Date,a=arguments;if(n&&n+i>s){clearTimeout(r);r=setTimeout(function(){n=o;e.apply(t,a)},i)}else if(n){n=s;e.apply(t,a)}else n=s}}function xt(t,n){if(!t)return 0;var r=e("<div/>").css("width",Nt(t)).appendTo(n||i.body),o=r[0].offsetWidth;r.remove();return o}function bt(t,n){var r=t.oScroll;if(r.sX||r.sY){var i=r.sX?0:r.iBarWidth;n.style.width=Nt(e(n).outerWidth()-i)}}function Tt(t,n){var r=St(t,n);if(0>r)return null;var i=t.aoData[r];return i.nTr?i.anCells[n]:e("<td/>").html(N(t,r,n,"display"))[0]}function St(e,t){for(var n,r=-1,i=-1,o=0,s=e.aoData.length;s>o;o++){n=N(e,o,t,"display")+"";n=n.replace(Sn,"");if(n.length>r){r=n.length;i=o}}return i}function Nt(e){return null===e?"0px":"number"==typeof e?0>e?"0px":e+"px":e.match(/\d$/)?e+"px":e}function Ct(){if(!Xt.__scrollbarWidth){var t=e("<p/>").css({width:"100%",height:200,padding:0})[0],n=e("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(t).appendTo("body"),r=t.offsetWidth;n.css("overflow","scroll");var i=t.offsetWidth;r===i&&(i=n[0].clientWidth);n.remove();Xt.__scrollbarWidth=r-i}return Xt.__scrollbarWidth}function Lt(t){var n,r,i,o,s,a,l,u=[],c=t.aoColumns,p=t.aaSortingFixed,d=e.isPlainObject(p),f=[],h=function(t){t.length&&!e.isArray(t[0])?f.push(t):f.push.apply(f,t)};e.isArray(p)&&h(p);d&&p.pre&&h(p.pre);h(t.aaSorting);d&&p.post&&h(p.post);for(n=0;n<f.length;n++){l=f[n][0];o=c[l].aDataSort;for(r=0,i=o.length;i>r;r++){s=o[r];a=c[s].sType||"string";u.push({src:l,col:s,dir:f[n][1],index:f[n][2],type:a,formatter:Xt.ext.type.order[a+"-pre"]})}}return u}function At(e){var t,n,r,i,o,s=[],a=Xt.ext.type.order,l=e.aoData,u=(e.aoColumns,0),c=e.aiDisplayMaster;E(e);o=Lt(e);for(t=0,n=o.length;n>t;t++){i=o[t];i.formatter&&u++;_t(e,i.col)}if("ssp"!=Vt(e)&&0!==o.length){for(t=0,r=c.length;r>t;t++)s[c[t]]=t;c.sort(u===o.length?function(e,t){var n,r,i,a,u,c=o.length,p=l[e]._aSortData,d=l[t]._aSortData;for(i=0;c>i;i++){u=o[i];n=p[u.col];r=d[u.col];a=r>n?-1:n>r?1:0;if(0!==a)return"asc"===u.dir?a:-a}n=s[e];r=s[t];return r>n?-1:n>r?1:0}:function(e,t){var n,r,i,u,c,p,d=o.length,f=l[e]._aSortData,h=l[t]._aSortData;for(i=0;d>i;i++){c=o[i];n=f[c.col];r=h[c.col];p=a[c.type+"-"+c.dir]||a["string-"+c.dir];u=p(n,r);if(0!==u)return u}n=s[e];r=s[t];return r>n?-1:n>r?1:0})}e.bSorted=!0}function It(e){for(var t,n,r=e.aoColumns,i=Lt(e),o=e.oLanguage.oAria,s=0,a=r.length;a>s;s++){var l=r[s],u=l.asSorting,c=l.sTitle.replace(/<.*?>/g,""),p=l.nTh;p.removeAttribute("aria-sort");if(l.bSortable){if(i.length>0&&i[0].col==s){p.setAttribute("aria-sort","asc"==i[0].dir?"ascending":"descending");n=u[i[0].index+1]||u[0]}else n=u[0];t=c+("asc"===n?o.sSortAscending:o.sSortDescending)}else t=c;p.setAttribute("aria-label",t)}}function wt(t,n,r,i){var s,a=t.aoColumns[n],l=t.aaSorting,u=a.asSorting,c=function(t){var n=t._idx;n===o&&(n=e.inArray(t[1],u));return n+1>=u.length?0:n+1};"number"==typeof l[0]&&(l=t.aaSorting=[l]);if(r&&t.oFeatures.bSortMulti){var p=e.inArray(n,fn(l,"0"));if(-1!==p){s=c(l[p]);l[p][1]=u[s];l[p]._idx=s}else{l.push([n,u[0],0]);l[l.length-1]._idx=0}}else if(l.length&&l[0][0]==n){s=c(l[0]);l.length=1;l[0][1]=u[s];l[0]._idx=s}else{l.length=0;l.push([n,u[0]]);l[0]._idx=0}G(t);"function"==typeof i&&i(t)}function Rt(e,t,n,r){var i=e.aoColumns[n];Gt(t,{},function(t){if(i.bSortable!==!1)if(e.oFeatures.bProcessing){ht(e,!0);setTimeout(function(){wt(e,n,t.shiftKey,r);"ssp"!==Vt(e)&&ht(e,!1)},0)}else wt(e,n,t.shiftKey,r)})}function Ot(t){var n,r,i,o=t.aLastSort,s=t.oClasses.sSortColumn,a=Lt(t),l=t.oFeatures;if(l.bSort&&l.bSortClasses){for(n=0,r=o.length;r>n;n++){i=o[n].src;e(fn(t.aoData,"anCells",i)).removeClass(s+(2>n?n+1:3))}for(n=0,r=a.length;r>n;n++){i=a[n].src;e(fn(t.aoData,"anCells",i)).addClass(s+(2>n?n+1:3))}}t.aLastSort=a}function _t(e,t){var n,r=e.aoColumns[t],i=Xt.ext.order[r.sSortDataType];i&&(n=i.call(e.oInstance,e,t,g(e,t)));for(var o,s,a=Xt.ext.type.order[r.sType+"-pre"],l=0,u=e.aoData.length;u>l;l++){o=e.aoData[l];o._aSortData||(o._aSortData=[]);if(!o._aSortData[t]||i){s=i?n[l]:N(e,l,t,"sort");o._aSortData[t]=a?a(s):s}}}function Dt(t){if(t.oFeatures.bStateSave&&!t.bDestroying){var n={time:+new Date,start:t._iDisplayStart,length:t._iDisplayLength,order:e.extend(!0,[],t.aaSorting),search:nt(t.oPreviousSearch),columns:e.map(t.aoColumns,function(e,n){return{visible:e.bVisible,search:nt(t.aoPreSearchCols[n])}})};Bt(t,"aoStateSaveParams","stateSaveParams",[t,n]);t.oSavedState=n;t.fnStateSaveCallback.call(t.oInstance,t,n)}}function Ft(t){var n,r,i=t.aoColumns;if(t.oFeatures.bStateSave){var o=t.fnStateLoadCallback.call(t.oInstance,t);if(o&&o.time){var s=Bt(t,"aoStateLoadParams","stateLoadParams",[t,o]);if(-1===e.inArray(!1,s)){var a=t.iStateDuration;if(!(a>0&&o.time<+new Date-1e3*a)&&i.length===o.columns.length){t.oLoadedState=e.extend(!0,{},o);t._iDisplayStart=o.start;t.iInitDisplayStart=o.start;t._iDisplayLength=o.length;t.aaSorting=[];e.each(o.order,function(e,n){t.aaSorting.push(n[0]>=i.length?[0,n[1]]:n)});e.extend(t.oPreviousSearch,rt(o.search));for(n=0,r=o.columns.length;r>n;n++){var l=o.columns[n];i[n].bVisible=l.visible;e.extend(t.aoPreSearchCols[n],rt(l.search))}Bt(t,"aoStateLoaded","stateLoaded",[t,o])}}}}}function kt(t){var n=Xt.settings,r=e.inArray(t,fn(n,"nTable"));return-1!==r?n[r]:null}function Pt(e,t,r,i){r="DataTables warning: "+(null!==e?"table id="+e.sTableId+" - ":"")+r;i&&(r+=". For more information about this error, please see http://datatables.net/tn/"+i);if(t)n.console&&console.log&&console.log(r);else{var o=Xt.ext,s=o.sErrMode||o.errMode;if("alert"!=s)throw new Error(r);alert(r)}}function Mt(t,n,r,i){if(e.isArray(r))e.each(r,function(r,i){e.isArray(i)?Mt(t,n,i[0],i[1]):Mt(t,n,i)});else{i===o&&(i=r);n[r]!==o&&(t[i]=n[r])}}function jt(t,n,r){var i;for(var o in n)if(n.hasOwnProperty(o)){i=n[o];if(e.isPlainObject(i)){e.isPlainObject(t[o])||(t[o]={});e.extend(!0,t[o],i)}else t[o]=r&&"data"!==o&&"aaData"!==o&&e.isArray(i)?i.slice():i}return t}function Gt(t,n,r){e(t).bind("click.DT",n,function(e){t.blur();r(e)}).bind("keypress.DT",n,function(e){if(13===e.which){e.preventDefault();r(e)}}).bind("selectstart.DT",function(){return!1})}function Ut(e,t,n,r){n&&e[t].push({fn:n,sName:r})}function Bt(t,n,r,i){var o=[];n&&(o=e.map(t[n].slice().reverse(),function(e){return e.fn.apply(t.oInstance,i)}));null!==r&&e(t.nTable).trigger(r+".dt",i);return o}function qt(e){var t=e._iDisplayStart,n=e.fnDisplayEnd(),r=e._iDisplayLength;n===e.fnRecordsDisplay()&&(t=n-r);(-1===r||0>t)&&(t=0);e._iDisplayStart=t}function Ht(t,n){var r=t.renderer,i=Xt.ext.renderer[n];return e.isPlainObject(r)&&r[n]?i[r[n]]||i._:"string"==typeof r?i[r]||i._:i._}function Vt(e){return e.oFeatures.bServerSide?"ssp":e.ajax||e.sAjaxSource?"ajax":"dom"}function Wt(e,t){var n=[],r=Wn.numbers_length,i=Math.floor(r/2);if(r>=t)n=gn(0,t);else if(i>=e){n=gn(0,r-2);n.push("ellipsis");n.push(t-1)}else if(e>=t-1-i){n=gn(t-(r-2),t);n.splice(0,0,"ellipsis");n.splice(0,0,0)}else{n=gn(e-1,e+2);n.push("ellipsis");n.push(t-1);n.splice(0,0,"ellipsis");n.splice(0,0,0)}n.DT_el="span";return n}function zt(t){e.each({num:function(e){return zn(e,t)},"num-fmt":function(e){return zn(e,t,sn)},"html-num":function(e){return zn(e,t,tn)},"html-num-fmt":function(e){return zn(e,t,tn,sn)}},function(e,n){Yt.type.order[e+t+"-pre"]=n})}function $t(e){return function(){var t=[kt(this[Xt.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return Xt.ext.internal[e].apply(this,t)}}var Xt,Yt,Kt,Qt,Jt,Zt={},en=/[\r\n]/g,tn=/<.*?>/g,nn=/^[\w\+\-]/,rn=/[\w\+\-]$/,on=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g"),sn=/[',$£€¥%\u2009\u202F]/g,an=function(e){return e&&e!==!0&&"-"!==e?!1:!0},ln=function(e){var t=parseInt(e,10);return!isNaN(t)&&isFinite(e)?t:null},un=function(e,t){Zt[t]||(Zt[t]=new RegExp(et(t),"g"));return"string"==typeof e?e.replace(/\./g,"").replace(Zt[t],"."):e},cn=function(e,t,n){var r="string"==typeof e;t&&r&&(e=un(e,t));n&&r&&(e=e.replace(sn,""));return an(e)||!isNaN(parseFloat(e))&&isFinite(e)},pn=function(e){return an(e)||"string"==typeof e},dn=function(e,t,n){if(an(e))return!0;var r=pn(e);return r&&cn(mn(e),t,n)?!0:null},fn=function(e,t,n){var r=[],i=0,s=e.length;if(n!==o)for(;s>i;i++)e[i]&&e[i][t]&&r.push(e[i][t][n]);else for(;s>i;i++)e[i]&&r.push(e[i][t]);return r},hn=function(e,t,n,r){var i=[],s=0,a=t.length;if(r!==o)for(;a>s;s++)i.push(e[t[s]][n][r]);else for(;a>s;s++)i.push(e[t[s]][n]);return i},gn=function(e,t){var n,r=[];if(t===o){t=0;n=e}else{n=t;t=e}for(var i=t;n>i;i++)r.push(i);return r},mn=function(e){return e.replace(tn,"")},vn=function(e){var t,n,r,i=[],o=e.length,s=0;e:for(n=0;o>n;n++){t=e[n];for(r=0;s>r;r++)if(i[r]===t)continue e;i.push(t);s++}return i},En=function(e,t,n){e[t]!==o&&(e[n]=e[t])},yn=/\[.*?\]$/,xn=/\(\)$/,bn=e("<div>")[0],Tn=bn.textContent!==o,Sn=/<.*?>/g;Xt=function(t){this.$=function(e,t){return this.api(!0).$(e,t)};this._=function(e,t){return this.api(!0).rows(e,t).data()};this.api=function(e){return new Kt(e?kt(this[Yt.iApiIndex]):this)};this.fnAddData=function(t,n){var r=this.api(!0),i=e.isArray(t)&&(e.isArray(t[0])||e.isPlainObject(t[0]))?r.rows.add(t):r.row.add(t);(n===o||n)&&r.draw();return i.flatten().toArray()};this.fnAdjustColumnSizing=function(e){var t=this.api(!0).columns.adjust(),n=t.settings()[0],r=n.oScroll;e===o||e?t.draw(!1):(""!==r.sX||""!==r.sY)&&mt(n)};this.fnClearTable=function(e){var t=this.api(!0).clear();(e===o||e)&&t.draw()};this.fnClose=function(e){this.api(!0).row(e).child.hide()};this.fnDeleteRow=function(e,t,n){var r=this.api(!0),i=r.rows(e),s=i.settings()[0],a=s.aoData[i[0][0]];i.remove();t&&t.call(this,s,a);(n===o||n)&&r.draw();return a};this.fnDestroy=function(e){this.api(!0).destroy(e)};this.fnDraw=function(e){this.api(!0).draw(!e)};this.fnFilter=function(e,t,n,r,i,s){var a=this.api(!0);null===t||t===o?a.search(e,n,r,s):a.column(t).search(e,n,r,s);a.draw()};this.fnGetData=function(e,t){var n=this.api(!0);if(e!==o){var r=e.nodeName?e.nodeName.toLowerCase():"";return t!==o||"td"==r||"th"==r?n.cell(e,t).data():n.row(e).data()||null}return n.data().toArray()};this.fnGetNodes=function(e){var t=this.api(!0);return e!==o?t.row(e).node():t.rows().nodes().flatten().toArray()};this.fnGetPosition=function(e){var t=this.api(!0),n=e.nodeName.toUpperCase();if("TR"==n)return t.row(e).index();if("TD"==n||"TH"==n){var r=t.cell(e).index();return[r.row,r.columnVisible,r.column]}return null};this.fnIsOpen=function(e){return this.api(!0).row(e).child.isShown()};this.fnOpen=function(e,t,n){return this.api(!0).row(e).child(t,n).show().child()[0]};this.fnPageChange=function(e,t){var n=this.api(!0).page(e);(t===o||t)&&n.draw(!1)};this.fnSetColumnVis=function(e,t,n){var r=this.api(!0).column(e).visible(t);(n===o||n)&&r.columns.adjust().draw()};this.fnSettings=function(){return kt(this[Yt.iApiIndex])};this.fnSort=function(e){this.api(!0).order(e).draw()};this.fnSortListener=function(e,t,n){this.api(!0).order.listener(e,t,n)};this.fnUpdate=function(e,t,n,r,i){var s=this.api(!0);n===o||null===n?s.row(t).data(e):s.cell(t,n).data(e);(i===o||i)&&s.columns.adjust();(r===o||r)&&s.draw();return 0};this.fnVersionCheck=Yt.fnVersionCheck;var n=this,i=t===o,c=this.length;i&&(t={});this.oApi=this.internal=Yt.internal;for(var f in Xt.ext.internal)f&&(this[f]=$t(f));this.each(function(){var f,h={},g=c>1?jt(h,t,!0):t,m=0,v=this.getAttribute("id"),E=!1,T=Xt.defaults;if("table"==this.nodeName.toLowerCase()){a(T);l(T.column);r(T,T,!0);r(T.column,T.column,!0);r(T,g);var S=Xt.settings;for(m=0,f=S.length;f>m;m++){if(S[m].nTable==this){var N=g.bRetrieve!==o?g.bRetrieve:T.bRetrieve,C=g.bDestroy!==o?g.bDestroy:T.bDestroy;if(i||N)return S[m].oInstance;if(C){S[m].oInstance.fnDestroy();break}Pt(S[m],0,"Cannot reinitialise DataTable",3);return}if(S[m].sTableId==this.id){S.splice(m,1);break}}if(null===v||""===v){v="DataTables_Table_"+Xt.ext._unique++;this.id=v}var L=e.extend(!0,{},Xt.models.oSettings,{nTable:this,oApi:n.internal,oInit:g,sDestroyWidth:e(this)[0].style.width,sInstance:v,sTableId:v});S.push(L);L.oInstance=1===n.length?n:e(this).dataTable();a(g);g.oLanguage&&s(g.oLanguage);g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=e.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]);g=jt(e.extend(!0,{},T),g);Mt(L.oFeatures,g,["bPaginate","bLengthChange","bFilter","bSort","bSortMulti","bInfo","bProcessing","bAutoWidth","bSortClasses","bServerSide","bDeferRender"]);Mt(L,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);Mt(L.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);Mt(L.oLanguage,g,"fnInfoCallback");Ut(L,"aoDrawCallback",g.fnDrawCallback,"user");Ut(L,"aoServerParams",g.fnServerParams,"user");Ut(L,"aoStateSaveParams",g.fnStateSaveParams,"user");Ut(L,"aoStateLoadParams",g.fnStateLoadParams,"user");Ut(L,"aoStateLoaded",g.fnStateLoaded,"user");Ut(L,"aoRowCallback",g.fnRowCallback,"user");Ut(L,"aoRowCreatedCallback",g.fnCreatedRow,"user");Ut(L,"aoHeaderCallback",g.fnHeaderCallback,"user");Ut(L,"aoFooterCallback",g.fnFooterCallback,"user");Ut(L,"aoInitComplete",g.fnInitComplete,"user");Ut(L,"aoPreDrawCallback",g.fnPreDrawCallback,"user");var A=L.oClasses;if(g.bJQueryUI){e.extend(A,Xt.ext.oJUIClasses,g.oClasses);g.sDom===T.sDom&&"lfrtip"===T.sDom&&(L.sDom='<"H"lfr>t<"F"ip>');L.renderer?e.isPlainObject(L.renderer)&&!L.renderer.header&&(L.renderer.header="jqueryui"):L.renderer="jqueryui"}else e.extend(A,Xt.ext.classes,g.oClasses);e(this).addClass(A.sTable);(""!==L.oScroll.sX||""!==L.oScroll.sY)&&(L.oScroll.iBarWidth=Ct());L.oScroll.sX===!0&&(L.oScroll.sX="100%");if(L.iInitDisplayStart===o){L.iInitDisplayStart=g.iDisplayStart;L._iDisplayStart=g.iDisplayStart}if(null!==g.iDeferLoading){L.bDeferLoading=!0;var I=e.isArray(g.iDeferLoading);L._iRecordsDisplay=I?g.iDeferLoading[0]:g.iDeferLoading;L._iRecordsTotal=I?g.iDeferLoading[1]:g.iDeferLoading}if(""!==g.oLanguage.sUrl){L.oLanguage.sUrl=g.oLanguage.sUrl;e.getJSON(L.oLanguage.sUrl,null,function(t){s(t);r(T.oLanguage,t);e.extend(!0,L.oLanguage,g.oLanguage,t);at(L)});E=!0}else e.extend(!0,L.oLanguage,g.oLanguage);null===g.asStripeClasses&&(L.asStripeClasses=[A.sStripeOdd,A.sStripeEven]);var w=L.asStripeClasses,R=e("tbody tr:eq(0)",this);if(-1!==e.inArray(!0,e.map(w,function(e){return R.hasClass(e)}))){e("tbody tr",this).removeClass(w.join(" "));L.asDestroyStripes=w.slice()}var O,_=[],F=this.getElementsByTagName("thead");if(0!==F.length){B(L.aoHeader,F[0]);_=q(L)}if(null===g.aoColumns){O=[];for(m=0,f=_.length;f>m;m++)O.push(null)}else O=g.aoColumns;for(m=0,f=O.length;f>m;m++)p(L,_?_[m]:null);y(L,g.aoColumnDefs,O,function(e,t){d(L,e,t)});if(R.length){var k=function(e,t){return e.getAttribute("data-"+t)?t:null};e.each(D(L,R[0]).cells,function(e,t){var n=L.aoColumns[e];if(n.mData===e){var r=k(t,"sort")||k(t,"order"),i=k(t,"filter")||k(t,"search");if(null!==r||null!==i){n.mData={_:e+".display",sort:null!==r?e+".@data-"+r:o,type:null!==r?e+".@data-"+r:o,filter:null!==i?e+".@data-"+i:o};d(L,e)}}})}var P=L.oFeatures;if(g.bStateSave){P.bStateSave=!0;Ft(L,g);Ut(L,"aoDrawCallback",Dt,"state_save")}if(g.aaSorting===o){var M=L.aaSorting;for(m=0,f=M.length;f>m;m++)M[m][1]=L.aoColumns[m].asSorting[0]}Ot(L);P.bSort&&Ut(L,"aoDrawCallback",function(){if(L.bSorted){var t=Lt(L),n={};e.each(t,function(e,t){n[t.src]=t.dir});Bt(L,null,"order",[L,t,n]);It(L)}});Ut(L,"aoDrawCallback",function(){(L.bSorted||"ssp"===Vt(L)||P.bDeferRender)&&Ot(L)},"sc");u(L);var j=e(this).children("caption").each(function(){this._captionSide=e(this).css("caption-side")}),G=e(this).children("thead");0===G.length&&(G=e("<thead/>").appendTo(this));L.nTHead=G[0];var U=e(this).children("tbody");0===U.length&&(U=e("<tbody/>").appendTo(this));L.nTBody=U[0];var H=e(this).children("tfoot");0===H.length&&j.length>0&&(""!==L.oScroll.sX||""!==L.oScroll.sY)&&(H=e("<tfoot/>").appendTo(this));if(0===H.length||0===H.children().length)e(this).addClass(A.sNoFooter);else if(H.length>0){L.nTFoot=H[0];B(L.aoFooter,L.nTFoot)}if(g.aaData)for(m=0;m<g.aaData.length;m++)x(L,g.aaData[m]);else(L.bDeferLoading||"dom"==Vt(L))&&b(L,e(L.nTBody).children("tr"));L.aiDisplay=L.aiDisplayMaster.slice();L.bInitialised=!0;E===!1&&at(L)}else Pt(null,0,"Non-table node initialisation ("+this.nodeName+")",2)});n=null;return this};var Nn=[],Cn=Array.prototype,Ln=function(t){var n,r,i=Xt.settings,o=e.map(i,function(e){return e.nTable});if(!t)return[];if(t.nTable&&t.oApi)return[t];if(t.nodeName&&"table"===t.nodeName.toLowerCase()){n=e.inArray(t,o);return-1!==n?[i[n]]:null}if(t&&"function"==typeof t.settings)return t.settings().toArray();"string"==typeof t?r=e(t):t instanceof e&&(r=t);return r?r.map(function(){n=e.inArray(this,o);return-1!==n?i[n]:null}).toArray():void 0};Kt=function(t,n){if(!this instanceof Kt)throw"DT API must be constructed as a new object";var r=[],i=function(e){var t=Ln(e);t&&r.push.apply(r,t)};if(e.isArray(t))for(var o=0,s=t.length;s>o;o++)i(t[o]);else i(t);this.context=vn(r);n&&this.push.apply(this,n.toArray?n.toArray():n);this.selector={rows:null,cols:null,opts:null};Kt.extend(this,this,Nn)};Xt.Api=Kt;Kt.prototype={concat:Cn.concat,context:[],each:function(e){for(var t=0,n=this.length;n>t;t++)e.call(this,this[t],t,this);return this},eq:function(e){var t=this.context;return t.length>e?new Kt(t[e],this[e]):null},filter:function(e){var t=[];if(Cn.filter)t=Cn.filter.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)e.call(this,this[n],n,this)&&t.push(this[n]);return new Kt(this.context,t)},flatten:function(){var e=[];return new Kt(this.context,e.concat.apply(e,this.toArray()))},join:Cn.join,indexOf:Cn.indexOf||function(e,t){for(var n=t||0,r=this.length;r>n;n++)if(this[n]===e)return n;return-1},iterator:function(e,t,n){var r,i,s,a,l,u,c,p,d=[],f=this.context,h=this.selector;if("string"==typeof e){n=t;t=e;e=!1}for(i=0,s=f.length;s>i;i++)if("table"===t){r=n(f[i],i);r!==o&&d.push(r)}else if("columns"===t||"rows"===t){r=n(f[i],this[i],i);r!==o&&d.push(r)}else if("column"===t||"column-rows"===t||"row"===t||"cell"===t){c=this[i];"column-rows"===t&&(u=_n(f[i],h.opts));for(a=0,l=c.length;l>a;a++){p=c[a];r="cell"===t?n(f[i],p.row,p.column,i,a):n(f[i],p,i,a,u);r!==o&&d.push(r)}}if(d.length){var g=new Kt(f,e?d.concat.apply([],d):d),m=g.selector;m.rows=h.rows;m.cols=h.cols;m.opts=h.opts;return g}return this},lastIndexOf:Cn.lastIndexOf||function(){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(e){var t=[];if(Cn.map)t=Cn.map.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)t.push(e.call(this,this[n],n));return new Kt(this.context,t)},pluck:function(e){return this.map(function(t){return t[e]})},pop:Cn.pop,push:Cn.push,reduce:Cn.reduce||function(e,t){return c(this,e,t,0,this.length,1)},reduceRight:Cn.reduceRight||function(e,t){return c(this,e,t,this.length-1,-1,-1)},reverse:Cn.reverse,selector:null,shift:Cn.shift,sort:Cn.sort,splice:Cn.splice,toArray:function(){return Cn.slice.call(this)},to$:function(){return e(this)},toJQuery:function(){return e(this)},unique:function(){return new Kt(this.context,vn(this))},unshift:Cn.unshift};Kt.extend=function(t,n,r){if(n&&(n instanceof Kt||n.__dt_wrapper)){var i,o,s,a=function(e,t,n){return function(){var r=t.apply(e,arguments);Kt.extend(r,r,n.methodExt);return r}};for(i=0,o=r.length;o>i;i++){s=r[i];n[s.name]="function"==typeof s.val?a(t,s.val,s):e.isPlainObject(s.val)?{}:s.val;n[s.name].__dt_wrapper=!0;Kt.extend(t,n[s.name],s.propExt)}}};Kt.register=Qt=function(t,n){if(e.isArray(t))for(var r=0,i=t.length;i>r;r++)Kt.register(t[r],n);else{var o,s,a,l,u=t.split("."),c=Nn,p=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n].name===t)return e[n];return null};for(o=0,s=u.length;s>o;o++){l=-1!==u[o].indexOf("()");a=l?u[o].replace("()",""):u[o];var d=p(c,a);if(!d){d={name:a,val:{},methodExt:[],propExt:[]};c.push(d)}o===s-1?d.val=n:c=l?d.methodExt:d.propExt}}};Kt.registerPlural=Jt=function(t,n,r){Kt.register(t,r);Kt.register(n,function(){var t=r.apply(this,arguments);return t===this?this:t instanceof Kt?t.length?e.isArray(t[0])?new Kt(t.context,t[0]):t[0]:o:t})};var An=function(t,n){if("number"==typeof t)return[n[t]];var r=e.map(n,function(e){return e.nTable});return e(r).filter(t).map(function(){var t=e.inArray(this,r);return n[t]}).toArray()};Qt("tables()",function(e){return e?new Kt(An(e,this.context)):this});Qt("table()",function(e){var t=this.tables(e),n=t.context;return n.length?new Kt(n[0]):t});Jt("tables().nodes()","table().node()",function(){return this.iterator("table",function(e){return e.nTable})});Jt("tables().body()","table().body()",function(){return this.iterator("table",function(e){return e.nTBody})});Jt("tables().header()","table().header()",function(){return this.iterator("table",function(e){return e.nTHead})});Jt("tables().footer()","table().footer()",function(){return this.iterator("table",function(e){return e.nTFoot})});Jt("tables().containers()","table().container()",function(){return this.iterator("table",function(e){return e.nTableWrapper})});Qt("draw()",function(e){return this.iterator("table",function(t){G(t,e===!1)})});Qt("page()",function(e){return e===o?this.page.info().page:this.iterator("table",function(t){dt(t,e)})});Qt("page.info()",function(){if(0===this.context.length)return o;var e=this.context[0],t=e._iDisplayStart,n=e._iDisplayLength,r=e.fnRecordsDisplay(),i=-1===n;return{page:i?0:Math.floor(t/n),pages:i?1:Math.ceil(r/n),start:t,end:e.fnDisplayEnd(),length:n,recordsTotal:e.fnRecordsTotal(),recordsDisplay:r}
});Qt("page.len()",function(e){return e===o?0!==this.context.length?this.context[0]._iDisplayLength:o:this.iterator("table",function(t){ut(t,e)})});var In=function(e,t,n){if("ssp"==Vt(e))G(e,t);else{ht(e,!0);H(e,[],function(n){R(e);for(var r=$(e,n),i=0,o=r.length;o>i;i++)x(e,r[i]);G(e,t);ht(e,!1)})}if(n){var r=new Kt(e);r.one("draw",function(){n(r.ajax.json())})}};Qt("ajax.json()",function(){var e=this.context;return e.length>0?e[0].json:void 0});Qt("ajax.params()",function(){var e=this.context;return e.length>0?e[0].oAjaxData:void 0});Qt("ajax.reload()",function(e,t){return this.iterator("table",function(n){In(n,t===!1,e)})});Qt("ajax.url()",function(t){var n=this.context;if(t===o){if(0===n.length)return o;n=n[0];return n.ajax?e.isPlainObject(n.ajax)?n.ajax.url:n.ajax:n.sAjaxSource}return this.iterator("table",function(n){e.isPlainObject(n.ajax)?n.ajax.url=t:n.ajax=t})});Qt("ajax.url().load()",function(e,t){return this.iterator("table",function(n){In(n,t===!1,e)})});var wn=function(t,n){var r,i,s,a,l,u,c=[];t&&"string"!=typeof t&&t.length!==o||(t=[t]);for(s=0,a=t.length;a>s;s++){i=t[s]&&t[s].split?t[s].split(","):[t[s]];for(l=0,u=i.length;u>l;l++){r=n("string"==typeof i[l]?e.trim(i[l]):i[l]);r&&r.length&&c.push.apply(c,r)}}return c},Rn=function(e){e||(e={});e.filter&&!e.search&&(e.search=e.filter);return{search:e.search||"none",order:e.order||"current",page:e.page||"all"}},On=function(e){for(var t=0,n=e.length;n>t;t++)if(e[t].length>0){e[0]=e[t];e.length=1;e.context=[e.context[t]];return e}e.length=0;return e},_n=function(t,n){var r,i,o,s=[],a=t.aiDisplay,l=t.aiDisplayMaster,u=n.search,c=n.order,p=n.page;if("ssp"==Vt(t))return"removed"===u?[]:gn(0,l.length);if("current"==p)for(r=t._iDisplayStart,i=t.fnDisplayEnd();i>r;r++)s.push(a[r]);else if("current"==c||"applied"==c)s="none"==u?l.slice():"applied"==u?a.slice():e.map(l,function(t){return-1===e.inArray(t,a)?t:null});else if("index"==c||"original"==c)for(r=0,i=t.aoData.length;i>r;r++)if("none"==u)s.push(r);else{o=e.inArray(r,a);(-1===o&&"removed"==u||o>=0&&"applied"==u)&&s.push(r)}return s},Dn=function(t,n,r){return wn(n,function(n){var i=ln(n);if(null!==i&&!r)return[i];var o=_n(t,r);if(null!==i&&-1!==e.inArray(i,o))return[i];if(!n)return o;for(var s=[],a=0,l=o.length;l>a;a++)s.push(t.aoData[o[a]].nTr);return n.nodeName&&-1!==e.inArray(n,s)?[n._DT_RowIndex]:e(s).filter(n).map(function(){return this._DT_RowIndex}).toArray()})};Qt("rows()",function(t,n){if(t===o)t="";else if(e.isPlainObject(t)){n=t;t=""}n=Rn(n);var r=this.iterator("table",function(e){return Dn(e,t,n)});r.selector.rows=t;r.selector.opts=n;return r});Qt("rows().nodes()",function(){return this.iterator("row",function(e,t){return e.aoData[t].nTr||o})});Qt("rows().data()",function(){return this.iterator(!0,"rows",function(e,t){return hn(e.aoData,t,"_aData")})});Jt("rows().cache()","row().cache()",function(e){return this.iterator("row",function(t,n){var r=t.aoData[n];return"search"===e?r._aFilterData:r._aSortData})});Jt("rows().invalidate()","row().invalidate()",function(e){return this.iterator("row",function(t,n){_(t,n,e)})});Jt("rows().indexes()","row().index()",function(){return this.iterator("row",function(e,t){return t})});Jt("rows().remove()","row().remove()",function(){var t=this;return this.iterator("row",function(n,r,i){var o=n.aoData;o.splice(r,1);for(var s=0,a=o.length;a>s;s++)null!==o[s].nTr&&(o[s].nTr._DT_RowIndex=s);e.inArray(r,n.aiDisplay);O(n.aiDisplayMaster,r);O(n.aiDisplay,r);O(t[i],r,!1);qt(n)})});Qt("rows.add()",function(e){var t=this.iterator("table",function(t){var n,r,i,o=[];for(r=0,i=e.length;i>r;r++){n=e[r];o.push(n.nodeName&&"TR"===n.nodeName.toUpperCase()?b(t,n)[0]:x(t,n))}return o}),n=this.rows(-1);n.pop();n.push.apply(n,t.toArray());return n});Qt("row()",function(e,t){return On(this.rows(e,t))});Qt("row().data()",function(e){var t=this.context;if(e===o)return t.length&&this.length?t[0].aoData[this[0]]._aData:o;t[0].aoData[this[0]]._aData=e;_(t[0],this[0],"data");return this});Qt("row().node()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]].nTr||null:null});Qt("row.add()",function(t){t instanceof e&&t.length&&(t=t[0]);var n=this.iterator("table",function(e){return t.nodeName&&"TR"===t.nodeName.toUpperCase()?b(e,t)[0]:x(e,t)});return this.row(n[0])});var Fn=function(t,n,r,i){var o=[],s=function(n,r){if(n.nodeName&&"tr"===n.nodeName.toLowerCase())o.push(n);else{var i=e("<tr><td/></tr>").addClass(r);e("td",i).addClass(r).html(n)[0].colSpan=m(t);o.push(i[0])}};if(e.isArray(r)||r instanceof e)for(var a=0,l=r.length;l>a;a++)s(r[a],i);else s(r,i);n._details&&n._details.remove();n._details=e(o);n._detailsShow&&n._details.insertAfter(n.nTr)},kn=function(e){var t=e.context;if(t.length&&e.length){var n=t[0].aoData[e[0]];if(n._details){n._details.remove();n._detailsShow=o;n._details=o}}},Pn=function(e,t){var n=e.context;if(n.length&&e.length){var r=n[0].aoData[e[0]];if(r._details){r._detailsShow=t;t?r._details.insertAfter(r.nTr):r._details.detach();Mn(n[0])}}},Mn=function(e){var t=new Kt(e),n=".dt.DT_details",r="draw"+n,i="column-visibility"+n,o="destroy"+n,s=e.aoData;t.off(r+" "+i+" "+o);if(fn(s,"_details").length>0){t.on(r,function(n,r){e===r&&t.rows({page:"current"}).eq(0).each(function(e){var t=s[e];t._detailsShow&&t._details.insertAfter(t.nTr)})});t.on(i,function(t,n){if(e===n)for(var r,i=m(n),o=0,a=s.length;a>o;o++){r=s[o];r._details&&r._details.children("td[colspan]").attr("colspan",i)}});t.on(o,function(t,n){if(e===n)for(var r=0,i=s.length;i>r;r++)s[r]._details&&kn(s[r])})}},jn="",Gn=jn+"row().child",Un=Gn+"()";Qt(Un,function(e,t){var n=this.context;if(e===o)return n.length&&this.length?n[0].aoData[this[0]]._details:o;e===!0?this.child.show():e===!1?kn(this):n.length&&this.length&&Fn(n[0],n[0].aoData[this[0]],e,t);return this});Qt([Gn+".show()",Un+".show()"],function(){Pn(this,!0);return this});Qt([Gn+".hide()",Un+".hide()"],function(){Pn(this,!1);return this});Qt([Gn+".remove()",Un+".remove()"],function(){kn(this);return this});Qt(Gn+".isShown()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]]._detailsShow||!1:!1});var Bn=/^(.+):(name|visIdx|visible)$/,qn=function(t,n){var r=t.aoColumns,i=fn(r,"sName"),o=fn(r,"nTh");return wn(n,function(n){var s=ln(n);if(""===n)return gn(r.length);if(null!==s)return[s>=0?s:r.length+s];var a="string"==typeof n?n.match(Bn):"";if(!a)return e(o).filter(n).map(function(){return e.inArray(this,o)}).toArray();switch(a[2]){case"visIdx":case"visible":var l=parseInt(a[1],10);if(0>l){var u=e.map(r,function(e,t){return e.bVisible?t:null});return[u[u.length+l]]}return[h(t,l)];case"name":return e.map(i,function(e,t){return e===a[1]?t:null})}})},Hn=function(t,n,r,i){var s,a,l,u,c=t.aoColumns,p=c[n],d=t.aoData;if(r===o)return p.bVisible;if(p.bVisible!==r){if(r){var h=e.inArray(!0,fn(c,"bVisible"),n+1);for(a=0,l=d.length;l>a;a++){u=d[a].nTr;s=d[a].anCells;u&&u.insertBefore(s[n],s[h]||null)}}else e(fn(t.aoData,"anCells",n)).detach();p.bVisible=r;M(t,t.aoHeader);M(t,t.aoFooter);if(i===o||i){f(t);(t.oScroll.sX||t.oScroll.sY)&&mt(t)}Bt(t,null,"column-visibility",[t,n,r]);Dt(t)}};Qt("columns()",function(t,n){if(t===o)t="";else if(e.isPlainObject(t)){n=t;t=""}n=Rn(n);var r=this.iterator("table",function(e){return qn(e,t,n)});r.selector.cols=t;r.selector.opts=n;return r});Jt("columns().header()","column().header()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTh})});Jt("columns().footer()","column().footer()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTf})});Jt("columns().data()","column().data()",function(){return this.iterator("column-rows",function(e,t,n,r,i){for(var o=[],s=0,a=i.length;a>s;s++)o.push(N(e,i[s],t,""));return o})});Jt("columns().cache()","column().cache()",function(e){return this.iterator("column-rows",function(t,n,r,i,o){return hn(t.aoData,o,"search"===e?"_aFilterData":"_aSortData",n)})});Jt("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(e,t,n,r,i){return hn(e.aoData,i,"anCells",t)})});Jt("columns().visible()","column().visible()",function(e,t){return this.iterator("column",function(n,r){return e===o?n.aoColumns[r].bVisible:Hn(n,r,e,t)})});Jt("columns().indexes()","column().index()",function(e){return this.iterator("column",function(t,n){return"visible"===e?g(t,n):n})});Qt("columns.adjust()",function(){return this.iterator("table",function(e){f(e)})});Qt("column.index()",function(e,t){if(0!==this.context.length){var n=this.context[0];if("fromVisible"===e||"toData"===e)return h(n,t);if("fromData"===e||"toVisible"===e)return g(n,t)}});Qt("column()",function(e,t){return On(this.columns(e,t))});var Vn=function(t,n,r){var i,s,a,l,u,c=t.aoData,p=_n(t,r),d=hn(c,p,"anCells"),f=e([].concat.apply([],d)),h=t.aoColumns.length;return wn(n,function(t){if(null===t||t===o){s=[];for(a=0,l=p.length;l>a;a++){i=p[a];for(u=0;h>u;u++)s.push({row:i,column:u})}return s}return e.isPlainObject(t)?[t]:f.filter(t).map(function(t,n){i=n.parentNode._DT_RowIndex;return{row:i,column:e.inArray(n,c[i].anCells)}}).toArray()})};Qt("cells()",function(t,n,r){if(e.isPlainObject(t))if(typeof t.row!==o){r=n;n=null}else{r=t;t=null}if(e.isPlainObject(n)){r=n;n=null}if(null===n||n===o)return this.iterator("table",function(e){return Vn(e,t,Rn(r))});var i,s,a,l,u,c=this.columns(n,r),p=this.rows(t,r),d=this.iterator("table",function(e,t){i=[];for(s=0,a=p[t].length;a>s;s++)for(l=0,u=c[t].length;u>l;l++)i.push({row:p[t][s],column:c[t][l]});return i});e.extend(d.selector,{cols:n,rows:t,opts:r});return d});Jt("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(e,t,n){return e.aoData[t].anCells[n]})});Qt("cells().data()",function(){return this.iterator("cell",function(e,t,n){return N(e,t,n)})});Jt("cells().cache()","cell().cache()",function(e){e="search"===e?"_aFilterData":"_aSortData";return this.iterator("cell",function(t,n,r){return t.aoData[n][e][r]})});Jt("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(e,t,n){return{row:t,column:n,columnVisible:g(e,n)}})});Qt(["cells().invalidate()","cell().invalidate()"],function(e){var t=this.selector;this.rows(t.rows,t.opts).invalidate(e);return this});Qt("cell()",function(e,t,n){return On(this.cells(e,t,n))});Qt("cell().data()",function(e){var t=this.context,n=this[0];if(e===o)return t.length&&n.length?N(t[0],n[0].row,n[0].column):o;C(t[0],n[0].row,n[0].column,e);_(t[0],n[0].row,"data",n[0].column);return this});Qt("order()",function(t,n){var r=this.context;if(t===o)return 0!==r.length?r[0].aaSorting:o;"number"==typeof t?t=[[t,n]]:e.isArray(t[0])||(t=Array.prototype.slice.call(arguments));return this.iterator("table",function(e){e.aaSorting=t.slice()})});Qt("order.listener()",function(e,t,n){return this.iterator("table",function(r){Rt(r,e,t,n)})});Qt(["columns().order()","column().order()"],function(t){var n=this;return this.iterator("table",function(r,i){var o=[];e.each(n[i],function(e,n){o.push([n,t])});r.aaSorting=o})});Qt("search()",function(t,n,r,i){var s=this.context;return t===o?0!==s.length?s[0].oPreviousSearch.sSearch:o:this.iterator("table",function(o){o.oFeatures.bFilter&&Y(o,e.extend({},o.oPreviousSearch,{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),1)})});Jt("columns().search()","column().search()",function(t,n,r,i){return this.iterator("column",function(s,a){var l=s.aoPreSearchCols;if(t===o)return l[a].sSearch;if(s.oFeatures.bFilter){e.extend(l[a],{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i});Y(s,s.oPreviousSearch,1)}})});Qt("state()",function(){return this.context.length?this.context[0].oSavedState:null});Qt("state.clear()",function(){return this.iterator("table",function(e){e.fnStateSaveCallback.call(e.oInstance,e,{})})});Qt("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});Qt("state.save()",function(){return this.iterator("table",function(e){Dt(e)})});Xt.versionCheck=Xt.fnVersionCheck=function(e){for(var t,n,r=Xt.version.split("."),i=e.split("."),o=0,s=i.length;s>o;o++){t=parseInt(r[o],10)||0;n=parseInt(i[o],10)||0;if(t!==n)return t>n}return!0};Xt.isDataTable=Xt.fnIsDataTable=function(t){var n=e(t).get(0),r=!1;e.each(Xt.settings,function(e,t){(t.nTable===n||t.nScrollHead===n||t.nScrollFoot===n)&&(r=!0)});return r};Xt.tables=Xt.fnTables=function(t){return jQuery.map(Xt.settings,function(n){return!t||t&&e(n.nTable).is(":visible")?n.nTable:void 0})};Xt.camelToHungarian=r;Qt("$()",function(t,n){var r=this.rows(n).nodes(),i=e(r);return e([].concat(i.filter(t).toArray(),i.find(t).toArray()))});e.each(["on","one","off"],function(t,n){Qt(n+"()",function(){var t=Array.prototype.slice.call(arguments);t[0].match(/\.dt\b/)||(t[0]+=".dt");var r=e(this.tables().nodes());r[n].apply(r,t);return this})});Qt("clear()",function(){return this.iterator("table",function(e){R(e)})});Qt("settings()",function(){return new Kt(this.context,this.context)});Qt("data()",function(){return this.iterator("table",function(e){return fn(e.aoData,"_aData")}).flatten()});Qt("destroy()",function(t){t=t||!1;return this.iterator("table",function(r){var i,o=r.nTableWrapper.parentNode,s=r.oClasses,a=r.nTable,l=r.nTBody,u=r.nTHead,c=r.nTFoot,p=e(a),d=e(l),f=e(r.nTableWrapper),h=e.map(r.aoData,function(e){return e.nTr});r.bDestroying=!0;Bt(r,"aoDestroyCallback","destroy",[r]);t||new Kt(r).columns().visible(!0);f.unbind(".DT").find(":not(tbody *)").unbind(".DT");e(n).unbind(".DT-"+r.sInstance);if(a!=u.parentNode){p.children("thead").detach();p.append(u)}if(c&&a!=c.parentNode){p.children("tfoot").detach();p.append(c)}p.detach();f.detach();r.aaSorting=[];r.aaSortingFixed=[];Ot(r);e(h).removeClass(r.asStripeClasses.join(" "));e("th, td",u).removeClass(s.sSortable+" "+s.sSortableAsc+" "+s.sSortableDesc+" "+s.sSortableNone);if(r.bJUI){e("th span."+s.sSortIcon+", td span."+s.sSortIcon,u).detach();e("th, td",u).each(function(){var t=e("div."+s.sSortJUIWrapper,this);e(this).append(t.contents());t.detach()})}!t&&o&&o.insertBefore(a,r.nTableReinsertBefore);d.children().detach();d.append(h);p.css("width",r.sDestroyWidth).removeClass(s.sTable);i=r.asDestroyStripes.length;i&&d.children().each(function(t){e(this).addClass(r.asDestroyStripes[t%i])});var g=e.inArray(r,Xt.settings);-1!==g&&Xt.settings.splice(g,1)})});Xt.version="1.10.2";Xt.settings=[];Xt.models={};Xt.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};Xt.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};Xt.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};Xt.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(e){try{return JSON.parse((-1===e.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+e.sInstance+"_"+location.pathname))}catch(t){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(e,t){try{(-1===e.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+e.sInstance+"_"+location.pathname,JSON.stringify(t))}catch(n){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:e.extend({},Xt.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};t(Xt.defaults);Xt.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};t(Xt.defaults.column);Xt.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:o,oAjaxData:o,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Vt(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Vt(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var e=this._iDisplayLength,t=this._iDisplayStart,n=t+e,r=this.aiDisplay.length,i=this.oFeatures,o=i.bPaginate;return i.bServerSide?o===!1||-1===e?t+r:Math.min(t+e,this._iRecordsDisplay):!o||n>r||-1===e?r:n},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};Xt.ext=Yt={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:Xt.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:Xt.version};e.extend(Yt,{afnFiltering:Yt.search,aTypes:Yt.type.detect,ofnSearch:Yt.type.search,oSort:Yt.type.order,afnSortData:Yt.order,aoFeatures:Yt.feature,oApi:Yt.internal,oStdClasses:Yt.classes,oPagination:Yt.pager});e.extend(Xt.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});(function(){var t="";t="";var n=t+"ui-state-default",r=t+"css_right ui-icon ui-icon-",i=t+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";e.extend(Xt.ext.oJUIClasses,Xt.ext.classes,{sPageButton:"fg-button ui-button "+n,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:n+" sorting_asc",sSortDesc:n+" sorting_desc",sSortable:n+" sorting",sSortableAsc:n+" sorting_asc_disabled",sSortableDesc:n+" sorting_desc_disabled",sSortableNone:n+" sorting_disabled",sSortJUIAsc:r+"triangle-1-n",sSortJUIDesc:r+"triangle-1-s",sSortJUI:r+"carat-2-n-s",sSortJUIAscAllowed:r+"carat-1-n",sSortJUIDescAllowed:r+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+n,sScrollFoot:"dataTables_scrollFoot "+n,sHeaderTH:n,sFooterTH:n,sJUIHeader:i+" ui-corner-tl ui-corner-tr",sJUIFooter:i+" ui-corner-bl ui-corner-br"})})();var Wn=Xt.ext.pager;e.extend(Wn,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(e,t){return["previous",Wt(e,t),"next"]},full_numbers:function(e,t){return["first","previous",Wt(e,t),"next","last"]},_numbers:Wt,numbers_length:7});e.extend(!0,Xt.ext.renderer,{pageButton:{_:function(t,n,r,o,s,a){var l,u,c=t.oClasses,p=t.oLanguage.oPaginate,d=0,f=function(n,i){var o,h,g,m,v=function(e){dt(t,e.data.action,!0)};for(o=0,h=i.length;h>o;o++){m=i[o];if(e.isArray(m)){var E=e("<"+(m.DT_el||"div")+"/>").appendTo(n);f(E,m)}else{l="";u="";switch(m){case"ellipsis":n.append("<span>…</span>");break;case"first":l=p.sFirst;u=m+(s>0?"":" "+c.sPageButtonDisabled);break;case"previous":l=p.sPrevious;u=m+(s>0?"":" "+c.sPageButtonDisabled);break;case"next":l=p.sNext;u=m+(a-1>s?"":" "+c.sPageButtonDisabled);break;case"last":l=p.sLast;u=m+(a-1>s?"":" "+c.sPageButtonDisabled);break;default:l=m+1;u=s===m?c.sPageButtonActive:""}if(l){g=e("<a>",{"class":c.sPageButton+" "+u,"aria-controls":t.sTableId,"data-dt-idx":d,tabindex:t.iTabIndex,id:0===r&&"string"==typeof m?t.sTableId+"_"+m:null}).html(l).appendTo(n);Gt(g,{action:m},v);d++}}}};try{var h=e(i.activeElement).data("dt-idx");f(e(n).empty(),o);null!==h&&e(n).find("[data-dt-idx="+h+"]").focus()}catch(g){}}}});var zn=function(e,t,n,r){if(!e||"-"===e)return-1/0;t&&(e=un(e,t));if(e.replace){n&&(e=e.replace(n,""));r&&(e=e.replace(r,""))}return 1*e};e.extend(Yt.type.order,{"date-pre":function(e){return Date.parse(e)||0},"html-pre":function(e){return an(e)?"":e.replace?e.replace(/<.*?>/g,"").toLowerCase():e+""},"string-pre":function(e){return an(e)?"":"string"==typeof e?e.toLowerCase():e.toString?e.toString():""},"string-asc":function(e,t){return t>e?-1:e>t?1:0},"string-desc":function(e,t){return t>e?1:e>t?-1:0}});zt("");e.extend(Xt.ext.type.detect,[function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n)?"num"+n:null},function(e){if(e&&(!nn.test(e)||!rn.test(e)))return null;var t=Date.parse(e);return null!==t&&!isNaN(t)||an(e)?"date":null},function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n,!0)?"num-fmt"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n)?"html-num"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n,!0)?"html-num-fmt"+n:null},function(e){return an(e)||"string"==typeof e&&-1!==e.indexOf("<")?"html":null}]);e.extend(Xt.ext.type.search,{html:function(e){return an(e)?e:"string"==typeof e?e.replace(en," ").replace(tn,""):""},string:function(e){return an(e)?e:"string"==typeof e?e.replace(en," "):e}});e.extend(!0,Xt.ext.renderer,{header:{_:function(t,n,r,i){e(t.nTable).on("order.dt.DT",function(e,o,s,a){if(t===o){var l=r.idx;n.removeClass(r.sSortingClass+" "+i.sSortAsc+" "+i.sSortDesc).addClass("asc"==a[l]?i.sSortAsc:"desc"==a[l]?i.sSortDesc:r.sSortingClass)}})},jqueryui:function(t,n,r,i){var o=r.idx;e("<div/>").addClass(i.sSortJUIWrapper).append(n.contents()).append(e("<span/>").addClass(i.sSortIcon+" "+r.sSortingClassJUI)).appendTo(n);e(t.nTable).on("order.dt.DT",function(e,s,a,l){if(t===s){n.removeClass(i.sSortAsc+" "+i.sSortDesc).addClass("asc"==l[o]?i.sSortAsc:"desc"==l[o]?i.sSortDesc:r.sSortingClass);n.find("span."+i.sSortIcon).removeClass(i.sSortJUIAsc+" "+i.sSortJUIDesc+" "+i.sSortJUI+" "+i.sSortJUIAscAllowed+" "+i.sSortJUIDescAllowed).addClass("asc"==l[o]?i.sSortJUIAsc:"desc"==l[o]?i.sSortJUIDesc:r.sSortingClassJUI)}})}}});Xt.render={number:function(e,t,n,r){return{display:function(i){var o=0>i?"-":"";i=Math.abs(parseFloat(i));var s=parseInt(i,10),a=n?t+(i-s).toFixed(n).substring(2):"";return o+(r||"")+s.toString().replace(/\B(?=(\d{3})+(?!\d))/g,e)+a}}}};e.extend(Xt.ext.internal,{_fnExternApiFunc:$t,_fnBuildAjax:H,_fnAjaxUpdate:V,_fnAjaxParameters:W,_fnAjaxUpdateDraw:z,_fnAjaxDataSrc:$,_fnAddColumn:p,_fnColumnOptions:d,_fnAdjustColumnSizing:f,_fnVisibleToColumnIndex:h,_fnColumnIndexToVisible:g,_fnVisbleColumns:m,_fnGetColumns:v,_fnColumnTypes:E,_fnApplyColumnDefs:y,_fnHungarianMap:t,_fnCamelToHungarian:r,_fnLanguageCompat:s,_fnBrowserDetect:u,_fnAddData:x,_fnAddTr:b,_fnNodeToDataIndex:T,_fnNodeToColumnIndex:S,_fnGetCellData:N,_fnSetCellData:C,_fnSplitObjNotation:L,_fnGetObjectDataFn:A,_fnSetObjectDataFn:I,_fnGetDataMaster:w,_fnClearTable:R,_fnDeleteIndex:O,_fnInvalidateRow:_,_fnGetRowElements:D,_fnCreateTr:F,_fnBuildHead:P,_fnDrawHead:M,_fnDraw:j,_fnReDraw:G,_fnAddOptionsHtml:U,_fnDetectHeader:B,_fnGetUniqueThs:q,_fnFeatureHtmlFilter:X,_fnFilterComplete:Y,_fnFilterCustom:K,_fnFilterColumn:Q,_fnFilter:J,_fnFilterCreateSearch:Z,_fnEscapeRegex:et,_fnFilterData:tt,_fnFeatureHtmlInfo:it,_fnUpdateInfo:ot,_fnInfoMacros:st,_fnInitialise:at,_fnInitComplete:lt,_fnLengthChange:ut,_fnFeatureHtmlLength:ct,_fnFeatureHtmlPaginate:pt,_fnPageChange:dt,_fnFeatureHtmlProcessing:ft,_fnProcessingDisplay:ht,_fnFeatureHtmlTable:gt,_fnScrollDraw:mt,_fnApplyToChildren:vt,_fnCalculateColumnWidths:Et,_fnThrottle:yt,_fnConvertToWidth:xt,_fnScrollingWidthAdjust:bt,_fnGetWidestNode:Tt,_fnGetMaxLenString:St,_fnStringToCss:Nt,_fnScrollBarWidth:Ct,_fnSortFlatten:Lt,_fnSort:At,_fnSortAria:It,_fnSortListener:wt,_fnSortAttachListener:Rt,_fnSortingClasses:Ot,_fnSortData:_t,_fnSaveState:Dt,_fnLoadState:Ft,_fnSettingsFromNode:kt,_fnLog:Pt,_fnMap:Mt,_fnBindAction:Gt,_fnCallbackReg:Ut,_fnCallbackFire:Bt,_fnLengthOverflow:qt,_fnRenderer:Ht,_fnDataSource:Vt,_fnRowAttributes:k,_fnCalculateEnd:function(){}});e.fn.dataTable=Xt;e.fn.dataTableSettings=Xt.settings;e.fn.dataTableExt=Xt.ext;e.fn.DataTable=function(t){return e(this).dataTable(t).api()};e.each(Xt,function(t,n){e.fn.DataTable[t]=n});return e.fn.dataTable})})(window,document)},{jquery:63}],48:[function(e){var t,n=e("jquery"),r=n(document),i=n("head"),o=null,s=[],a=0,l="id",u="px",c="JColResizer",p=parseInt,d=Math,f=navigator.userAgent.indexOf("Trident/4.0")>0;try{t=sessionStorage}catch(h){}i.append("<style type='text/css'> .JColResizer{table-layout:fixed;} .JColResizer td, .JColResizer th{overflow:hidden;padding-left:0!important; padding-right:0!important;} .JCLRgrips{ height:0px; position:relative;} .JCLRgrip{margin-left:-5px; position:absolute; z-index:5; } .JCLRgrip .JColResizer{position:absolute;background-color:red;filter:alpha(opacity=1);opacity:0;width:10px;height:100%;top:0px} .JCLRLastGrip{position:absolute; width:1px; } .JCLRgripDrag{ border-left:1px dotted black; }</style>");var g=function(e,t){var r=n(e);if(t.disable)return m(r);var i=r.id=r.attr(l)||c+a++;r.p=t.postbackSafe;if(r.is("table")&&!s[i]){r.addClass(c).attr(l,i).before('<div class="JCLRgrips"/>');r.opt=t;r.g=[];r.c=[];r.w=r.width();r.gc=r.prev();t.marginLeft&&r.gc.css("marginLeft",t.marginLeft);t.marginRight&&r.gc.css("marginRight",t.marginRight);r.cs=p(f?e.cellSpacing||e.currentStyle.borderSpacing:r.css("border-spacing"))||2;r.b=p(f?e.border||e.currentStyle.borderLeftWidth:r.css("border-left-width"))||1;s[i]=r;v(r)}},m=function(e){var t=e.attr(l),e=s[t];if(e&&e.is("table")){e.removeClass(c).gc.remove();delete s[t]}},v=function(e){var r=e.find(">thead>tr>th,>thead>tr>td");r.length||(r=e.find(">tbody>tr:first>th,>tr:first>th,>tbody>tr:first>td, >tr:first>td"));e.cg=e.find("col");e.ln=r.length;e.p&&t&&t[e.id]&&E(e,r);r.each(function(t){var r=n(this),i=n(e.gc.append('<div class="JCLRgrip"></div>')[0].lastChild);i.t=e;i.i=t;i.c=r;r.w=r.width();e.g.push(i);e.c.push(r);r.width(r.w).removeAttr("width");t<e.ln-1?i.bind("touchstart mousedown",S).append(e.opt.gripInnerHtml).append('<div class="'+c+'" style="cursor:'+e.opt.hoverCursor+'"></div>'):i.addClass("JCLRLastGrip").removeClass("JCLRgrip");i.data(c,{i:t,t:e.attr(l)})});e.cg.removeAttr("width");y(e);e.find("td, th").not(r).not("table th, table td").each(function(){n(this).removeAttr("width")})},E=function(e,n){var r,i=0,o=0,s=[];if(n){e.cg.removeAttr("width");if(e.opt.flush){t[e.id]="";return}r=t[e.id].split(";");for(;o<e.ln;o++){s.push(100*r[o]/r[e.ln]+"%");n.eq(o).css("width",s[o])}for(o=0;o<e.ln;o++)e.cg.eq(o).css("width",s[o])}else{t[e.id]="";for(;o<e.c.length;o++){r=e.c[o].width();t[e.id]+=r+";";i+=r}t[e.id]+=i}},y=function(e){e.gc.width(e.w);for(var t=0;t<e.ln;t++){var n=e.c[t];e.g[t].css({left:n.offset().left-e.offset().left+n.outerWidth(!1)+e.cs/2+u,height:e.opt.headerOnly?e.c[0].outerHeight(!1):e.outerHeight(!1)})}},x=function(e,t,n){var r=o.x-o.l,i=e.c[t],s=e.c[t+1],a=i.w+r,l=s.w-r;i.width(a+u);s.width(l+u);e.cg.eq(t).width(a+u);e.cg.eq(t+1).width(l+u);if(n){i.w=a;s.w=l}},b=function(e){if(o){var t=o.t;if(e.originalEvent.touches)var n=e.originalEvent.touches[0].pageX-o.ox+o.l;else var n=e.pageX-o.ox+o.l;var r=t.opt.minWidth,i=o.i,s=1.5*t.cs+r+t.b,a=i==t.ln-1?t.w-s:t.g[i+1].position().left-t.cs-r,l=i?t.g[i-1].position().left+t.cs+r:s;n=d.max(l,d.min(a,n));o.x=n;o.css("left",n+u);if(t.opt.liveDrag){x(t,i);y(t);var c=t.opt.onDrag;if(c){e.currentTarget=t[0];c(e)}}return!1}},T=function(e){r.unbind("touchend."+c+" mouseup."+c).unbind("touchmove."+c+" mousemove."+c);n("head :last-child").remove();if(o){o.removeClass(o.t.opt.draggingClass);var i=o.t,s=i.opt.onResize;if(o.x){x(i,o.i,!0);y(i);if(s){e.currentTarget=i[0];s(e)}}i.p&&t&&E(i);o=null}},S=function(e){var t=n(this).data(c),a=s[t.t],l=a.g[t.i];l.ox=e.originalEvent.touches?e.originalEvent.touches[0].pageX:e.pageX;l.l=l.position().left;r.bind("touchmove."+c+" mousemove."+c,b).bind("touchend."+c+" mouseup."+c,T);i.append("<style type='text/css'>*{cursor:"+a.opt.dragCursor+"!important}</style>");l.addClass(a.opt.draggingClass);o=l;if(a.c[t.i].l)for(var u,p=0;p<a.ln;p++){u=a.c[p];u.l=!1;u.w=u.width()}return!1},N=function(){for(t in s){var e,t=s[t],n=0;t.removeClass(c);if(t.w!=t.width()){t.w=t.width();for(e=0;e<t.ln;e++)n+=t.c[e].w;for(e=0;e<t.ln;e++)t.c[e].css("width",d.round(1e3*t.c[e].w/n)/10+"%").l=!0}y(t.addClass(c))}};n(window).bind("resize."+c,N);n.fn.extend({colResizable:function(e){var t={draggingClass:"JCLRgripDrag",gripInnerHtml:"",liveDrag:!1,minWidth:15,headerOnly:!1,hoverCursor:"e-resize",dragCursor:"e-resize",postbackSafe:!1,flush:!1,marginLeft:null,marginRight:null,disable:!1,onDrag:null,onResize:null},e=n.extend(t,e);return this.each(function(){g(this,e)})}})},{jquery:63}],49:[function(){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")
};(function(e){"use strict";e.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var n=parseInt(e);return isNaN(n)?null:n}},parsers:{parse:function(e,t){function n(){l=0;u="";if(t.start&&t.state.rowNum<t.start){a=[];t.state.rowNum++;t.state.colNum=1}else{if(void 0===t.onParseEntry)s.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&s.push(e)}a=[];t.end&&t.state.rowNum>=t.end&&(c=!0);t.state.rowNum++;t.state.colNum=1}}function r(){if(void 0===t.onParseValue)a.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&a.push(e)}u="";l=0;t.state.colNum++}var i=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var s=[],a=[],l=0,u="",c=!1,p=RegExp.escape(i),d=RegExp.escape(o),f=/(D|S|\n|\r|[^DS\r\n]+)/,h=f.source;h=h.replace(/S/g,p);h=h.replace(/D/g,d);f=RegExp(h,"gm");e.replace(f,function(e){if(!c)switch(l){case 0:if(e===i){u+="";r();break}if(e===o){l=1;break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;u+=e;l=3;break;case 1:if(e===o){l=2;break}u+=e;l=1;break;case 2:if(e===o){u+=e;l=1;break}if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});if(0!==a.length){r();n()}return s},splitLines:function(e,t){function n(){s=0;if(t.start&&t.state.rowNum<t.start){a="";t.state.rowNum++}else{if(void 0===t.onParseEntry)o.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&o.push(e)}a="";t.end&&t.state.rowNum>=t.end&&(l=!0);t.state.rowNum++}}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],s=0,a="",l=!1,u=RegExp.escape(r),c=RegExp.escape(i),p=/(D|S|\n|\r|[^DS\r\n]+)/,d=p.source;d=d.replace(/S/g,u);d=d.replace(/D/g,c);p=RegExp(d,"gm");e.replace(p,function(e){if(!l)switch(s){case 0:if(e===r){a+=e;s=0;break}if(e===i){a+=e;s=1;break}if("\n"===e){n();break}if(/^\r$/.test(e))break;a+=e;s=3;break;case 1:if(e===i){a+=e;s=2;break}a+=e;s=1;break;case 2:var o=a.substr(a.length-1);if(e===i&&o===i){a+=e;s=1;break}if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}});""!==a&&n();return o},parseEntry:function(e,t){function n(){if(void 0===t.onParseValue)o.push(a);else{var e=t.onParseValue(a,t.state);e!==!1&&o.push(e)}a="";s=0;t.state.colNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var o=[],s=0,a="";if(!t.match){var l=RegExp.escape(r),u=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,p=c.source;p=p.replace(/S/g,l);p=p.replace(/D/g,u);t.match=RegExp(p,"gm")}e.replace(t.match,function(e){switch(s){case 0:if(e===r){a+="";n();break}if(e===i){s=1;break}if("\n"===e||"\r"===e)break;a+=e;s=3;break;case 1:if(e===i){s=2;break}a+=e;s=1;break;case 2:if(e===i){a+=e;s=1;break}if(e===r){n();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===r){n();break}if("\n"===e||"\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});n();return o}},toArray:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:e.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},s=e.csv.parsers.parseEntry(t,n);if(!i.callback)return s;i.callback("",s);return void 0},toArrays:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:e.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};o=e.csv.parsers.parse(t,n);if(!i.callback)return o;i.callback("",o);return void 0},toObjects:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:e.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;i.headers="headers"in n?n.headers:e.csv.defaults.headers;n.start="start"in n?n.start:1;i.headers&&n.start++;n.end&&i.headers&&n.end++;var o=[],s=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},a={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=e.csv.parsers.splitLines(t,a),u=e.csv.toArray(l[0],n),o=e.csv.parsers.splitLines(t,n);n.state.colNum=1;n.state.rowNum=u?2:1;for(var c=0,p=o.length;p>c;c++){var d=e.csv.toArray(o[c],n),f={};for(var h in u)f[u[h]]=d[h];s.push(f);n.state.rowNum++}if(!i.callback)return s;i.callback("",s);return void 0},fromArrays:function(t,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:e.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;o.escaper="escaper"in n?n.escaper:e.csv.defaults.escaper;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in t)s.push(t[i]);if(!o.callback)return s;o.callback("",s);return void 0},fromObjects2CSV:function(t,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:e.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in t)s.push(arrays[i]);if(!o.callback)return s;o.callback("",s);return void 0}};e.csvEntry2Array=e.csv.toArray;e.csv2Array=e.csv.toArrays;e.csv2Dictionary=e.csv.toObjects})(jQuery)},{}],50:[function(e,t){t.exports=e(17)},{"../../lib/codemirror":55,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/edit/matchbrackets.js":17}],51:[function(e,t){t.exports=e(18)},{"../../lib/codemirror":55,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/brace-fold.js":18}],52:[function(e,t){t.exports=e(19)},{"../../lib/codemirror":55,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldcode.js":19}],53:[function(e,t){t.exports=e(20)},{"../../lib/codemirror":55,"./foldcode":52,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldgutter.js":20}],54:[function(e,t){t.exports=e(21)},{"../../lib/codemirror":55,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/xml-fold.js":21}],55:[function(e,t){t.exports=e(25)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/lib/codemirror.js":25}],56:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("javascript",function(t,n){function r(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}function i(e,t,n){gt=e;mt=n;return t}function o(e,t){var n=e.next();if('"'==n||"'"==n){t.tokenize=s(n);return t.tokenize(e,t)}if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i)){e.eatWhile(/[\da-f]/i);return i("number","number")}if(/\d/.test(n)){e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return i("number","number")}if("/"==n){if(e.eat("*")){t.tokenize=a;return a(e,t)}if(e.eat("/")){e.skipToEnd();return i("comment","comment")}if("operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)){r(e);e.eatWhile(/[gimy]/);return i("regexp","string-2")}e.eatWhile(Nt);return i("operator","operator",e.current())}if("`"==n){t.tokenize=l;return l(e,t)}if("#"==n){e.skipToEnd();return i("error","error")}if(Nt.test(n)){e.eatWhile(Nt);return i("operator","operator",e.current())}if(Tt.test(n)){e.eatWhile(Tt);var o=e.current(),u=St.propertyIsEnumerable(o)&&St[o];return u&&"."!=t.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function s(e){return function(t,n){var r,s=!1;if(yt&&"@"==t.peek()&&t.match(Ct)){n.tokenize=o;return i("jsonld-keyword","meta")}for(;null!=(r=t.next())&&(r!=e||s);)s=!s&&"\\"==r;s||(n.tokenize=o);return i("string","string")}}function a(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var s=e.string.charAt(o),a=Lt.indexOf(s);if(a>=0&&3>a){if(!r){++o;break}if(0==--r)break}else if(a>=3&&6>a)++r;else if(Tt.test(s))i=!0;else{if(/["'\/]/.test(s))return;if(i&&!r){++o;break}}}i&&!r&&(t.fatArrowAt=o)}}function c(e,t,n,r,i,o){this.indented=e;this.column=t;this.type=n;this.prev=i;this.info=o;null!=r&&(this.align=r)}function p(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function d(e,t,n,r,i){var o=e.cc;It.state=e;It.stream=i;It.marked=null,It.cc=o;It.style=t;e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);for(;;){var s=o.length?o.pop():xt?T:b;if(s(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return It.marked?It.marked:"variable"==n&&p(e,r)?"variable-2":t}}}function f(){for(var e=arguments.length-1;e>=0;e--)It.cc.push(arguments[e])}function h(){f.apply(null,arguments);return!0}function g(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=It.state;if(r.context){It.marked="def";if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function m(){It.state.context={prev:It.state.context,vars:It.state.localVars};It.state.localVars=wt}function v(){It.state.localVars=It.state.context.vars;It.state.context=It.state.context.prev}function E(e,t){var n=function(){var n=It.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new c(r,It.stream.column(),e,null,n.lexical,t)};n.lex=!0;return n}function y(){var e=It.state;if(e.lexical.prev){")"==e.lexical.type&&(e.indented=e.lexical.indented);e.lexical=e.lexical.prev}}function x(e){function t(n){return n==e?h():";"==e?f():h(t)}return t}function b(e,t){if("var"==e)return h(E("vardef",t.length),H,x(";"),y);if("keyword a"==e)return h(E("form"),T,b,y);if("keyword b"==e)return h(E("form"),b,y);if("{"==e)return h(E("}"),U,y);if(";"==e)return h();if("if"==e){"else"==It.state.lexical.info&&It.state.cc[It.state.cc.length-1]==y&&It.state.cc.pop()();return h(E("form"),T,b,y,X)}return"function"==e?h(et):"for"==e?h(E("form"),Y,b,y):"variable"==e?h(E("stat"),D):"switch"==e?h(E("form"),T,E("}","switch"),x("{"),U,y,y):"case"==e?h(T,x(":")):"default"==e?h(x(":")):"catch"==e?h(E("form"),m,x("("),tt,x(")"),b,y,v):"module"==e?h(E("form"),m,st,v,y):"class"==e?h(E("form"),nt,y):"export"==e?h(E("form"),at,y):"import"==e?h(E("form"),lt,y):f(E("stat"),T,x(";"),y)}function T(e){return N(e,!1)}function S(e){return N(e,!0)}function N(e,t){if(It.state.fatArrowAt==It.stream.start){var n=t?_:O;if("("==e)return h(m,E(")"),j(V,")"),y,x("=>"),n,v);if("variable"==e)return f(m,V,x("=>"),n,v)}var r=t?I:A;return At.hasOwnProperty(e)?h(r):"function"==e?h(et,r):"keyword c"==e?h(t?L:C):"("==e?h(E(")"),C,ft,x(")"),y,r):"operator"==e||"spread"==e?h(t?S:T):"["==e?h(E("]"),pt,y,r):"{"==e?G(k,"}",null,r):"quasi"==e?f(w,r):h()}function C(e){return e.match(/[;\}\)\],]/)?f():f(T)}function L(e){return e.match(/[;\}\)\],]/)?f():f(S)}function A(e,t){return","==e?h(T):I(e,t,!1)}function I(e,t,n){var r=0==n?A:I,i=0==n?T:S;return"=>"==e?h(m,n?_:O,v):"operator"==e?/\+\+|--/.test(t)?h(r):"?"==t?h(T,x(":"),i):h(i):"quasi"==e?f(w,r):";"!=e?"("==e?G(S,")","call",r):"."==e?h(F,r):"["==e?h(E("]"),C,x("]"),y,r):void 0:void 0}function w(e,t){return"quasi"!=e?f():"${"!=t.slice(t.length-2)?h(w):h(T,R)}function R(e){if("}"==e){It.marked="string-2";It.state.tokenize=l;return h(w)}}function O(e){u(It.stream,It.state);return f("{"==e?b:T)}function _(e){u(It.stream,It.state);return f("{"==e?b:S)}function D(e){return":"==e?h(y,b):f(A,x(";"),y)}function F(e){if("variable"==e){It.marked="property";return h()}}function k(e,t){if("variable"==e||"keyword"==It.style){It.marked="property";return h("get"==t||"set"==t?P:M)}if("number"==e||"string"==e){It.marked=yt?"property":It.style+" property";return h(M)}return"jsonld-keyword"==e?h(M):"["==e?h(T,x("]"),M):void 0}function P(e){if("variable"!=e)return f(M);It.marked="property";return h(et)}function M(e){return":"==e?h(S):"("==e?f(et):void 0}function j(e,t){function n(r){if(","==r){var i=It.state.lexical;"call"==i.info&&(i.pos=(i.pos||0)+1);return h(e,n)}return r==t?h():h(x(t))}return function(r){return r==t?h():f(e,n)}}function G(e,t,n){for(var r=3;r<arguments.length;r++)It.cc.push(arguments[r]);return h(E(t,n),j(e,t),y)}function U(e){return"}"==e?h():f(b,U)}function B(e){return bt&&":"==e?h(q):void 0}function q(e){if("variable"==e){It.marked="variable-3";return h()}}function H(){return f(V,B,z,$)}function V(e,t){if("variable"==e){g(t);return h()}return"["==e?G(V,"]"):"{"==e?G(W,"}"):void 0}function W(e,t){if("variable"==e&&!It.stream.match(/^\s*:/,!1)){g(t);return h(z)}"variable"==e&&(It.marked="property");return h(x(":"),V,z)}function z(e,t){return"="==t?h(S):void 0}function $(e){return","==e?h(H):void 0}function X(e,t){return"keyword b"==e&&"else"==t?h(E("form","else"),b,y):void 0}function Y(e){return"("==e?h(E(")"),K,x(")"),y):void 0}function K(e){return"var"==e?h(H,x(";"),J):";"==e?h(J):"variable"==e?h(Q):f(T,x(";"),J)}function Q(e,t){if("in"==t||"of"==t){It.marked="keyword";return h(T)}return h(A,J)}function J(e,t){if(";"==e)return h(Z);if("in"==t||"of"==t){It.marked="keyword";return h(T)}return f(T,x(";"),Z)}function Z(e){")"!=e&&h(T)}function et(e,t){if("*"==t){It.marked="keyword";return h(et)}if("variable"==e){g(t);return h(et)}return"("==e?h(m,E(")"),j(tt,")"),y,b,v):void 0}function tt(e){return"spread"==e?h(tt):f(V,B)}function nt(e,t){if("variable"==e){g(t);return h(rt)}}function rt(e,t){return"extends"==t?h(T,rt):"{"==e?h(E("}"),it,y):void 0}function it(e,t){if("variable"==e||"keyword"==It.style){It.marked="property";return"get"==t||"set"==t?h(ot,et,it):h(et,it)}if("*"==t){It.marked="keyword";return h(it)}return";"==e?h(it):"}"==e?h():void 0}function ot(e){if("variable"!=e)return f();It.marked="property";return h()}function st(e,t){if("string"==e)return h(b);if("variable"==e){g(t);return h(ct)}}function at(e,t){if("*"==t){It.marked="keyword";return h(ct,x(";"))}if("default"==t){It.marked="keyword";return h(T,x(";"))}return f(b)}function lt(e){return"string"==e?h():f(ut,ct)}function ut(e,t){if("{"==e)return G(ut,"}");"variable"==e&&g(t);return h()}function ct(e,t){if("from"==t){It.marked="keyword";return h(T)}}function pt(e){return"]"==e?h():f(S,dt)}function dt(e){return"for"==e?f(ft,x("]")):","==e?h(j(L,"]")):f(j(S,"]"))}function ft(e){return"for"==e?h(Y,ft):"if"==e?h(T,ft):void 0}function ht(e,t){return"operator"==e.lastType||","==e.lastType||Nt.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}var gt,mt,vt=t.indentUnit,Et=n.statementIndent,yt=n.jsonld,xt=n.json||yt,bt=n.typescript,Tt=n.wordCharacters||/[\w$\xa1-\uffff]/,St=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("operator"),o={type:"atom",style:"atom"},s={"if":e("if"),"while":t,"with":t,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":r,"export":e("export"),"import":e("import"),"extends":r};if(bt){var a={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:a,number:a,bool:a,any:a};for(var u in l)s[u]=l[u]}return s}(),Nt=/[+\-*&%=<>!?|~^]/,Ct=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Lt="([{}])",At={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},It={state:null,column:null,marked:null,cc:null},wt={name:"this",next:{name:"arguments"}};y.lex=!0;return{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new c((e||0)-vt,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars);return t},token:function(e,t){if(e.sol()){t.lexical.hasOwnProperty("align")||(t.lexical.align=!1);t.indented=e.indentation();u(e,t)}if(t.tokenize!=a&&e.eatSpace())return null;var n=t.tokenize(e,t);if("comment"==gt)return n;t.lastType="operator"!=gt||"++"!=mt&&"--"!=mt?gt:"incdec";return d(t,n,gt,mt,e)},indent:function(t,r){if(t.tokenize==a)return e.Pass;if(t.tokenize!=o)return 0;var i=r&&r.charAt(0),s=t.lexical;if(!/^\s*else\b/.test(r))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==y)s=s.prev;else if(u!=X)break}"stat"==s.type&&"}"==i&&(s=s.prev);Et&&")"==s.type&&"stat"==s.prev.type&&(s=s.prev);var c=s.type,p=i==c;return"vardef"==c?s.indented+("operator"==t.lastType||","==t.lastType?s.info+1:0):"form"==c&&"{"==i?s.indented:"form"==c?s.indented+vt:"stat"==c?s.indented+(ht(t,r)?Et||vt:0):"switch"!=s.info||p||0==n.doubleIndentSwitch?s.align?s.column+(p?0:1):s.indented+(p?0:vt):s.indented+(/^(?:case|default)\b/.test(r)?vt:2*vt)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:xt?null:"/*",blockCommentEnd:xt?null:"*/",lineComment:xt?null:"//",fold:"brace",helperType:xt?"json":"javascript",jsonldMode:yt,jsonMode:xt}});e.registerHelper("wordChars","javascript",/[\w$]/);e.defineMIME("text/javascript","javascript");e.defineMIME("text/ecmascript","javascript");e.defineMIME("application/javascript","javascript");e.defineMIME("application/x-javascript","javascript");e.defineMIME("application/ecmascript","javascript");e.defineMIME("application/json",{name:"javascript",json:!0});e.defineMIME("application/x-json",{name:"javascript",json:!0});e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});e.defineMIME("text/typescript",{name:"javascript",typescript:!0});e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{"../../lib/codemirror":55}],57:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("xml",function(t,n){function r(e,t){function n(n){t.tokenize=n;return n(e,t)}var r=e.next();if("<"==r){if(e.eat("!")){if(e.eat("["))return e.match("CDATA[")?n(s("atom","]]>")):null;if(e.match("--"))return n(s("comment","-->"));if(e.match("DOCTYPE",!0,!0)){e.eatWhile(/[\w\._\-]/);return n(a(1))}return null}if(e.eat("?")){e.eatWhile(/[\w\._\-]/);t.tokenize=s("meta","?>");return"meta"}S=e.eat("/")?"closeTag":"openTag";t.tokenize=i;return"tag bracket"}if("&"==r){var o;o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";");return o?"atom":"error"}e.eatWhile(/[^&<]/);return null}function i(e,t){var n=e.next();if(">"==n||"/"==n&&e.eat(">")){t.tokenize=r;S=">"==n?"endTag":"selfcloseTag";return"tag bracket"}if("="==n){S="equals";return null}if("<"==n){t.tokenize=r;t.state=p;t.tagName=t.tagStart=null;var i=t.tokenize(e,t);return i?i+" tag error":"tag error"}if(/[\'\"]/.test(n)){t.tokenize=o(n);t.stringStartCol=e.column();return t.tokenize(e,t)}e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word"}function o(e){var t=function(t,n){for(;!t.eol();)if(t.next()==e){n.tokenize=i;break}return"string"};t.isInAttribute=!0;return t}function s(e,t){return function(n,i){for(;!n.eol();){if(n.match(t)){i.tokenize=r;break}n.next()}return e}}function a(e){return function(t,n){for(var i;null!=(i=t.next());){if("<"==i){n.tokenize=a(e+1);return n.tokenize(t,n)}if(">"==i){if(1==e){n.tokenize=r;break}n.tokenize=a(e-1);return n.tokenize(t,n)}}return"meta"}}function l(e,t,n){this.prev=e.context;this.tagName=t;this.indent=e.indented;this.startOfLine=n;(C.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function c(e,t){for(var n;;){if(!e.context)return;n=e.context.tagName;if(!C.contextGrabbers.hasOwnProperty(n)||!C.contextGrabbers[n].hasOwnProperty(t))return;u(e)}}function p(e,t,n){if("openTag"==e){n.tagStart=t.column();return d}return"closeTag"==e?f:p}function d(e,t,n){if("word"==e){n.tagName=t.current();N="tag";return m}N="error";return d}function f(e,t,n){if("word"==e){var r=t.current();n.context&&n.context.tagName!=r&&C.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n);if(n.context&&n.context.tagName==r){N="tag";return h}N="tag error";return g}N="error";return g}function h(e,t,n){if("endTag"!=e){N="error";return h}u(n);return p}function g(e,t,n){N="error";return h(e,t,n)}function m(e,t,n){if("word"==e){N="attribute";return v}if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;n.tagName=n.tagStart=null;if("selfcloseTag"==e||C.autoSelfClosers.hasOwnProperty(r))c(n,r);else{c(n,r);n.context=new l(n,r,i==n.indented)}return p}N="error";return m}function v(e,t,n){if("equals"==e)return E;C.allowMissing||(N="error");return m(e,t,n)}function E(e,t,n){if("string"==e)return y;if("word"==e&&C.allowUnquoted){N="string";return m}N="error";return m(e,t,n)}function y(e,t,n){return"string"==e?y:m(e,t,n)}var x=t.indentUnit,b=n.multilineTagIndentFactor||1,T=n.multilineTagIndentPastTag;null==T&&(T=!0);var S,N,C=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},L=n.alignCDATA;return{startState:function(){return{tokenize:r,state:p,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){!t.tagName&&e.sol()&&(t.indented=e.indentation());if(e.eatSpace())return null;S=null;var n=t.tokenize(e,t);if((n||S)&&"comment"!=n){N=null;t.state=t.state(S||n,e,t);N&&(n="error"==N?n+" error":N)}return n},indent:function(t,n,o){var s=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+x;if(s&&s.noIndent)return e.Pass;if(t.tokenize!=i&&t.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return T?t.tagStart+t.tagName.length+2:t.tagStart+x*b;if(L&&/<!\[CDATA\[/.test(n))return 0;var a=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(a&&a[1])for(;s;){if(s.tagName==a[2]){s=s.prev;break}if(!C.implicitlyClosed.hasOwnProperty(s.tagName))break;s=s.prev}else if(a)for(;s;){var l=C.contextGrabbers[s.tagName];if(!l||!l.hasOwnProperty(a[2]))break;s=s.prev}for(;s&&!s.startOfLine;)s=s.prev;return s?s.indent+x:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}});e.defineMIME("text/xml","xml");e.defineMIME("application/xml","xml");e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{"../../lib/codemirror":55}],58:[function(t,n){!function(){function t(e,t){return t>e?-1:e>t?1:e>=t?0:0/0}function r(e){return null===e?0/0:+e}function i(e){return!isNaN(e)}function o(e){return{left:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)<0?r=o+1:i=o}return r},right:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)>0?i=o:r=o+1}return r}}}function s(e){return e.length}function a(e){for(var t=1;e*t%1;)t*=10;return t}function l(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function u(){this._=Object.create(null)}function c(e){return(e+="")===ya||e[0]===xa?xa+e:e}function p(e){return(e+="")[0]===xa?e.slice(1):e}function d(e){return c(e)in this._}function f(e){return(e=c(e))in this._&&delete this._[e]}function h(){var e=[];for(var t in this._)e.push(p(t));return e}function g(){var e=0;for(var t in this._)++e;return e}function m(){for(var e in this._)return!1;return!0}function v(){this._=Object.create(null)}function E(e,t,n){return function(){var r=n.apply(t,arguments);return r===t?e:r}}function y(e,t){if(t in e)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var n=0,r=ba.length;r>n;++n){var i=ba[n]+t;if(i in e)return i}}function x(){}function b(){}function T(e){function t(){for(var t,r=n,i=-1,o=r.length;++i<o;)(t=r[i].on)&&t.apply(this,arguments);return e}var n=[],r=new u;t.on=function(t,i){var o,s=r.get(t);if(arguments.length<2)return s&&s.on;if(s){s.on=null;n=n.slice(0,o=n.indexOf(s)).concat(n.slice(o+1));r.remove(t)}i&&n.push(r.set(t,{on:i}));return e};return t}function S(){ia.event.preventDefault()}function N(){for(var e,t=ia.event;e=t.sourceEvent;)t=e;return t}function C(e){for(var t=new b,n=0,r=arguments.length;++n<r;)t[arguments[n]]=T(t);t.of=function(n,r){return function(i){try{var o=i.sourceEvent=ia.event;i.target=e;ia.event=i;t[i.type].apply(n,r)}finally{ia.event=o}}};return t}function L(e){Sa(e,Ia);return e}function A(e){return"function"==typeof e?e:function(){return Na(e,this)}}function I(e){return"function"==typeof e?e:function(){return Ca(e,this)}}function w(e,t){function n(){this.removeAttribute(e)}function r(){this.removeAttributeNS(e.space,e.local)}function i(){this.setAttribute(e,t)}function o(){this.setAttributeNS(e.space,e.local,t)}function s(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}function a(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}e=ia.ns.qualify(e);return null==t?e.local?r:n:"function"==typeof t?e.local?a:s:e.local?o:i}function R(e){return e.trim().replace(/\s+/g," ")}function O(e){return new RegExp("(?:^|\\s+)"+ia.requote(e)+"(?:\\s+|$)","g")}function _(e){return(e+"").trim().split(/^|\s+/)}function D(e,t){function n(){for(var n=-1;++n<i;)e[n](this,t)}function r(){for(var n=-1,r=t.apply(this,arguments);++n<i;)e[n](this,r)}e=_(e).map(F);var i=e.length;return"function"==typeof t?r:n}function F(e){var t=O(e);return function(n,r){if(i=n.classList)return r?i.add(e):i.remove(e);var i=n.getAttribute("class")||"";if(r){t.lastIndex=0;t.test(i)||n.setAttribute("class",R(i+" "+e))}else n.setAttribute("class",R(i.replace(t," ")))}}function k(e,t,n){function r(){this.style.removeProperty(e)}function i(){this.style.setProperty(e,t,n)}function o(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}return null==t?r:"function"==typeof t?o:i}function P(e,t){function n(){delete this[e]}function r(){this[e]=t}function i(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}return null==t?n:"function"==typeof t?i:r}function M(e){return"function"==typeof e?e:(e=ia.ns.qualify(e)).local?function(){return this.ownerDocument.createElementNS(e.space,e.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,e)}}function j(){var e=this.parentNode;e&&e.removeChild(this)}function G(e){return{__data__:e}}function U(e){return function(){return Aa(this,e)}}function B(e){arguments.length||(e=t);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}function q(e,t){for(var n=0,r=e.length;r>n;n++)for(var i,o=e[n],s=0,a=o.length;a>s;s++)(i=o[s])&&t(i,s,n);return e}function H(e){Sa(e,Ra);return e}function V(e){var t,n;return function(r,i,o){var s,a=e[o].update,l=a.length;o!=n&&(n=o,t=0);i>=t&&(t=i+1);for(;!(s=a[t])&&++t<l;);return s}}function W(e,t,n){function r(){var t=this[s];if(t){this.removeEventListener(e,t,t.$);delete this[s]}}function i(){var i=l(t,sa(arguments));r.call(this);this.addEventListener(e,this[s]=i,i.$=n);i._=t}function o(){var t,n=new RegExp("^__on([^.]+)"+ia.requote(e)+"$");for(var r in this)if(t=r.match(n)){var i=this[r];this.removeEventListener(t[1],i,i.$);delete this[r]}}var s="__on"+e,a=e.indexOf("."),l=z;a>0&&(e=e.slice(0,a));var u=_a.get(e);u&&(e=u,l=$);return a?t?i:r:t?x:o}function z(e,t){return function(n){var r=ia.event;ia.event=n;t[0]=this.__data__;try{e.apply(this,t)}finally{ia.event=r}}}function $(e,t){var n=z(e,t);return function(e){var t=this,r=e.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||n.call(t,e)}}function X(){var e=".dragsuppress-"+ ++Fa,t="click"+e,n=ia.select(ua).on("touchmove"+e,S).on("dragstart"+e,S).on("selectstart"+e,S);if(Da){var r=la.style,i=r[Da];r[Da]="none"}return function(o){n.on(e,null);Da&&(r[Da]=i);if(o){var s=function(){n.on(t,null)};n.on(t,function(){S();s()},!0);setTimeout(s,0)}}}function Y(e,t){t.changedTouches&&(t=t.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();if(0>ka&&(ua.scrollX||ua.scrollY)){n=ia.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var i=n[0][0].getScreenCTM();ka=!(i.f||i.e);n.remove()}ka?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY);r=r.matrixTransform(e.getScreenCTM().inverse());return[r.x,r.y]}var o=e.getBoundingClientRect();return[t.clientX-o.left-e.clientLeft,t.clientY-o.top-e.clientTop]
}function K(){return ia.event.changedTouches[0].identifier}function Q(){return ia.event.target}function J(){return ua}function Z(e){return e>0?1:0>e?-1:0}function et(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function tt(e){return e>1?0:-1>e?ja:Math.acos(e)}function nt(e){return e>1?Ba:-1>e?-Ba:Math.asin(e)}function rt(e){return((e=Math.exp(e))-1/e)/2}function it(e){return((e=Math.exp(e))+1/e)/2}function ot(e){return((e=Math.exp(2*e))-1)/(e+1)}function st(e){return(e=Math.sin(e/2))*e}function at(){}function lt(e,t,n){return this instanceof lt?void(this.h=+e,this.s=+t,this.l=+n):arguments.length<2?e instanceof lt?new lt(e.h,e.s,e.l):Tt(""+e,St,lt):new lt(e,t,n)}function ut(e,t,n){function r(e){e>360?e-=360:0>e&&(e+=360);return 60>e?o+(s-o)*e/60:180>e?s:240>e?o+(s-o)*(240-e)/60:o}function i(e){return Math.round(255*r(e))}var o,s;e=isNaN(e)?0:(e%=360)<0?e+360:e;t=isNaN(t)?0:0>t?0:t>1?1:t;n=0>n?0:n>1?1:n;s=.5>=n?n*(1+t):n+t-n*t;o=2*n-s;return new Et(i(e+120),i(e),i(e-120))}function ct(e,t,n){return this instanceof ct?void(this.h=+e,this.c=+t,this.l=+n):arguments.length<2?e instanceof ct?new ct(e.h,e.c,e.l):e instanceof dt?ht(e.l,e.a,e.b):ht((e=Nt((e=ia.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new ct(e,t,n)}function pt(e,t,n){isNaN(e)&&(e=0);isNaN(t)&&(t=0);return new dt(n,Math.cos(e*=qa)*t,Math.sin(e)*t)}function dt(e,t,n){return this instanceof dt?void(this.l=+e,this.a=+t,this.b=+n):arguments.length<2?e instanceof dt?new dt(e.l,e.a,e.b):e instanceof ct?pt(e.h,e.c,e.l):Nt((e=Et(e)).r,e.g,e.b):new dt(e,t,n)}function ft(e,t,n){var r=(e+16)/116,i=r+t/500,o=r-n/200;i=gt(i)*Za;r=gt(r)*el;o=gt(o)*tl;return new Et(vt(3.2404542*i-1.5371385*r-.4985314*o),vt(-.969266*i+1.8760108*r+.041556*o),vt(.0556434*i-.2040259*r+1.0572252*o))}function ht(e,t,n){return e>0?new ct(Math.atan2(n,t)*Ha,Math.sqrt(t*t+n*n),e):new ct(0/0,0/0,e)}function gt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function mt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function vt(e){return Math.round(255*(.00304>=e?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function Et(e,t,n){return this instanceof Et?void(this.r=~~e,this.g=~~t,this.b=~~n):arguments.length<2?e instanceof Et?new Et(e.r,e.g,e.b):Tt(""+e,Et,ut):new Et(e,t,n)}function yt(e){return new Et(e>>16,e>>8&255,255&e)}function xt(e){return yt(e)+""}function bt(e){return 16>e?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function Tt(e,t,n){var r,i,o,s=0,a=0,l=0;r=/([a-z]+)\((.*)\)/i.exec(e);if(r){i=r[2].split(",");switch(r[1]){case"hsl":return n(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(Lt(i[0]),Lt(i[1]),Lt(i[2]))}}if(o=il.get(e))return t(o.r,o.g,o.b);if(null!=e&&"#"===e.charAt(0)&&!isNaN(o=parseInt(e.slice(1),16)))if(4===e.length){s=(3840&o)>>4;s=s>>4|s;a=240&o;a=a>>4|a;l=15&o;l=l<<4|l}else if(7===e.length){s=(16711680&o)>>16;a=(65280&o)>>8;l=255&o}return t(s,a,l)}function St(e,t,n){var r,i,o=Math.min(e/=255,t/=255,n/=255),s=Math.max(e,t,n),a=s-o,l=(s+o)/2;if(a){i=.5>l?a/(s+o):a/(2-s-o);r=e==s?(t-n)/a+(n>t?6:0):t==s?(n-e)/a+2:(e-t)/a+4;r*=60}else{r=0/0;i=l>0&&1>l?0:r}return new lt(r,i,l)}function Nt(e,t,n){e=Ct(e);t=Ct(t);n=Ct(n);var r=mt((.4124564*e+.3575761*t+.1804375*n)/Za),i=mt((.2126729*e+.7151522*t+.072175*n)/el),o=mt((.0193339*e+.119192*t+.9503041*n)/tl);return dt(116*i-16,500*(r-i),200*(i-o))}function Ct(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function Lt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}function At(e){return"function"==typeof e?e:function(){return e}}function It(e){return e}function wt(e){return function(t,n,r){2===arguments.length&&"function"==typeof n&&(r=n,n=null);return Rt(t,n,e,r)}}function Rt(e,t,n,r){function i(){var e,t=l.status;if(!t&&_t(l)||t>=200&&300>t||304===t){try{e=n.call(o,l)}catch(r){s.error.call(o,r);return}s.load.call(o,e)}else s.error.call(o,l)}var o={},s=ia.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,u=null;!ua.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(e)||(l=new XDomainRequest);"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()};l.onprogress=function(e){var t=ia.event;ia.event=e;try{s.progress.call(o,l)}finally{ia.event=t}};o.header=function(e,t){e=(e+"").toLowerCase();if(arguments.length<2)return a[e];null==t?delete a[e]:a[e]=t+"";return o};o.mimeType=function(e){if(!arguments.length)return t;t=null==e?null:e+"";return o};o.responseType=function(e){if(!arguments.length)return u;u=e;return o};o.response=function(e){n=e;return o};["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(sa(arguments)))}});o.send=function(n,r,i){2===arguments.length&&"function"==typeof r&&(i=r,r=null);l.open(n,e,!0);null==t||"accept"in a||(a.accept=t+",*/*");if(l.setRequestHeader)for(var c in a)l.setRequestHeader(c,a[c]);null!=t&&l.overrideMimeType&&l.overrideMimeType(t);null!=u&&(l.responseType=u);null!=i&&o.on("error",i).on("load",function(e){i(null,e)});s.beforesend.call(o,l);l.send(null==r?null:r);return o};o.abort=function(){l.abort();return o};ia.rebind(o,s,"on");return null==r?o:o.get(Ot(r))}function Ot(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}function _t(e){var t=e.responseType;return t&&"text"!==t?e.response:e.responseText}function Dt(){var e=Ft(),t=kt()-e;if(t>24){if(isFinite(t)){clearTimeout(ll);ll=setTimeout(Dt,t)}al=0}else{al=1;cl(Dt)}}function Ft(){var e=Date.now();ul=ol;for(;ul;){e>=ul.t&&(ul.f=ul.c(e-ul.t));ul=ul.n}return e}function kt(){for(var e,t=ol,n=1/0;t;)if(t.f)t=e?e.n=t.n:ol=t.n;else{t.t<n&&(n=t.t);t=(e=t).n}sl=e;return n}function Pt(e,t){return t-(e?Math.ceil(Math.log(e)/Math.LN10):1)}function Mt(e,t){var n=Math.pow(10,3*Ea(8-t));return{scale:t>8?function(e){return e/n}:function(e){return e*n},symbol:e}}function jt(e){var t=e.decimal,n=e.thousands,r=e.grouping,i=e.currency,o=r&&n?function(e,t){for(var i=e.length,o=[],s=0,a=r[0],l=0;i>0&&a>0;){l+a+1>t&&(a=Math.max(1,t-l));o.push(e.substring(i-=a,i+a));if((l+=a+1)>t)break;a=r[s=(s+1)%r.length]}return o.reverse().join(n)}:It;return function(e){var n=dl.exec(e),r=n[1]||" ",s=n[2]||">",a=n[3]||"-",l=n[4]||"",u=n[5],c=+n[6],p=n[7],d=n[8],f=n[9],h=1,g="",m="",v=!1,E=!0;d&&(d=+d.substring(1));if(u||"0"===r&&"="===s){u=r="0";s="="}switch(f){case"n":p=!0;f="g";break;case"%":h=100;m="%";f="f";break;case"p":h=100;m="%";f="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+f.toLowerCase());case"c":E=!1;case"d":v=!0;d=0;break;case"s":h=-1;f="r"}"$"===l&&(g=i[0],m=i[1]);"r"!=f||d||(f="g");null!=d&&("g"==f?d=Math.max(1,Math.min(21,d)):("e"==f||"f"==f)&&(d=Math.max(0,Math.min(20,d))));f=fl.get(f)||Gt;var y=u&&p;return function(e){var n=m;if(v&&e%1)return"";var i=0>e||0===e&&0>1/e?(e=-e,"-"):"-"===a?"":a;if(0>h){var l=ia.formatPrefix(e,d);e=l.scale(e);n=l.symbol+m}else e*=h;e=f(e,d);var x,b,T=e.lastIndexOf(".");if(0>T){var S=E?e.lastIndexOf("e"):-1;0>S?(x=e,b=""):(x=e.substring(0,S),b=e.substring(S))}else{x=e.substring(0,T);b=t+e.substring(T+1)}!u&&p&&(x=o(x,1/0));var N=g.length+x.length+b.length+(y?0:i.length),C=c>N?new Array(N=c-N+1).join(r):"";y&&(x=o(C+x,C.length?c-b.length:1/0));i+=g;e=x+b;return("<"===s?i+e+C:">"===s?C+i+e:"^"===s?C.substring(0,N>>=1)+i+e+C.substring(N):i+(y?e:C+e))+n}}}function Gt(e){return e+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Bt(e,t,n){function r(t){var n=e(t),r=o(n,1);return r-t>t-n?n:r}function i(n){t(n=e(new gl(n-1)),1);return n}function o(e,n){t(e=new gl(+e),n);return e}function s(e,r,o){var s=i(e),a=[];if(o>1)for(;r>s;){n(s)%o||a.push(new Date(+s));t(s,1)}else for(;r>s;)a.push(new Date(+s)),t(s,1);return a}function a(e,t,n){try{gl=Ut;var r=new Ut;r._=e;return s(r,t,n)}finally{gl=Date}}e.floor=e;e.round=r;e.ceil=i;e.offset=o;e.range=s;var l=e.utc=qt(e);l.floor=l;l.round=qt(r);l.ceil=qt(i);l.offset=qt(o);l.range=a;return e}function qt(e){return function(t,n){try{gl=Ut;var r=new Ut;r._=t;return e(r,n)._}finally{gl=Date}}}function Ht(e){function t(e){function t(t){for(var n,i,o,s=[],a=-1,l=0;++a<r;)if(37===e.charCodeAt(a)){s.push(e.slice(l,a));null!=(i=vl[n=e.charAt(++a)])&&(n=e.charAt(++a));(o=I[n])&&(n=o(t,null==i?"e"===n?" ":"0":i));s.push(n);l=a+1}s.push(e.slice(l,a));return s.join("")}var r=e.length;t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=n(r,e,t,0);if(i!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var o=null!=r.Z&&gl!==Ut,s=new(o?Ut:gl);if("j"in r)s.setFullYear(r.y,0,r.j);else if("w"in r&&("W"in r||"U"in r)){s.setFullYear(r.y,0,1);s.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(s.getDay()+5)%7:r.w+7*r.U-(s.getDay()+6)%7)}else s.setFullYear(r.y,r.m,r.d);s.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L);return o?s._:s};t.toString=function(){return e};return t}function n(e,t,n,r){for(var i,o,s,a=0,l=t.length,u=n.length;l>a;){if(r>=u)return-1;i=t.charCodeAt(a++);if(37===i){s=t.charAt(a++);o=w[s in vl?t.charAt(a++):s];if(!o||(r=o(e,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function r(e,t,n){T.lastIndex=0;var r=T.exec(t.slice(n));return r?(e.w=S.get(r[0].toLowerCase()),n+r[0].length):-1}function i(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.w=b.get(r[0].toLowerCase()),n+r[0].length):-1}function o(e,t,n){L.lastIndex=0;var r=L.exec(t.slice(n));return r?(e.m=A.get(r[0].toLowerCase()),n+r[0].length):-1}function s(e,t,n){N.lastIndex=0;var r=N.exec(t.slice(n));return r?(e.m=C.get(r[0].toLowerCase()),n+r[0].length):-1}function a(e,t,r){return n(e,I.c.toString(),t,r)}function l(e,t,r){return n(e,I.x.toString(),t,r)}function u(e,t,r){return n(e,I.X.toString(),t,r)}function c(e,t,n){var r=y.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)}var p=e.dateTime,d=e.date,f=e.time,h=e.periods,g=e.days,m=e.shortDays,v=e.months,E=e.shortMonths;t.utc=function(e){function n(e){try{gl=Ut;var t=new gl;t._=e;return r(t)}finally{gl=Date}}var r=t(e);n.parse=function(e){try{gl=Ut;var t=r.parse(e);return t&&t._}finally{gl=Date}};n.toString=r.toString;return n};t.multi=t.utc.multi=cn;var y=ia.map(),x=Wt(g),b=zt(g),T=Wt(m),S=zt(m),N=Wt(v),C=zt(v),L=Wt(E),A=zt(E);h.forEach(function(e,t){y.set(e.toLowerCase(),t)});var I={a:function(e){return m[e.getDay()]},A:function(e){return g[e.getDay()]},b:function(e){return E[e.getMonth()]},B:function(e){return v[e.getMonth()]},c:t(p),d:function(e,t){return Vt(e.getDate(),t,2)},e:function(e,t){return Vt(e.getDate(),t,2)},H:function(e,t){return Vt(e.getHours(),t,2)},I:function(e,t){return Vt(e.getHours()%12||12,t,2)},j:function(e,t){return Vt(1+hl.dayOfYear(e),t,3)},L:function(e,t){return Vt(e.getMilliseconds(),t,3)},m:function(e,t){return Vt(e.getMonth()+1,t,2)},M:function(e,t){return Vt(e.getMinutes(),t,2)},p:function(e){return h[+(e.getHours()>=12)]},S:function(e,t){return Vt(e.getSeconds(),t,2)},U:function(e,t){return Vt(hl.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Vt(hl.mondayOfYear(e),t,2)},x:t(d),X:t(f),y:function(e,t){return Vt(e.getFullYear()%100,t,2)},Y:function(e,t){return Vt(e.getFullYear()%1e4,t,4)},Z:ln,"%":function(){return"%"}},w={a:r,A:i,b:o,B:s,c:a,d:tn,e:tn,H:rn,I:rn,j:nn,L:an,m:en,M:on,p:c,S:sn,U:Xt,w:$t,W:Yt,x:l,X:u,y:Qt,Y:Kt,Z:Jt,"%":un};return t}function Vt(e,t,n){var r=0>e?"-":"",i=(r?-e:e)+"",o=i.length;return r+(n>o?new Array(n-o+1).join(t)+i:i)}function Wt(e){return new RegExp("^(?:"+e.map(ia.requote).join("|")+")","i")}function zt(e){for(var t=new u,n=-1,r=e.length;++n<r;)t.set(e[n].toLowerCase(),n);return t}function $t(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Xt(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n));return r?(e.U=+r[0],n+r[0].length):-1}function Yt(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n));return r?(e.W=+r[0],n+r[0].length):-1}function Kt(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function Qt(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.y=Zt(+r[0]),n+r[0].length):-1}function Jt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Zt(e){return e+(e>68?1900:2e3)}function en(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function tn(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function nn(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function rn(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function on(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function sn(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function an(e,t,n){El.lastIndex=0;var r=El.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function ln(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=Ea(t)/60|0,i=Ea(t)%60;return n+Vt(r,"0",2)+Vt(i,"0",2)}function un(e,t,n){yl.lastIndex=0;var r=yl.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function cn(e){for(var t=e.length,n=-1;++n<t;)e[n][0]=this(e[n][0]);return function(t){for(var n=0,r=e[n];!r[1](t);)r=e[++n];return r[0](t)}}function pn(){}function dn(e,t,n){var r=n.s=e+t,i=r-e,o=r-i;n.t=e-o+(t-i)}function fn(e,t){e&&Sl.hasOwnProperty(e.type)&&Sl[e.type](e,t)}function hn(e,t,n){var r,i=-1,o=e.length-n;t.lineStart();for(;++i<o;)r=e[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function gn(e,t){var n=-1,r=e.length;t.polygonStart();for(;++n<r;)hn(e[n],t,1);t.polygonEnd()}function mn(){function e(e,t){e*=qa;t=t*qa/2+ja/4;var n=e-r,s=n>=0?1:-1,a=s*n,l=Math.cos(t),u=Math.sin(t),c=o*u,p=i*l+c*Math.cos(a),d=c*s*Math.sin(a);Cl.add(Math.atan2(d,p));r=e,i=l,o=u}var t,n,r,i,o;Ll.point=function(s,a){Ll.point=e;r=(t=s)*qa,i=Math.cos(a=(n=a)*qa/2+ja/4),o=Math.sin(a)};Ll.lineEnd=function(){e(t,n)}}function vn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function En(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function yn(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function xn(e,t){e[0]+=t[0];e[1]+=t[1];e[2]+=t[2]}function bn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Tn(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t;e[1]/=t;e[2]/=t}function Sn(e){return[Math.atan2(e[1],e[0]),nt(e[2])]}function Nn(e,t){return Ea(e[0]-t[0])<Pa&&Ea(e[1]-t[1])<Pa}function Cn(e,t){e*=qa;var n=Math.cos(t*=qa);Ln(n*Math.cos(e),n*Math.sin(e),Math.sin(t))}function Ln(e,t,n){++Al;wl+=(e-wl)/Al;Rl+=(t-Rl)/Al;Ol+=(n-Ol)/Al}function An(){function e(e,i){e*=qa;var o=Math.cos(i*=qa),s=o*Math.cos(e),a=o*Math.sin(e),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=n*l-r*a)*u+(u=r*s-t*l)*u+(u=t*a-n*s)*u),t*s+n*a+r*l);Il+=u;_l+=u*(t+(t=s));Dl+=u*(n+(n=a));Fl+=u*(r+(r=l));Ln(t,n,r)}var t,n,r;jl.point=function(i,o){i*=qa;var s=Math.cos(o*=qa);t=s*Math.cos(i);n=s*Math.sin(i);r=Math.sin(o);jl.point=e;Ln(t,n,r)}}function In(){jl.point=Cn}function wn(){function e(e,t){e*=qa;var n=Math.cos(t*=qa),s=n*Math.cos(e),a=n*Math.sin(e),l=Math.sin(t),u=i*l-o*a,c=o*s-r*l,p=r*a-i*s,d=Math.sqrt(u*u+c*c+p*p),f=r*s+i*a+o*l,h=d&&-tt(f)/d,g=Math.atan2(d,f);kl+=h*u;Pl+=h*c;Ml+=h*p;Il+=g;_l+=g*(r+(r=s));Dl+=g*(i+(i=a));Fl+=g*(o+(o=l));Ln(r,i,o)}var t,n,r,i,o;jl.point=function(s,a){t=s,n=a;jl.point=e;s*=qa;var l=Math.cos(a*=qa);r=l*Math.cos(s);i=l*Math.sin(s);o=Math.sin(a);Ln(r,i,o)};jl.lineEnd=function(){e(t,n);jl.lineEnd=In;jl.point=Cn}}function Rn(e,t){function n(n,r){return n=e(n,r),t(n[0],n[1])}e.invert&&t.invert&&(n.invert=function(n,r){return n=t.invert(n,r),n&&e.invert(n[0],n[1])});return n}function On(){return!0}function _n(e,t,n,r,i){var o=[],s=[];e.forEach(function(e){if(!((t=e.length-1)<=0)){var t,n=e[0],r=e[t];if(Nn(n,r)){i.lineStart();for(var a=0;t>a;++a)i.point((n=e[a])[0],n[1]);i.lineEnd()}else{var l=new Fn(n,e,null,!0),u=new Fn(n,null,l,!1);l.o=u;o.push(l);s.push(u);l=new Fn(r,e,null,!1);u=new Fn(r,null,l,!0);l.o=u;o.push(l);s.push(u)}}});s.sort(t);Dn(o);Dn(s);if(o.length){for(var a=0,l=n,u=s.length;u>a;++a)s[a].e=l=!l;for(var c,p,d=o[0];;){for(var f=d,h=!0;f.v;)if((f=f.n)===d)return;c=f.z;i.lineStart();do{f.v=f.o.v=!0;if(f.e){if(h)for(var a=0,u=c.length;u>a;++a)i.point((p=c[a])[0],p[1]);else r(f.x,f.n.x,1,i);f=f.n}else{if(h){c=f.p.z;for(var a=c.length-1;a>=0;--a)i.point((p=c[a])[0],p[1])}else r(f.x,f.p.x,-1,i);f=f.p}f=f.o;c=f.z;h=!h}while(!f.v);i.lineEnd()}}}function Dn(e){if(t=e.length){for(var t,n,r=0,i=e[0];++r<t;){i.n=n=e[r];n.p=i;i=n}i.n=n=e[0];n.p=i}}function Fn(e,t,n,r){this.x=e;this.z=t;this.o=n;this.e=r;this.v=!1;this.n=this.p=null}function kn(e,t,n,r){return function(i,o){function s(t,n){var r=i(t,n);e(t=r[0],n=r[1])&&o.point(t,n)}function a(e,t){var n=i(e,t);m.point(n[0],n[1])}function l(){E.point=a;m.lineStart()}function u(){E.point=s;m.lineEnd()}function c(e,t){g.push([e,t]);var n=i(e,t);x.point(n[0],n[1])}function p(){x.lineStart();g=[]}function d(){c(g[0][0],g[0][1]);x.lineEnd();var e,t=x.clean(),n=y.buffer(),r=n.length;g.pop();h.push(g);g=null;if(r)if(1&t){e=n[0];var i,r=e.length-1,s=-1;if(r>0){b||(o.polygonStart(),b=!0);o.lineStart();for(;++s<r;)o.point((i=e[s])[0],i[1]);o.lineEnd()}}else{r>1&&2&t&&n.push(n.pop().concat(n.shift()));f.push(n.filter(Pn))}}var f,h,g,m=t(o),v=i.invert(r[0],r[1]),E={point:s,lineStart:l,lineEnd:u,polygonStart:function(){E.point=c;E.lineStart=p;E.lineEnd=d;f=[];h=[]},polygonEnd:function(){E.point=s;E.lineStart=l;E.lineEnd=u;f=ia.merge(f);var e=qn(v,h);if(f.length){b||(o.polygonStart(),b=!0);_n(f,jn,e,n,o)}else if(e){b||(o.polygonStart(),b=!0);o.lineStart();n(null,null,1,o);o.lineEnd()}b&&(o.polygonEnd(),b=!1);f=h=null},sphere:function(){o.polygonStart();o.lineStart();n(null,null,1,o);o.lineEnd();o.polygonEnd()}},y=Mn(),x=t(y),b=!1;return E}}function Pn(e){return e.length>1}function Mn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:x,buffer:function(){var n=t;t=[];e=null;return n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function jn(e,t){return((e=e.x)[0]<0?e[1]-Ba-Pa:Ba-e[1])-((t=t.x)[0]<0?t[1]-Ba-Pa:Ba-t[1])}function Gn(e){var t,n=0/0,r=0/0,i=0/0;return{lineStart:function(){e.lineStart();t=1},point:function(o,s){var a=o>0?ja:-ja,l=Ea(o-n);if(Ea(l-ja)<Pa){e.point(n,r=(r+s)/2>0?Ba:-Ba);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);e.point(o,r);t=0}else if(i!==a&&l>=ja){Ea(n-i)<Pa&&(n-=i*Pa);Ea(o-a)<Pa&&(o-=a*Pa);r=Un(n,r,o,s);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);t=0}e.point(n=o,r=s);i=a},lineEnd:function(){e.lineEnd();n=r=0/0},clean:function(){return 2-t}}}function Un(e,t,n,r){var i,o,s=Math.sin(e-n);return Ea(s)>Pa?Math.atan((Math.sin(t)*(o=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(t))*Math.sin(e))/(i*o*s)):(t+r)/2}function Bn(e,t,n,r){var i;if(null==e){i=n*Ba;r.point(-ja,i);r.point(0,i);r.point(ja,i);r.point(ja,0);r.point(ja,-i);r.point(0,-i);r.point(-ja,-i);r.point(-ja,0);r.point(-ja,i)}else if(Ea(e[0]-t[0])>Pa){var o=e[0]<t[0]?ja:-ja;i=n*o/2;r.point(-o,i);r.point(0,i);r.point(o,i)}else r.point(t[0],t[1])}function qn(e,t){var n=e[0],r=e[1],i=[Math.sin(n),-Math.cos(n),0],o=0,s=0;Cl.reset();for(var a=0,l=t.length;l>a;++a){var u=t[a],c=u.length;if(c)for(var p=u[0],d=p[0],f=p[1]/2+ja/4,h=Math.sin(f),g=Math.cos(f),m=1;;){m===c&&(m=0);e=u[m];var v=e[0],E=e[1]/2+ja/4,y=Math.sin(E),x=Math.cos(E),b=v-d,T=b>=0?1:-1,S=T*b,N=S>ja,C=h*y;Cl.add(Math.atan2(C*T*Math.sin(S),g*x+C*Math.cos(S)));o+=N?b+T*Ga:b;if(N^d>=n^v>=n){var L=yn(vn(p),vn(e));Tn(L);var A=yn(i,L);Tn(A);var I=(N^b>=0?-1:1)*nt(A[2]);(r>I||r===I&&(L[0]||L[1]))&&(s+=N^b>=0?1:-1)}if(!m++)break;d=v,h=y,g=x,p=e}}return(-Pa>o||Pa>o&&0>Cl)^1&s}function Hn(e){function t(e,t){return Math.cos(e)*Math.cos(t)>o}function n(e){var n,o,l,u,c;return{lineStart:function(){u=l=!1;c=1},point:function(p,d){var f,h=[p,d],g=t(p,d),m=s?g?0:i(p,d):g?i(p+(0>p?ja:-ja),d):0;!n&&(u=l=g)&&e.lineStart();if(g!==l){f=r(n,h);if(Nn(n,f)||Nn(h,f)){h[0]+=Pa;h[1]+=Pa;g=t(h[0],h[1])}}if(g!==l){c=0;if(g){e.lineStart();f=r(h,n);e.point(f[0],f[1])}else{f=r(n,h);e.point(f[0],f[1]);e.lineEnd()}n=f}else if(a&&n&&s^g){var v;if(!(m&o)&&(v=r(h,n,!0))){c=0;if(s){e.lineStart();e.point(v[0][0],v[0][1]);e.point(v[1][0],v[1][1]);e.lineEnd()}else{e.point(v[1][0],v[1][1]);e.lineEnd();e.lineStart();e.point(v[0][0],v[0][1])}}}!g||n&&Nn(n,h)||e.point(h[0],h[1]);n=h,l=g,o=m},lineEnd:function(){l&&e.lineEnd();n=null},clean:function(){return c|(u&&l)<<1}}}function r(e,t,n){var r=vn(e),i=vn(t),s=[1,0,0],a=yn(r,i),l=En(a,a),u=a[0],c=l-u*u;if(!c)return!n&&e;var p=o*l/c,d=-o*u/c,f=yn(s,a),h=bn(s,p),g=bn(a,d);xn(h,g);var m=f,v=En(h,m),E=En(m,m),y=v*v-E*(En(h,h)-1);if(!(0>y)){var x=Math.sqrt(y),b=bn(m,(-v-x)/E);xn(b,h);b=Sn(b);if(!n)return b;var T,S=e[0],N=t[0],C=e[1],L=t[1];S>N&&(T=S,S=N,N=T);var A=N-S,I=Ea(A-ja)<Pa,w=I||Pa>A;!I&&C>L&&(T=C,C=L,L=T);if(w?I?C+L>0^b[1]<(Ea(b[0]-S)<Pa?C:L):C<=b[1]&&b[1]<=L:A>ja^(S<=b[0]&&b[0]<=N)){var R=bn(m,(-v+x)/E);xn(R,h);return[b,Sn(R)]}}}function i(t,n){var r=s?e:ja-e,i=0;-r>t?i|=1:t>r&&(i|=2);-r>n?i|=4:n>r&&(i|=8);return i}var o=Math.cos(e),s=o>0,a=Ea(o)>Pa,l=mr(e,6*qa);return kn(t,n,l,s?[0,-e]:[-ja,e-ja])}function Vn(e,t,n,r){return function(i){var o,s=i.a,a=i.b,l=s.x,u=s.y,c=a.x,p=a.y,d=0,f=1,h=c-l,g=p-u;o=e-l;if(h||!(o>0)){o/=h;if(0>h){if(d>o)return;f>o&&(f=o)}else if(h>0){if(o>f)return;o>d&&(d=o)}o=n-l;if(h||!(0>o)){o/=h;if(0>h){if(o>f)return;o>d&&(d=o)}else if(h>0){if(d>o)return;f>o&&(f=o)}o=t-u;if(g||!(o>0)){o/=g;if(0>g){if(d>o)return;f>o&&(f=o)}else if(g>0){if(o>f)return;o>d&&(d=o)}o=r-u;if(g||!(0>o)){o/=g;if(0>g){if(o>f)return;o>d&&(d=o)}else if(g>0){if(d>o)return;f>o&&(f=o)}d>0&&(i.a={x:l+d*h,y:u+d*g});1>f&&(i.b={x:l+f*h,y:u+f*g});return i}}}}}}function Wn(e,t,n,r){function i(r,i){return Ea(r[0]-e)<Pa?i>0?0:3:Ea(r[0]-n)<Pa?i>0?2:1:Ea(r[1]-t)<Pa?i>0?1:0:i>0?3:2}function o(e,t){return s(e.x,t.x)}function s(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}return function(a){function l(e){for(var t=0,n=m.length,r=e[1],i=0;n>i;++i)for(var o,s=1,a=m[i],l=a.length,u=a[0];l>s;++s){o=a[s];u[1]<=r?o[1]>r&&et(u,o,e)>0&&++t:o[1]<=r&&et(u,o,e)<0&&--t;u=o}return 0!==t}function u(o,a,l,u){var c=0,p=0;if(null==o||(c=i(o,l))!==(p=i(a,l))||s(o,a)<0^l>0){do u.point(0===c||3===c?e:n,c>1?r:t);while((c=(c+l+4)%4)!==p)}else u.point(a[0],a[1])}function c(i,o){return i>=e&&n>=i&&o>=t&&r>=o}function p(e,t){c(e,t)&&a.point(e,t)}function d(){w.point=h;m&&m.push(v=[]);N=!0;S=!1;b=T=0/0}function f(){if(g){h(E,y);x&&S&&A.rejoin();g.push(A.buffer())}w.point=p;S&&a.lineEnd()}function h(e,t){e=Math.max(-Ul,Math.min(Ul,e));t=Math.max(-Ul,Math.min(Ul,t));var n=c(e,t);m&&v.push([e,t]);if(N){E=e,y=t,x=n;N=!1;if(n){a.lineStart();a.point(e,t)}}else if(n&&S)a.point(e,t);else{var r={a:{x:b,y:T},b:{x:e,y:t}};if(I(r)){if(!S){a.lineStart();a.point(r.a.x,r.a.y)}a.point(r.b.x,r.b.y);n||a.lineEnd();C=!1}else if(n){a.lineStart();a.point(e,t);C=!1}}b=e,T=t,S=n}var g,m,v,E,y,x,b,T,S,N,C,L=a,A=Mn(),I=Vn(e,t,n,r),w={point:p,lineStart:d,lineEnd:f,polygonStart:function(){a=A;g=[];m=[];C=!0},polygonEnd:function(){a=L;g=ia.merge(g);var t=l([e,r]),n=C&&t,i=g.length;if(n||i){a.polygonStart();if(n){a.lineStart();u(null,null,1,a);a.lineEnd()}i&&_n(g,o,t,u,a);a.polygonEnd()}g=m=v=null}};return w}}function zn(e){var t=0,n=ja/3,r=lr(e),i=r(t,n);i.parallels=function(e){return arguments.length?r(t=e[0]*ja/180,n=e[1]*ja/180):[t/ja*180,n/ja*180]};return i}function $n(e,t){function n(e,t){var n=Math.sqrt(o-2*i*Math.sin(t))/i;return[n*Math.sin(e*=i),s-n*Math.cos(e)]}var r=Math.sin(e),i=(r+Math.sin(t))/2,o=1+r*(2*i-r),s=Math.sqrt(o)/i;n.invert=function(e,t){var n=s-t;return[Math.atan2(e,n)/i,nt((o-(e*e+n*n)*i*i)/(2*i))]};return n}function Xn(){function e(e,t){ql+=i*e-r*t;r=e,i=t}var t,n,r,i;$l.point=function(o,s){$l.point=e;t=r=o,n=i=s};$l.lineEnd=function(){e(t,n)}}function Yn(e,t){Hl>e&&(Hl=e);e>Wl&&(Wl=e);Vl>t&&(Vl=t);t>zl&&(zl=t)}function Kn(){function e(e,t){s.push("M",e,",",t,o)}function t(e,t){s.push("M",e,",",t);a.point=n}function n(e,t){s.push("L",e,",",t)}function r(){a.point=e}function i(){s.push("Z")}var o=Qn(4.5),s=[],a={point:e,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r;a.point=e},pointRadius:function(e){o=Qn(e);return a},result:function(){if(s.length){var e=s.join("");s=[];return e}}};return a}function Qn(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}function Jn(e,t){wl+=e;Rl+=t;++Ol}function Zn(){function e(e,r){var i=e-t,o=r-n,s=Math.sqrt(i*i+o*o);_l+=s*(t+e)/2;Dl+=s*(n+r)/2;Fl+=s;Jn(t=e,n=r)}var t,n;Yl.point=function(r,i){Yl.point=e;Jn(t=r,n=i)}}function er(){Yl.point=Jn}function tr(){function e(e,t){var n=e-r,o=t-i,s=Math.sqrt(n*n+o*o);_l+=s*(r+e)/2;Dl+=s*(i+t)/2;Fl+=s;s=i*e-r*t;kl+=s*(r+e);Pl+=s*(i+t);Ml+=3*s;Jn(r=e,i=t)}var t,n,r,i;Yl.point=function(o,s){Yl.point=e;Jn(t=r=o,n=i=s)};Yl.lineEnd=function(){e(t,n)}}function nr(e){function t(t,n){e.moveTo(t+s,n);e.arc(t,n,s,0,Ga)}function n(t,n){e.moveTo(t,n);a.point=r}function r(t,n){e.lineTo(t,n)}function i(){a.point=t}function o(){e.closePath()}var s=4.5,a={point:t,lineStart:function(){a.point=n},lineEnd:i,polygonStart:function(){a.lineEnd=o},polygonEnd:function(){a.lineEnd=i;a.point=t},pointRadius:function(e){s=e;return a},result:x};return a}function rr(e){function t(e){return(a?r:n)(e)}function n(t){return sr(t,function(n,r){n=e(n,r);t.point(n[0],n[1])})}function r(t){function n(n,r){n=e(n,r);t.point(n[0],n[1])}function r(){y=0/0;N.point=o;t.lineStart()}function o(n,r){var o=vn([n,r]),s=e(n,r);i(y,x,E,b,T,S,y=s[0],x=s[1],E=n,b=o[0],T=o[1],S=o[2],a,t);t.point(y,x)}function s(){N.point=n;t.lineEnd()}function l(){r();N.point=u;N.lineEnd=c}function u(e,t){o(p=e,d=t),f=y,h=x,g=b,m=T,v=S;N.point=o}function c(){i(y,x,E,b,T,S,f,h,p,g,m,v,a,t);N.lineEnd=s;s()}var p,d,f,h,g,m,v,E,y,x,b,T,S,N={point:n,lineStart:r,lineEnd:s,polygonStart:function(){t.polygonStart();N.lineStart=l},polygonEnd:function(){t.polygonEnd();N.lineStart=r}};return N}function i(t,n,r,a,l,u,c,p,d,f,h,g,m,v){var E=c-t,y=p-n,x=E*E+y*y;if(x>4*o&&m--){var b=a+f,T=l+h,S=u+g,N=Math.sqrt(b*b+T*T+S*S),C=Math.asin(S/=N),L=Ea(Ea(S)-1)<Pa||Ea(r-d)<Pa?(r+d)/2:Math.atan2(T,b),A=e(L,C),I=A[0],w=A[1],R=I-t,O=w-n,_=y*R-E*O;if(_*_/x>o||Ea((E*R+y*O)/x-.5)>.3||s>a*f+l*h+u*g){i(t,n,r,a,l,u,I,w,L,b/=N,T/=N,S,m,v);v.point(I,w);i(I,w,L,b,T,S,c,p,d,f,h,g,m,v)}}}var o=.5,s=Math.cos(30*qa),a=16;t.precision=function(e){if(!arguments.length)return Math.sqrt(o);a=(o=e*e)>0&&16;return t};return t}function ir(e){var t=rr(function(t,n){return e([t*Ha,n*Ha])});return function(e){return ur(t(e))}}function or(e){this.stream=e}function sr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function ar(e){return lr(function(){return e})()}function lr(e){function t(e){e=a(e[0]*qa,e[1]*qa);return[e[0]*d+l,u-e[1]*d]}function n(e){e=a.invert((e[0]-l)/d,(u-e[1])/d);return e&&[e[0]*Ha,e[1]*Ha]}function r(){a=Rn(s=dr(v,E,y),o);var e=o(g,m);l=f-e[0]*d;u=h+e[1]*d;return i()}function i(){c&&(c.valid=!1,c=null);return t}var o,s,a,l,u,c,p=rr(function(e,t){e=o(e,t);return[e[0]*d+l,u-e[1]*d]}),d=150,f=480,h=250,g=0,m=0,v=0,E=0,y=0,x=Gl,b=It,T=null,S=null;t.stream=function(e){c&&(c.valid=!1);c=ur(x(s,p(b(e))));c.valid=!0;return c};t.clipAngle=function(e){if(!arguments.length)return T;x=null==e?(T=e,Gl):Hn((T=+e)*qa);return i()};t.clipExtent=function(e){if(!arguments.length)return S;S=e;b=e?Wn(e[0][0],e[0][1],e[1][0],e[1][1]):It;return i()};t.scale=function(e){if(!arguments.length)return d;d=+e;return r()};t.translate=function(e){if(!arguments.length)return[f,h];f=+e[0];h=+e[1];return r()};t.center=function(e){if(!arguments.length)return[g*Ha,m*Ha];g=e[0]%360*qa;m=e[1]%360*qa;return r()};t.rotate=function(e){if(!arguments.length)return[v*Ha,E*Ha,y*Ha];v=e[0]%360*qa;E=e[1]%360*qa;y=e.length>2?e[2]%360*qa:0;return r()};ia.rebind(t,p,"precision");return function(){o=e.apply(this,arguments);t.invert=o.invert&&n;return r()}}function ur(e){return sr(e,function(t,n){e.point(t*qa,n*qa)})}function cr(e,t){return[e,t]}function pr(e,t){return[e>ja?e-Ga:-ja>e?e+Ga:e,t]}function dr(e,t,n){return e?t||n?Rn(hr(e),gr(t,n)):hr(e):t||n?gr(t,n):pr}function fr(e){return function(t,n){return t+=e,[t>ja?t-Ga:-ja>t?t+Ga:t,n]}}function hr(e){var t=fr(e);t.invert=fr(-e);return t}function gr(e,t){function n(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),c=u*r+a*i;return[Math.atan2(l*o-c*s,a*r-u*i),nt(c*o+l*s)]}var r=Math.cos(e),i=Math.sin(e),o=Math.cos(t),s=Math.sin(t);n.invert=function(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),c=u*o-l*s;return[Math.atan2(l*o+u*s,a*r+c*i),nt(c*r-a*i)]};return n}function mr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(i,o,s,a){var l=s*t;if(null!=i){i=vr(n,i);o=vr(n,o);(s>0?o>i:i>o)&&(i+=s*Ga)}else{i=e+s*Ga;o=e-.5*l}for(var u,c=i;s>0?c>o:o>c;c-=l)a.point((u=Sn([n,-r*Math.cos(c),-r*Math.sin(c)]))[0],u[1])}}function vr(e,t){var n=vn(t);n[0]-=e;Tn(n);var r=tt(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-Pa)%(2*Math.PI)}function Er(e,t,n){var r=ia.range(e,t-Pa,n).concat(t);return function(e){return r.map(function(t){return[e,t]})}}function yr(e,t,n){var r=ia.range(e,t-Pa,n).concat(t);return function(e){return r.map(function(t){return[t,e]})}}function xr(e){return e.source}function br(e){return e.target}function Tr(e,t,n,r){var i=Math.cos(t),o=Math.sin(t),s=Math.cos(r),a=Math.sin(r),l=i*Math.cos(e),u=i*Math.sin(e),c=s*Math.cos(n),p=s*Math.sin(n),d=2*Math.asin(Math.sqrt(st(r-t)+i*s*st(n-e))),f=1/Math.sin(d),h=d?function(e){var t=Math.sin(e*=d)*f,n=Math.sin(d-e)*f,r=n*l+t*c,i=n*u+t*p,s=n*o+t*a;return[Math.atan2(i,r)*Ha,Math.atan2(s,Math.sqrt(r*r+i*i))*Ha]}:function(){return[e*Ha,t*Ha]};h.distance=d;return h}function Sr(){function e(e,i){var o=Math.sin(i*=qa),s=Math.cos(i),a=Ea((e*=qa)-t),l=Math.cos(a);Kl+=Math.atan2(Math.sqrt((a=s*Math.sin(a))*a+(a=r*o-n*s*l)*a),n*o+r*s*l);t=e,n=o,r=s}var t,n,r;Ql.point=function(i,o){t=i*qa,n=Math.sin(o*=qa),r=Math.cos(o);Ql.point=e};Ql.lineEnd=function(){Ql.point=Ql.lineEnd=x}}function Nr(e,t){function n(t,n){var r=Math.cos(t),i=Math.cos(n),o=e(r*i);return[o*i*Math.sin(t),o*Math.sin(n)]}n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),i=t(r),o=Math.sin(i),s=Math.cos(i);return[Math.atan2(e*o,r*s),Math.asin(r&&n*o/r)]};return n}function Cr(e,t){function n(e,t){s>0?-Ba+Pa>t&&(t=-Ba+Pa):t>Ba-Pa&&(t=Ba-Pa);var n=s/Math.pow(i(t),o);return[n*Math.sin(o*e),s-n*Math.cos(o*e)]}var r=Math.cos(e),i=function(e){return Math.tan(ja/4+e/2)},o=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(i(t)/i(e)),s=r*Math.pow(i(e),o)/o;if(!o)return Ar;n.invert=function(e,t){var n=s-t,r=Z(o)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/o,2*Math.atan(Math.pow(s/r,1/o))-Ba]};return n}function Lr(e,t){function n(e,t){var n=o-t;return[n*Math.sin(i*e),o-n*Math.cos(i*e)]}var r=Math.cos(e),i=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),o=r/i+e;if(Ea(i)<Pa)return cr;n.invert=function(e,t){var n=o-t;return[Math.atan2(e,n)/i,o-Z(i)*Math.sqrt(e*e+n*n)]};return n}function Ar(e,t){return[e,Math.log(Math.tan(ja/4+t/2))]}function Ir(e){var t,n=ar(e),r=n.scale,i=n.translate,o=n.clipExtent;n.scale=function(){var e=r.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.translate=function(){var e=i.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.clipExtent=function(e){var s=o.apply(n,arguments);if(s===n){if(t=null==e){var a=ja*r(),l=i();o([[l[0]-a,l[1]-a],[l[0]+a,l[1]+a]])}}else t&&(s=null);return s};return n.clipExtent(null)}function wr(e,t){return[Math.log(Math.tan(ja/4+t/2)),-e]}function Rr(e){return e[0]}function Or(e){return e[1]}function _r(e){for(var t=e.length,n=[0,1],r=2,i=2;t>i;i++){for(;r>1&&et(e[n[r-2]],e[n[r-1]],e[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function Dr(e,t){return e[0]-t[0]||e[1]-t[1]}function Fr(e,t,n){return(n[0]-t[0])*(e[1]-t[1])<(n[1]-t[1])*(e[0]-t[0])}function kr(e,t,n,r){var i=e[0],o=n[0],s=t[0]-i,a=r[0]-o,l=e[1],u=n[1],c=t[1]-l,p=r[1]-u,d=(a*(l-u)-p*(i-o))/(p*s-a*c);
return[i+d*s,l+d*c]}function Pr(e){var t=e[0],n=e[e.length-1];return!(t[0]-n[0]||t[1]-n[1])}function Mr(){ii(this);this.edge=this.site=this.circle=null}function jr(e){var t=uu.pop()||new Mr;t.site=e;return t}function Gr(e){Yr(e);su.remove(e);uu.push(e);ii(e)}function Ur(e){var t=e.circle,n=t.x,r=t.cy,i={x:n,y:r},o=e.P,s=e.N,a=[e];Gr(e);for(var l=o;l.circle&&Ea(n-l.circle.x)<Pa&&Ea(r-l.circle.cy)<Pa;){o=l.P;a.unshift(l);Gr(l);l=o}a.unshift(l);Yr(l);for(var u=s;u.circle&&Ea(n-u.circle.x)<Pa&&Ea(r-u.circle.cy)<Pa;){s=u.N;a.push(u);Gr(u);u=s}a.push(u);Yr(u);var c,p=a.length;for(c=1;p>c;++c){u=a[c];l=a[c-1];ti(u.edge,l.site,u.site,i)}l=a[0];u=a[p-1];u.edge=Zr(l.site,u.site,null,i);Xr(l);Xr(u)}function Br(e){for(var t,n,r,i,o=e.x,s=e.y,a=su._;a;){r=qr(a,s)-o;if(r>Pa)a=a.L;else{i=o-Hr(a,s);if(!(i>Pa)){if(r>-Pa){t=a.P;n=a}else if(i>-Pa){t=a;n=a.N}else t=n=a;break}if(!a.R){t=a;break}a=a.R}}var l=jr(e);su.insert(t,l);if(t||n)if(t!==n)if(n){Yr(t);Yr(n);var u=t.site,c=u.x,p=u.y,d=e.x-c,f=e.y-p,h=n.site,g=h.x-c,m=h.y-p,v=2*(d*m-f*g),E=d*d+f*f,y=g*g+m*m,x={x:(m*E-f*y)/v+c,y:(d*y-g*E)/v+p};ti(n.edge,u,h,x);l.edge=Zr(u,e,null,x);n.edge=Zr(e,h,null,x);Xr(t);Xr(n)}else l.edge=Zr(t.site,l.site);else{Yr(t);n=jr(t.site);su.insert(l,n);l.edge=n.edge=Zr(t.site,l.site);Xr(t);Xr(n)}}function qr(e,t){var n=e.site,r=n.x,i=n.y,o=i-t;if(!o)return r;var s=e.P;if(!s)return-1/0;n=s.site;var a=n.x,l=n.y,u=l-t;if(!u)return a;var c=a-r,p=1/o-1/u,d=c/u;return p?(-d+Math.sqrt(d*d-2*p*(c*c/(-2*u)-l+u/2+i-o/2)))/p+r:(r+a)/2}function Hr(e,t){var n=e.N;if(n)return qr(n,t);var r=e.site;return r.y===t?r.x:1/0}function Vr(e){this.site=e;this.edges=[]}function Wr(e){for(var t,n,r,i,o,s,a,l,u,c,p=e[0][0],d=e[1][0],f=e[0][1],h=e[1][1],g=ou,m=g.length;m--;){o=g[m];if(o&&o.prepare()){a=o.edges;l=a.length;s=0;for(;l>s;){c=a[s].end(),r=c.x,i=c.y;u=a[++s%l].start(),t=u.x,n=u.y;if(Ea(r-t)>Pa||Ea(i-n)>Pa){a.splice(s,0,new ni(ei(o.site,c,Ea(r-p)<Pa&&h-i>Pa?{x:p,y:Ea(t-p)<Pa?n:h}:Ea(i-h)<Pa&&d-r>Pa?{x:Ea(n-h)<Pa?t:d,y:h}:Ea(r-d)<Pa&&i-f>Pa?{x:d,y:Ea(t-d)<Pa?n:f}:Ea(i-f)<Pa&&r-p>Pa?{x:Ea(n-f)<Pa?t:p,y:f}:null),o.site,null));++l}}}}}function zr(e,t){return t.angle-e.angle}function $r(){ii(this);this.x=this.y=this.arc=this.site=this.cy=null}function Xr(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,i=e.site,o=n.site;if(r!==o){var s=i.x,a=i.y,l=r.x-s,u=r.y-a,c=o.x-s,p=o.y-a,d=2*(l*p-u*c);if(!(d>=-Ma)){var f=l*l+u*u,h=c*c+p*p,g=(p*f-u*h)/d,m=(l*h-c*f)/d,p=m+a,v=cu.pop()||new $r;v.arc=e;v.site=i;v.x=g+s;v.y=p+Math.sqrt(g*g+m*m);v.cy=p;e.circle=v;for(var E=null,y=lu._;y;)if(v.y<y.y||v.y===y.y&&v.x<=y.x){if(!y.L){E=y.P;break}y=y.L}else{if(!y.R){E=y;break}y=y.R}lu.insert(E,v);E||(au=v)}}}}function Yr(e){var t=e.circle;if(t){t.P||(au=t.N);lu.remove(t);cu.push(t);ii(t);e.circle=null}}function Kr(e){for(var t,n=iu,r=Vn(e[0][0],e[0][1],e[1][0],e[1][1]),i=n.length;i--;){t=n[i];if(!Qr(t,e)||!r(t)||Ea(t.a.x-t.b.x)<Pa&&Ea(t.a.y-t.b.y)<Pa){t.a=t.b=null;n.splice(i,1)}}}function Qr(e,t){var n=e.b;if(n)return!0;var r,i,o=e.a,s=t[0][0],a=t[1][0],l=t[0][1],u=t[1][1],c=e.l,p=e.r,d=c.x,f=c.y,h=p.x,g=p.y,m=(d+h)/2,v=(f+g)/2;if(g===f){if(s>m||m>=a)return;if(d>h){if(o){if(o.y>=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y<l)return}else o={x:m,y:u};n={x:m,y:l}}}else{r=(d-h)/(g-f);i=v-r*m;if(-1>r||r>1)if(d>h){if(o){if(o.y>=u)return}else o={x:(l-i)/r,y:l};n={x:(u-i)/r,y:u}}else{if(o){if(o.y<l)return}else o={x:(u-i)/r,y:u};n={x:(l-i)/r,y:l}}else if(g>f){if(o){if(o.x>=a)return}else o={x:s,y:r*s+i};n={x:a,y:r*a+i}}else{if(o){if(o.x<s)return}else o={x:a,y:r*a+i};n={x:s,y:r*s+i}}}e.a=o;e.b=n;return!0}function Jr(e,t){this.l=e;this.r=t;this.a=this.b=null}function Zr(e,t,n,r){var i=new Jr(e,t);iu.push(i);n&&ti(i,e,t,n);r&&ti(i,t,e,r);ou[e.i].edges.push(new ni(i,e,t));ou[t.i].edges.push(new ni(i,t,e));return i}function ei(e,t,n){var r=new Jr(e,null);r.a=t;r.b=n;iu.push(r);return r}function ti(e,t,n,r){if(e.a||e.b)e.l===n?e.b=r:e.a=r;else{e.a=r;e.l=t;e.r=n}}function ni(e,t,n){var r=e.a,i=e.b;this.edge=e;this.site=t;this.angle=n?Math.atan2(n.y-t.y,n.x-t.x):e.l===t?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function ri(){this._=null}function ii(e){e.U=e.C=e.L=e.R=e.P=e.N=null}function oi(e,t){var n=t,r=t.R,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.R=r.L;n.R&&(n.R.U=n);r.L=n}function si(e,t){var n=t,r=t.L,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.L=r.R;n.L&&(n.L.U=n);r.R=n}function ai(e){for(;e.L;)e=e.L;return e}function li(e,t){var n,r,i,o=e.sort(ui).pop();iu=[];ou=new Array(e.length);su=new ri;lu=new ri;for(;;){i=au;if(o&&(!i||o.y<i.y||o.y===i.y&&o.x<i.x)){if(o.x!==n||o.y!==r){ou[o.i]=new Vr(o);Br(o);n=o.x,r=o.y}o=e.pop()}else{if(!i)break;Ur(i.arc)}}t&&(Kr(t),Wr(t));var s={cells:ou,edges:iu};su=lu=iu=ou=null;return s}function ui(e,t){return t.y-e.y||t.x-e.x}function ci(e,t,n){return(e.x-n.x)*(t.y-e.y)-(e.x-t.x)*(n.y-e.y)}function pi(e){return e.x}function di(e){return e.y}function fi(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function hi(e,t,n,r,i,o){if(!e(t,n,r,i,o)){var s=.5*(n+i),a=.5*(r+o),l=t.nodes;l[0]&&hi(e,l[0],n,r,s,a);l[1]&&hi(e,l[1],s,r,i,a);l[2]&&hi(e,l[2],n,a,s,o);l[3]&&hi(e,l[3],s,a,i,o)}}function gi(e,t,n,r,i,o,s){var a,l=1/0;(function u(e,c,p,d,f){if(!(c>o||p>s||r>d||i>f)){if(h=e.point){var h,g=t-h[0],m=n-h[1],v=g*g+m*m;if(l>v){var E=Math.sqrt(l=v);r=t-E,i=n-E;o=t+E,s=n+E;a=h}}for(var y=e.nodes,x=.5*(c+d),b=.5*(p+f),T=t>=x,S=n>=b,N=S<<1|T,C=N+4;C>N;++N)if(e=y[3&N])switch(3&N){case 0:u(e,c,p,x,b);break;case 1:u(e,x,p,d,b);break;case 2:u(e,c,b,x,f);break;case 3:u(e,x,b,d,f)}}})(e,r,i,o,s);return a}function mi(e,t){e=ia.rgb(e);t=ia.rgb(t);var n=e.r,r=e.g,i=e.b,o=t.r-n,s=t.g-r,a=t.b-i;return function(e){return"#"+bt(Math.round(n+o*e))+bt(Math.round(r+s*e))+bt(Math.round(i+a*e))}}function vi(e,t){var n,r={},i={};for(n in e)n in t?r[n]=xi(e[n],t[n]):i[n]=e[n];for(n in t)n in e||(i[n]=t[n]);return function(e){for(n in r)i[n]=r[n](e);return i}}function Ei(e,t){e=+e,t=+t;return function(n){return e*(1-n)+t*n}}function yi(e,t){var n,r,i,o=du.lastIndex=fu.lastIndex=0,s=-1,a=[],l=[];e+="",t+="";for(;(n=du.exec(e))&&(r=fu.exec(t));){if((i=r.index)>o){i=t.slice(o,i);a[s]?a[s]+=i:a[++s]=i}if((n=n[0])===(r=r[0]))a[s]?a[s]+=r:a[++s]=r;else{a[++s]=null;l.push({i:s,x:Ei(n,r)})}o=fu.lastIndex}if(o<t.length){i=t.slice(o);a[s]?a[s]+=i:a[++s]=i}return a.length<2?l[0]?(t=l[0].x,function(e){return t(e)+""}):function(){return t}:(t=l.length,function(e){for(var n,r=0;t>r;++r)a[(n=l[r]).i]=n.x(e);return a.join("")})}function xi(e,t){for(var n,r=ia.interpolators.length;--r>=0&&!(n=ia.interpolators[r](e,t)););return n}function bi(e,t){var n,r=[],i=[],o=e.length,s=t.length,a=Math.min(e.length,t.length);for(n=0;a>n;++n)r.push(xi(e[n],t[n]));for(;o>n;++n)i[n]=e[n];for(;s>n;++n)i[n]=t[n];return function(e){for(n=0;a>n;++n)i[n]=r[n](e);return i}}function Ti(e){return function(t){return 0>=t?0:t>=1?1:e(t)}}function Si(e){return function(t){return 1-e(1-t)}}function Ni(e){return function(t){return.5*(.5>t?e(2*t):2-e(2-2*t))}}function Ci(e){return e*e}function Li(e){return e*e*e}function Ai(e){if(0>=e)return 0;if(e>=1)return 1;var t=e*e,n=t*e;return 4*(.5>e?n:3*(e-t)+n-.75)}function Ii(e){return function(t){return Math.pow(t,e)}}function wi(e){return 1-Math.cos(e*Ba)}function Ri(e){return Math.pow(2,10*(e-1))}function Oi(e){return 1-Math.sqrt(1-e*e)}function _i(e,t){var n;arguments.length<2&&(t=.45);arguments.length?n=t/Ga*Math.asin(1/e):(e=1,n=t/4);return function(r){return 1+e*Math.pow(2,-10*r)*Math.sin((r-n)*Ga/t)}}function Di(e){e||(e=1.70158);return function(t){return t*t*((e+1)*t-e)}}function Fi(e){return 1/2.75>e?7.5625*e*e:2/2.75>e?7.5625*(e-=1.5/2.75)*e+.75:2.5/2.75>e?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ki(e,t){e=ia.hcl(e);t=ia.hcl(t);var n=e.h,r=e.c,i=e.l,o=t.h-n,s=t.c-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.c:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return pt(n+o*e,r+s*e,i+a*e)+""}}function Pi(e,t){e=ia.hsl(e);t=ia.hsl(t);var n=e.h,r=e.s,i=e.l,o=t.h-n,s=t.s-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.s:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return ut(n+o*e,r+s*e,i+a*e)+""}}function Mi(e,t){e=ia.lab(e);t=ia.lab(t);var n=e.l,r=e.a,i=e.b,o=t.l-n,s=t.a-r,a=t.b-i;return function(e){return ft(n+o*e,r+s*e,i+a*e)+""}}function ji(e,t){t-=e;return function(n){return Math.round(e+t*n)}}function Gi(e){var t=[e.a,e.b],n=[e.c,e.d],r=Bi(t),i=Ui(t,n),o=Bi(qi(n,t,-i))||0;if(t[0]*n[1]<n[0]*t[1]){t[0]*=-1;t[1]*=-1;r*=-1;i*=-1}this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-n[0],n[1]))*Ha;this.translate=[e.e,e.f];this.scale=[r,o];this.skew=o?Math.atan2(i,o)*Ha:0}function Ui(e,t){return e[0]*t[0]+e[1]*t[1]}function Bi(e){var t=Math.sqrt(Ui(e,e));if(t){e[0]/=t;e[1]/=t}return t}function qi(e,t,n){e[0]+=n*t[0];e[1]+=n*t[1];return e}function Hi(e,t){var n,r=[],i=[],o=ia.transform(e),s=ia.transform(t),a=o.translate,l=s.translate,u=o.rotate,c=s.rotate,p=o.skew,d=s.skew,f=o.scale,h=s.scale;if(a[0]!=l[0]||a[1]!=l[1]){r.push("translate(",null,",",null,")");i.push({i:1,x:Ei(a[0],l[0])},{i:3,x:Ei(a[1],l[1])})}else r.push(l[0]||l[1]?"translate("+l+")":"");if(u!=c){u-c>180?c+=360:c-u>180&&(u+=360);i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:Ei(u,c)})}else c&&r.push(r.pop()+"rotate("+c+")");p!=d?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:Ei(p,d)}):d&&r.push(r.pop()+"skewX("+d+")");if(f[0]!=h[0]||f[1]!=h[1]){n=r.push(r.pop()+"scale(",null,",",null,")");i.push({i:n-4,x:Ei(f[0],h[0])},{i:n-2,x:Ei(f[1],h[1])})}else(1!=h[0]||1!=h[1])&&r.push(r.pop()+"scale("+h+")");n=i.length;return function(e){for(var t,o=-1;++o<n;)r[(t=i[o]).i]=t.x(e);return r.join("")}}function Vi(e,t){t=(t-=e=+e)||1/t;return function(n){return(n-e)/t}}function Wi(e,t){t=(t-=e=+e)||1/t;return function(n){return Math.max(0,Math.min(1,(n-e)/t))}}function zi(e){for(var t=e.source,n=e.target,r=Xi(t,n),i=[t];t!==r;){t=t.parent;i.push(t)}for(var o=i.length;n!==r;){i.splice(o,0,n);n=n.parent}return i}function $i(e){for(var t=[],n=e.parent;null!=n;){t.push(e);e=n;n=n.parent}t.push(e);return t}function Xi(e,t){if(e===t)return e;for(var n=$i(e),r=$i(t),i=n.pop(),o=r.pop(),s=null;i===o;){s=i;i=n.pop();o=r.pop()}return s}function Yi(e){e.fixed|=2}function Ki(e){e.fixed&=-7}function Qi(e){e.fixed|=4;e.px=e.x,e.py=e.y}function Ji(e){e.fixed&=-5}function Zi(e,t,n){var r=0,i=0;e.charge=0;if(!e.leaf)for(var o,s=e.nodes,a=s.length,l=-1;++l<a;){o=s[l];if(null!=o){Zi(o,t,n);e.charge+=o.charge;r+=o.charge*o.cx;i+=o.charge*o.cy}}if(e.point){if(!e.leaf){e.point.x+=Math.random()-.5;e.point.y+=Math.random()-.5}var u=t*n[e.point.index];e.charge+=e.pointCharge=u;r+=u*e.point.x;i+=u*e.point.y}e.cx=r/e.charge;e.cy=i/e.charge}function eo(e,t){ia.rebind(e,t,"sort","children","value");e.nodes=e;e.links=so;return e}function to(e,t){for(var n=[e];null!=(e=n.pop());){t(e);if((i=e.children)&&(r=i.length))for(var r,i;--r>=0;)n.push(i[r])}}function no(e,t){for(var n=[e],r=[];null!=(e=n.pop());){r.push(e);if((o=e.children)&&(i=o.length))for(var i,o,s=-1;++s<i;)n.push(o[s])}for(;null!=(e=r.pop());)t(e)}function ro(e){return e.children}function io(e){return e.value}function oo(e,t){return t.value-e.value}function so(e){return ia.merge(e.map(function(e){return(e.children||[]).map(function(t){return{source:e,target:t}})}))}function ao(e){return e.x}function lo(e){return e.y}function uo(e,t,n){e.y0=t;e.y=n}function co(e){return ia.range(e.length)}function po(e){for(var t=-1,n=e[0].length,r=[];++t<n;)r[t]=0;return r}function fo(e){for(var t,n=1,r=0,i=e[0][1],o=e.length;o>n;++n)if((t=e[n][1])>i){r=n;i=t}return r}function ho(e){return e.reduce(go,0)}function go(e,t){return e+t[1]}function mo(e,t){return vo(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function vo(e,t){for(var n=-1,r=+e[0],i=(e[1]-r)/t,o=[];++n<=t;)o[n]=i*n+r;return o}function Eo(e){return[ia.min(e),ia.max(e)]}function yo(e,t){return e.value-t.value}function xo(e,t){var n=e._pack_next;e._pack_next=t;t._pack_prev=e;t._pack_next=n;n._pack_prev=t}function bo(e,t){e._pack_next=t;t._pack_prev=e}function To(e,t){var n=t.x-e.x,r=t.y-e.y,i=e.r+t.r;return.999*i*i>n*n+r*r}function So(e){function t(e){c=Math.min(e.x-e.r,c);p=Math.max(e.x+e.r,p);d=Math.min(e.y-e.r,d);f=Math.max(e.y+e.r,f)}if((n=e.children)&&(u=n.length)){var n,r,i,o,s,a,l,u,c=1/0,p=-1/0,d=1/0,f=-1/0;n.forEach(No);r=n[0];r.x=-r.r;r.y=0;t(r);if(u>1){i=n[1];i.x=i.r;i.y=0;t(i);if(u>2){o=n[2];Ao(r,i,o);t(o);xo(r,o);r._pack_prev=o;xo(o,i);i=r._pack_next;for(s=3;u>s;s++){Ao(r,i,o=n[s]);var h=0,g=1,m=1;for(a=i._pack_next;a!==i;a=a._pack_next,g++)if(To(a,o)){h=1;break}if(1==h)for(l=r._pack_prev;l!==a._pack_prev&&!To(l,o);l=l._pack_prev,m++);if(h){m>g||g==m&&i.r<r.r?bo(r,i=a):bo(r=l,i);s--}else{xo(r,o);i=o;t(o)}}}}var v=(c+p)/2,E=(d+f)/2,y=0;for(s=0;u>s;s++){o=n[s];o.x-=v;o.y-=E;y=Math.max(y,o.r+Math.sqrt(o.x*o.x+o.y*o.y))}e.r=y;n.forEach(Co)}}function No(e){e._pack_next=e._pack_prev=e}function Co(e){delete e._pack_next;delete e._pack_prev}function Lo(e,t,n,r){var i=e.children;e.x=t+=r*e.x;e.y=n+=r*e.y;e.r*=r;if(i)for(var o=-1,s=i.length;++o<s;)Lo(i[o],t,n,r)}function Ao(e,t,n){var r=e.r+n.r,i=t.x-e.x,o=t.y-e.y;if(r&&(i||o)){var s=t.r+n.r,a=i*i+o*o;s*=s;r*=r;var l=.5+(r-s)/(2*a),u=Math.sqrt(Math.max(0,2*s*(r+a)-(r-=a)*r-s*s))/(2*a);n.x=e.x+l*i+u*o;n.y=e.y+l*o-u*i}else{n.x=e.x+r;n.y=e.y}}function Io(e,t){return e.parent==t.parent?1:2}function wo(e){var t=e.children;return t.length?t[0]:e.t}function Ro(e){var t,n=e.children;return(t=n.length)?n[t-1]:e.t}function Oo(e,t,n){var r=n/(t.i-e.i);t.c-=r;t.s+=n;e.c+=r;t.z+=n;t.m+=n}function _o(e){for(var t,n=0,r=0,i=e.children,o=i.length;--o>=0;){t=i[o];t.z+=n;t.m+=n;n+=t.s+(r+=t.c)}}function Do(e,t,n){return e.a.parent===t.parent?e.a:n}function Fo(e){return 1+ia.max(e,function(e){return e.y})}function ko(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}function Po(e){var t=e.children;return t&&t.length?Po(t[0]):e}function Mo(e){var t,n=e.children;return n&&(t=n.length)?Mo(n[t-1]):e}function jo(e){return{x:e.x,y:e.y,dx:e.dx,dy:e.dy}}function Go(e,t){var n=e.x+t[3],r=e.y+t[0],i=e.dx-t[1]-t[3],o=e.dy-t[0]-t[2];if(0>i){n+=i/2;i=0}if(0>o){r+=o/2;o=0}return{x:n,y:r,dx:i,dy:o}}function Uo(e){var t=e[0],n=e[e.length-1];return n>t?[t,n]:[n,t]}function Bo(e){return e.rangeExtent?e.rangeExtent():Uo(e.range())}function qo(e,t,n,r){var i=n(e[0],e[1]),o=r(t[0],t[1]);return function(e){return o(i(e))}}function Ho(e,t){var n,r=0,i=e.length-1,o=e[r],s=e[i];if(o>s){n=r,r=i,i=n;n=o,o=s,s=n}e[r]=t.floor(o);e[i]=t.ceil(s);return e}function Vo(e){return e?{floor:function(t){return Math.floor(t/e)*e},ceil:function(t){return Math.ceil(t/e)*e}}:Nu}function Wo(e,t,n,r){var i=[],o=[],s=0,a=Math.min(e.length,t.length)-1;if(e[a]<e[0]){e=e.slice().reverse();t=t.slice().reverse()}for(;++s<=a;){i.push(n(e[s-1],e[s]));o.push(r(t[s-1],t[s]))}return function(t){var n=ia.bisect(e,t,1,a)-1;return o[n](i[n](t))}}function zo(e,t,n,r){function i(){var i=Math.min(e.length,t.length)>2?Wo:qo,l=r?Wi:Vi;s=i(e,t,l,n);a=i(t,e,l,xi);return o}function o(e){return s(e)}var s,a;o.invert=function(e){return a(e)};o.domain=function(t){if(!arguments.length)return e;e=t.map(Number);return i()};o.range=function(e){if(!arguments.length)return t;t=e;return i()};o.rangeRound=function(e){return o.range(e).interpolate(ji)};o.clamp=function(e){if(!arguments.length)return r;r=e;return i()};o.interpolate=function(e){if(!arguments.length)return n;n=e;return i()};o.ticks=function(t){return Ko(e,t)};o.tickFormat=function(t,n){return Qo(e,t,n)};o.nice=function(t){Xo(e,t);return i()};o.copy=function(){return zo(e,t,n,r)};return i()}function $o(e,t){return ia.rebind(e,t,"range","rangeRound","interpolate","clamp")}function Xo(e,t){return Ho(e,Vo(Yo(e,t)[2]))}function Yo(e,t){null==t&&(t=10);var n=Uo(e),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),o=t/r*i;.15>=o?i*=10:.35>=o?i*=5:.75>=o&&(i*=2);n[0]=Math.ceil(n[0]/i)*i;n[1]=Math.floor(n[1]/i)*i+.5*i;n[2]=i;return n}function Ko(e,t){return ia.range.apply(ia,Yo(e,t))}function Qo(e,t,n){var r=Yo(e,t);if(n){var i=dl.exec(n);i.shift();if("s"===i[8]){var o=ia.formatPrefix(Math.max(Ea(r[0]),Ea(r[1])));i[7]||(i[7]="."+Jo(o.scale(r[2])));i[8]="f";n=ia.format(i.join(""));return function(e){return n(o.scale(e))+o.symbol}}i[7]||(i[7]="."+Zo(i[8],r));n=i.join("")}else n=",."+Jo(r[2])+"f";return ia.format(n)}function Jo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}function Zo(e,t){var n=Jo(t[2]);return e in Cu?Math.abs(n-Jo(Math.max(Ea(t[0]),Ea(t[1]))))+ +("e"!==e):n-2*("%"===e)}function es(e,t,n,r){function i(e){return(n?Math.log(0>e?0:e):-Math.log(e>0?0:-e))/Math.log(t)}function o(e){return n?Math.pow(t,e):-Math.pow(t,-e)}function s(t){return e(i(t))}s.invert=function(t){return o(e.invert(t))};s.domain=function(t){if(!arguments.length)return r;n=t[0]>=0;e.domain((r=t.map(Number)).map(i));return s};s.base=function(n){if(!arguments.length)return t;t=+n;e.domain(r.map(i));return s};s.nice=function(){var t=Ho(r.map(i),n?Math:Au);e.domain(t);r=t.map(o);return s};s.ticks=function(){var e=Uo(r),s=[],a=e[0],l=e[1],u=Math.floor(i(a)),c=Math.ceil(i(l)),p=t%1?2:t;if(isFinite(c-u)){if(n){for(;c>u;u++)for(var d=1;p>d;d++)s.push(o(u)*d);s.push(o(u))}else{s.push(o(u));for(;u++<c;)for(var d=p-1;d>0;d--)s.push(o(u)*d)}for(u=0;s[u]<a;u++);for(c=s.length;s[c-1]>l;c--);s=s.slice(u,c)}return s};s.tickFormat=function(e,t){if(!arguments.length)return Lu;arguments.length<2?t=Lu:"function"!=typeof t&&(t=ia.format(t));var r,a=Math.max(.1,e/s.ticks().length),l=n?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(e){return e/o(l(i(e)+r))<=a?t(e):""}};s.copy=function(){return es(e.copy(),t,n,r)};return $o(s,e)}function ts(e,t,n){function r(t){return e(i(t))}var i=ns(t),o=ns(1/t);r.invert=function(t){return o(e.invert(t))};r.domain=function(t){if(!arguments.length)return n;e.domain((n=t.map(Number)).map(i));return r};r.ticks=function(e){return Ko(n,e)};r.tickFormat=function(e,t){return Qo(n,e,t)};r.nice=function(e){return r.domain(Xo(n,e))};r.exponent=function(s){if(!arguments.length)return t;i=ns(t=s);o=ns(1/t);e.domain(n.map(i));return r};r.copy=function(){return ts(e.copy(),t,n)};return $o(r,e)}function ns(e){return function(t){return 0>t?-Math.pow(-t,e):Math.pow(t,e)}}function rs(e,t){function n(n){return o[((i.get(n)||("range"===t.t?i.set(n,e.push(n)):0/0))-1)%o.length]}function r(t,n){return ia.range(e.length).map(function(e){return t+n*e})}var i,o,s;n.domain=function(r){if(!arguments.length)return e;e=[];i=new u;for(var o,s=-1,a=r.length;++s<a;)i.has(o=r[s])||i.set(o,e.push(o));return n[t.t].apply(n,t.a)};n.range=function(e){if(!arguments.length)return o;o=e;s=0;t={t:"range",a:arguments};return n};n.rangePoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],c=e.length<2?(l=(l+u)/2,0):(u-l)/(e.length-1+a);o=r(l+c*a/2,c);s=0;t={t:"rangePoints",a:arguments};return n};n.rangeRoundPoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],c=e.length<2?(l=u=Math.round((l+u)/2),0):(u-l)/(e.length-1+a)|0;o=r(l+Math.round(c*a/2+(u-l-(e.length-1+a)*c)/2),c);s=0;t={t:"rangeRoundPoints",a:arguments};return n};n.rangeBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],c=i[u-0],p=i[1-u],d=(p-c)/(e.length-a+2*l);o=r(c+d*l,d);u&&o.reverse();s=d*(1-a);t={t:"rangeBands",a:arguments};return n};n.rangeRoundBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],c=i[u-0],p=i[1-u],d=Math.floor((p-c)/(e.length-a+2*l));o=r(c+Math.round((p-c-(e.length-a)*d)/2),d);u&&o.reverse();s=Math.round(d*(1-a));t={t:"rangeRoundBands",a:arguments};return n};n.rangeBand=function(){return s};n.rangeExtent=function(){return Uo(t.a[0])};n.copy=function(){return rs(e,t)};return n.domain(e)}function is(e,n){function o(){var t=0,r=n.length;a=[];for(;++t<r;)a[t-1]=ia.quantile(e,t/r);return s}function s(e){return isNaN(e=+e)?void 0:n[ia.bisect(a,e)]}var a;s.domain=function(n){if(!arguments.length)return e;e=n.map(r).filter(i).sort(t);return o()};s.range=function(e){if(!arguments.length)return n;n=e;return o()};s.quantiles=function(){return a};s.invertExtent=function(t){t=n.indexOf(t);return 0>t?[0/0,0/0]:[t>0?a[t-1]:e[0],t<a.length?a[t]:e[e.length-1]]};s.copy=function(){return is(e,n)};return o()}function os(e,t,n){function r(t){return n[Math.max(0,Math.min(s,Math.floor(o*(t-e))))]}function i(){o=n.length/(t-e);s=n.length-1;return r}var o,s;r.domain=function(n){if(!arguments.length)return[e,t];e=+n[0];t=+n[n.length-1];return i()};r.range=function(e){if(!arguments.length)return n;n=e;return i()};r.invertExtent=function(t){t=n.indexOf(t);t=0>t?0/0:t/o+e;return[t,t+1/o]};r.copy=function(){return os(e,t,n)};return i()}function ss(e,t){function n(n){return n>=n?t[ia.bisect(e,n)]:void 0}n.domain=function(t){if(!arguments.length)return e;e=t;return n};n.range=function(e){if(!arguments.length)return t;t=e;return n};n.invertExtent=function(n){n=t.indexOf(n);return[e[n-1],e[n]]};n.copy=function(){return ss(e,t)};return n}function as(e){function t(e){return+e}t.invert=t;t.domain=t.range=function(n){if(!arguments.length)return e;e=n.map(t);return t};t.ticks=function(t){return Ko(e,t)};t.tickFormat=function(t,n){return Qo(e,t,n)};t.copy=function(){return as(e)};return t}function ls(){return 0}function us(e){return e.innerRadius}function cs(e){return e.outerRadius}function ps(e){return e.startAngle}function ds(e){return e.endAngle}function fs(e){return e&&e.padAngle}function hs(e,t,n,r){return(e-n)*t-(t-r)*e>0?0:1}function gs(e,t,n,r,i){var o=e[0]-t[0],s=e[1]-t[1],a=(i?r:-r)/Math.sqrt(o*o+s*s),l=a*s,u=-a*o,c=e[0]+l,p=e[1]+u,d=t[0]+l,f=t[1]+u,h=(c+d)/2,g=(p+f)/2,m=d-c,v=f-p,E=m*m+v*v,y=n-r,x=c*f-d*p,b=(0>v?-1:1)*Math.sqrt(y*y*E-x*x),T=(x*v-m*b)/E,S=(-x*m-v*b)/E,N=(x*v+m*b)/E,C=(-x*m+v*b)/E,L=T-h,A=S-g,I=N-h,w=C-g;L*L+A*A>I*I+w*w&&(T=N,S=C);return[[T-l,S-u],[T*n/y,S*n/y]]}function ms(e){function t(t){function s(){u.push("M",o(e(c),a))}for(var l,u=[],c=[],p=-1,d=t.length,f=At(n),h=At(r);++p<d;)if(i.call(this,l=t[p],p))c.push([+f.call(this,l,p),+h.call(this,l,p)]);else if(c.length){s();c=[]}c.length&&s();return u.length?u.join(""):null}var n=Rr,r=Or,i=On,o=vs,s=o.key,a=.7;t.x=function(e){if(!arguments.length)return n;n=e;return t};t.y=function(e){if(!arguments.length)return r;r=e;return t};t.defined=function(e){if(!arguments.length)return i;i=e;return t};t.interpolate=function(e){if(!arguments.length)return s;s="function"==typeof e?o=e:(o=Du.get(e)||vs).key;return t};t.tension=function(e){if(!arguments.length)return a;a=e;return t};return t}function vs(e){return e.join("L")}function Es(e){return vs(e)+"Z"}function ys(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r[0]+(r=e[t])[0])/2,"V",r[1]);n>1&&i.push("H",r[0]);return i.join("")}function xs(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("V",(r=e[t])[1],"H",r[0]);return i.join("")}function bs(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r=e[t])[0],"V",r[1]);return i.join("")}function Ts(e,t){return e.length<4?vs(e):e[1]+Cs(e.slice(1,-1),Ls(e,t))}function Ss(e,t){return e.length<3?vs(e):e[0]+Cs((e.push(e[0]),e),Ls([e[e.length-2]].concat(e,[e[1]]),t))}function Ns(e,t){return e.length<3?vs(e):e[0]+Cs(e,Ls(e,t))}function Cs(e,t){if(t.length<1||e.length!=t.length&&e.length!=t.length+2)return vs(e);var n=e.length!=t.length,r="",i=e[0],o=e[1],s=t[0],a=s,l=1;if(n){r+="Q"+(o[0]-2*s[0]/3)+","+(o[1]-2*s[1]/3)+","+o[0]+","+o[1];i=e[1];l=2}if(t.length>1){a=t[1];o=e[l];l++;r+="C"+(i[0]+s[0])+","+(i[1]+s[1])+","+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1];for(var u=2;u<t.length;u++,l++){o=e[l];a=t[u];r+="S"+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1]}}if(n){var c=e[l];r+="Q"+(o[0]+2*a[0]/3)+","+(o[1]+2*a[1]/3)+","+c[0]+","+c[1]}return r}function Ls(e,t){for(var n,r=[],i=(1-t)/2,o=e[0],s=e[1],a=1,l=e.length;++a<l;){n=o;o=s;s=e[a];r.push([i*(s[0]-n[0]),i*(s[1]-n[1])])}return r}function As(e){if(e.length<3)return vs(e);var t=1,n=e.length,r=e[0],i=r[0],o=r[1],s=[i,i,i,(r=e[1])[0]],a=[o,o,o,r[1]],l=[i,",",o,"L",Os(Pu,s),",",Os(Pu,a)];e.push(e[n-1]);for(;++t<=n;){r=e[t];s.shift();s.push(r[0]);a.shift();a.push(r[1]);_s(l,s,a)}e.pop();l.push("L",r);return l.join("")}function Is(e){if(e.length<4)return vs(e);for(var t,n=[],r=-1,i=e.length,o=[0],s=[0];++r<3;){t=e[r];o.push(t[0]);s.push(t[1])}n.push(Os(Pu,o)+","+Os(Pu,s));--r;for(;++r<i;){t=e[r];o.shift();o.push(t[0]);s.shift();s.push(t[1]);_s(n,o,s)}return n.join("")}function ws(e){for(var t,n,r=-1,i=e.length,o=i+4,s=[],a=[];++r<4;){n=e[r%i];s.push(n[0]);a.push(n[1])}t=[Os(Pu,s),",",Os(Pu,a)];--r;for(;++r<o;){n=e[r%i];s.shift();s.push(n[0]);a.shift();a.push(n[1]);_s(t,s,a)}return t.join("")}function Rs(e,t){var n=e.length-1;if(n)for(var r,i,o=e[0][0],s=e[0][1],a=e[n][0]-o,l=e[n][1]-s,u=-1;++u<=n;){r=e[u];i=u/n;r[0]=t*r[0]+(1-t)*(o+i*a);r[1]=t*r[1]+(1-t)*(s+i*l)}return As(e)}function Os(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function _s(e,t,n){e.push("C",Os(Fu,t),",",Os(Fu,n),",",Os(ku,t),",",Os(ku,n),",",Os(Pu,t),",",Os(Pu,n))}function Ds(e,t){return(t[1]-e[1])/(t[0]-e[0])}function Fs(e){for(var t=0,n=e.length-1,r=[],i=e[0],o=e[1],s=r[0]=Ds(i,o);++t<n;)r[t]=(s+(s=Ds(i=o,o=e[t+1])))/2;r[t]=s;return r}function ks(e){for(var t,n,r,i,o=[],s=Fs(e),a=-1,l=e.length-1;++a<l;){t=Ds(e[a],e[a+1]);if(Ea(t)<Pa)s[a]=s[a+1]=0;else{n=s[a]/t;r=s[a+1]/t;i=n*n+r*r;if(i>9){i=3*t/Math.sqrt(i);s[a]=i*n;s[a+1]=i*r}}}a=-1;for(;++a<=l;){i=(e[Math.min(l,a+1)][0]-e[Math.max(0,a-1)][0])/(6*(1+s[a]*s[a]));o.push([i||0,s[a]*i||0])}return o}function Ps(e){return e.length<3?vs(e):e[0]+Cs(e,ks(e))}function Ms(e){for(var t,n,r,i=-1,o=e.length;++i<o;){t=e[i];n=t[0];r=t[1]-Ba;t[0]=n*Math.cos(r);t[1]=n*Math.sin(r)}return e}function js(e){function t(t){function l(){g.push("M",a(e(v),p),c,u(e(m.reverse()),p),"Z")}for(var d,f,h,g=[],m=[],v=[],E=-1,y=t.length,x=At(n),b=At(i),T=n===r?function(){return f}:At(r),S=i===o?function(){return h}:At(o);++E<y;)if(s.call(this,d=t[E],E)){m.push([f=+x.call(this,d,E),h=+b.call(this,d,E)]);v.push([+T.call(this,d,E),+S.call(this,d,E)])}else if(m.length){l();m=[];v=[]}m.length&&l();return g.length?g.join(""):null}var n=Rr,r=Rr,i=0,o=Or,s=On,a=vs,l=a.key,u=a,c="L",p=.7;t.x=function(e){if(!arguments.length)return r;n=r=e;return t};t.x0=function(e){if(!arguments.length)return n;n=e;return t};t.x1=function(e){if(!arguments.length)return r;r=e;return t};t.y=function(e){if(!arguments.length)return o;i=o=e;return t};t.y0=function(e){if(!arguments.length)return i;i=e;return t};t.y1=function(e){if(!arguments.length)return o;o=e;return t};t.defined=function(e){if(!arguments.length)return s;s=e;return t};t.interpolate=function(e){if(!arguments.length)return l;l="function"==typeof e?a=e:(a=Du.get(e)||vs).key;u=a.reverse||a;c=a.closed?"M":"L";return t};t.tension=function(e){if(!arguments.length)return p;p=e;return t};return t}function Gs(e){return e.radius}function Us(e){return[e.x,e.y]}function Bs(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ba;return[n*Math.cos(r),n*Math.sin(r)]}}function qs(){return 64}function Hs(){return"circle"}function Vs(e){var t=Math.sqrt(e/ja);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function Ws(e){return function(){var t,n;if((t=this[e])&&(n=t[t.active])){--t.count?delete t[t.active]:delete this[e];t.active+=.5;n.event&&n.event.interrupt.call(this,this.__data__,n.index)}}}function zs(e,t,n){Sa(e,Hu);e.namespace=t;e.id=n;return e}function $s(e,t,n,r){var i=e.id,o=e.namespace;return q(e,"function"==typeof n?function(e,s,a){e[o][i].tween.set(t,r(n.call(e,e.__data__,s,a)))}:(n=r(n),function(e){e[o][i].tween.set(t,n)}))}function Xs(e){null==e&&(e="");return function(){this.textContent=e}}function Ys(e){return null==e?"__transition__":"__transition_"+e+"__"}function Ks(e,t,n,r,i){var o=e[n]||(e[n]={active:0,count:0}),s=o[r];if(!s){var a=i.time;s=o[r]={tween:new u,time:a,delay:i.delay,duration:i.duration,ease:i.ease,index:t};i=null;++o.count;ia.timer(function(i){function l(n){if(o.active>r)return c();var i=o[o.active];if(i){--o.count;delete o[o.active];i.event&&i.event.interrupt.call(e,e.__data__,i.index)}o.active=r;s.event&&s.event.start.call(e,e.__data__,t);s.tween.forEach(function(n,r){(r=r.call(e,e.__data__,t))&&g.push(r)});d=s.ease;p=s.duration;ia.timer(function(){h.c=u(n||1)?On:u;return 1},0,a)}function u(n){if(o.active!==r)return 1;for(var i=n/p,a=d(i),l=g.length;l>0;)g[--l].call(e,a);if(i>=1){s.event&&s.event.end.call(e,e.__data__,t);return c()}}function c(){--o.count?delete o[r]:delete e[n];return 1}var p,d,f=s.delay,h=ul,g=[];h.t=f+a;if(i>=f)return l(i-f);h.c=l;return void 0},0,a)}}function Qs(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate("+(isFinite(r)?r:n(e))+",0)"})}function Js(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate(0,"+(isFinite(r)?r:n(e))+")"})}function Zs(e){return e.toISOString()}function ea(e,t,n){function r(t){return e(t)}function i(e,n){var r=e[1]-e[0],i=r/n,o=ia.bisect(Ju,i);return o==Ju.length?[t.year,Yo(e.map(function(e){return e/31536e6}),n)[2]]:o?t[i/Ju[o-1]<Ju[o]/i?o-1:o]:[tc,Yo(e,n)[2]]}r.invert=function(t){return ta(e.invert(t))};r.domain=function(t){if(!arguments.length)return e.domain().map(ta);e.domain(t);return r};r.nice=function(e,t){function n(n){return!isNaN(n)&&!e.range(n,ta(+n+1),t).length}var o=r.domain(),s=Uo(o),a=null==e?i(s,10):"number"==typeof e&&i(s,e);a&&(e=a[0],t=a[1]);return r.domain(Ho(o,t>1?{floor:function(t){for(;n(t=e.floor(t));)t=ta(t-1);return t},ceil:function(t){for(;n(t=e.ceil(t));)t=ta(+t+1);return t}}:e))};r.ticks=function(e,t){var n=Uo(r.domain()),o=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];o&&(e=o[0],t=o[1]);return e.range(n[0],ta(+n[1]+1),1>t?1:t)};r.tickFormat=function(){return n};r.copy=function(){return ea(e.copy(),t,n)};return $o(r,e)}function ta(e){return new Date(e)}function na(e){return JSON.parse(e.responseText)}function ra(e){var t=aa.createRange();t.selectNode(aa.body);return t.createContextualFragment(e.responseText)}var ia={version:"3.5.3"};Date.now||(Date.now=function(){return+new Date});var oa=[].slice,sa=function(e){return oa.call(e)},aa=document,la=aa.documentElement,ua=window;try{sa(la.childNodes)[0].nodeType}catch(ca){sa=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}try{aa.createElement("div").style.setProperty("opacity",0,"")}catch(pa){var da=ua.Element.prototype,fa=da.setAttribute,ha=da.setAttributeNS,ga=ua.CSSStyleDeclaration.prototype,ma=ga.setProperty;da.setAttribute=function(e,t){fa.call(this,e,t+"")};da.setAttributeNS=function(e,t,n){ha.call(this,e,t,n+"")};ga.setProperty=function(e,t,n){ma.call(this,e,t+"",n)}}ia.ascending=t;ia.descending=function(e,t){return e>t?-1:t>e?1:t>=e?0:0/0};ia.min=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&n>r&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&n>r&&(n=r)}return n};ia.max=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&r>n&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&r>n&&(n=r)}return n};ia.extent=function(e,t){var n,r,i,o=-1,s=e.length;if(1===arguments.length){for(;++o<s;)if(null!=(r=e[o])&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=e[o])){n>r&&(n=r);r>i&&(i=r)}}else{for(;++o<s;)if(null!=(r=t.call(e,e[o],o))&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=t.call(e,e[o],o))){n>r&&(n=r);r>i&&(i=r)}}return[n,i]};ia.sum=function(e,t){var n,r=0,o=e.length,s=-1;if(1===arguments.length)for(;++s<o;)i(n=+e[s])&&(r+=n);else for(;++s<o;)i(n=+t.call(e,e[s],s))&&(r+=n);return r};ia.mean=function(e,t){var n,o=0,s=e.length,a=-1,l=s;if(1===arguments.length)for(;++a<s;)i(n=r(e[a]))?o+=n:--l;else for(;++a<s;)i(n=r(t.call(e,e[a],a)))?o+=n:--l;return l?o/l:void 0};ia.quantile=function(e,t){var n=(e.length-1)*t+1,r=Math.floor(n),i=+e[r-1],o=n-r;return o?i+o*(e[r]-i):i};ia.median=function(e,n){var o,s=[],a=e.length,l=-1;
if(1===arguments.length)for(;++l<a;)i(o=r(e[l]))&&s.push(o);else for(;++l<a;)i(o=r(n.call(e,e[l],l)))&&s.push(o);return s.length?ia.quantile(s.sort(t),.5):void 0};ia.variance=function(e,t){var n,o,s=e.length,a=0,l=0,u=-1,c=0;if(1===arguments.length){for(;++u<s;)if(i(n=r(e[u]))){o=n-a;a+=o/++c;l+=o*(n-a)}}else for(;++u<s;)if(i(n=r(t.call(e,e[u],u)))){o=n-a;a+=o/++c;l+=o*(n-a)}return c>1?l/(c-1):void 0};ia.deviation=function(){var e=ia.variance.apply(this,arguments);return e?Math.sqrt(e):e};var va=o(t);ia.bisectLeft=va.left;ia.bisect=ia.bisectRight=va.right;ia.bisector=function(e){return o(1===e.length?function(n,r){return t(e(n),r)}:e)};ia.shuffle=function(e,t,n){if((o=arguments.length)<3){n=e.length;2>o&&(t=0)}for(var r,i,o=n-t;o;){i=Math.random()*o--|0;r=e[o+t],e[o+t]=e[i+t],e[i+t]=r}return e};ia.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r};ia.pairs=function(e){for(var t,n=0,r=e.length-1,i=e[0],o=new Array(0>r?0:r);r>n;)o[n]=[t=i,i=e[++n]];return o};ia.zip=function(){if(!(r=arguments.length))return[];for(var e=-1,t=ia.min(arguments,s),n=new Array(t);++e<t;)for(var r,i=-1,o=n[e]=new Array(r);++i<r;)o[i]=arguments[i][e];return n};ia.transpose=function(e){return ia.zip.apply(ia,e)};ia.keys=function(e){var t=[];for(var n in e)t.push(n);return t};ia.values=function(e){var t=[];for(var n in e)t.push(e[n]);return t};ia.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t};ia.merge=function(e){for(var t,n,r,i=e.length,o=-1,s=0;++o<i;)s+=e[o].length;n=new Array(s);for(;--i>=0;){r=e[i];t=r.length;for(;--t>=0;)n[--s]=r[t]}return n};var Ea=Math.abs;ia.range=function(e,t,n){if(arguments.length<3){n=1;if(arguments.length<2){t=e;e=0}}if((t-e)/n===1/0)throw new Error("infinite range");var r,i=[],o=a(Ea(n)),s=-1;e*=o,t*=o,n*=o;if(0>n)for(;(r=e+n*++s)>t;)i.push(r/o);else for(;(r=e+n*++s)<t;)i.push(r/o);return i};ia.map=function(e,t){var n=new u;if(e instanceof u)e.forEach(function(e,t){n.set(e,t)});else if(Array.isArray(e)){var r,i=-1,o=e.length;if(1===arguments.length)for(;++i<o;)n.set(i,e[i]);else for(;++i<o;)n.set(t.call(e,r=e[i],i),r)}else for(var s in e)n.set(s,e[s]);return n};var ya="__proto__",xa="\x00";l(u,{has:d,get:function(e){return this._[c(e)]},set:function(e,t){return this._[c(e)]=t},remove:f,keys:h,values:function(){var e=[];for(var t in this._)e.push(this._[t]);return e},entries:function(){var e=[];for(var t in this._)e.push({key:p(t),value:this._[t]});return e},size:g,empty:m,forEach:function(e){for(var t in this._)e.call(this,p(t),this._[t])}});ia.nest=function(){function e(t,s,a){if(a>=o.length)return r?r.call(i,s):n?s.sort(n):s;for(var l,c,p,d,f=-1,h=s.length,g=o[a++],m=new u;++f<h;)(d=m.get(l=g(c=s[f])))?d.push(c):m.set(l,[c]);if(t){c=t();p=function(n,r){c.set(n,e(t,r,a))}}else{c={};p=function(n,r){c[n]=e(t,r,a)}}m.forEach(p);return c}function t(e,n){if(n>=o.length)return e;var r=[],i=s[n++];e.forEach(function(e,i){r.push({key:e,values:t(i,n)})});return i?r.sort(function(e,t){return i(e.key,t.key)}):r}var n,r,i={},o=[],s=[];i.map=function(t,n){return e(n,t,0)};i.entries=function(n){return t(e(ia.map,n,0),0)};i.key=function(e){o.push(e);return i};i.sortKeys=function(e){s[o.length-1]=e;return i};i.sortValues=function(e){n=e;return i};i.rollup=function(e){r=e;return i};return i};ia.set=function(e){var t=new v;if(e)for(var n=0,r=e.length;r>n;++n)t.add(e[n]);return t};l(v,{has:d,add:function(e){this._[c(e+="")]=!0;return e},remove:f,values:h,size:g,empty:m,forEach:function(e){for(var t in this._)e.call(this,p(t))}});ia.behavior={};ia.rebind=function(e,t){for(var n,r=1,i=arguments.length;++r<i;)e[n=arguments[r]]=E(e,t,t[n]);return e};var ba=["webkit","ms","moz","Moz","o","O"];ia.dispatch=function(){for(var e=new b,t=-1,n=arguments.length;++t<n;)e[arguments[t]]=T(e);return e};b.prototype.on=function(e,t){var n=e.indexOf("."),r="";if(n>=0){r=e.slice(n+1);e=e.slice(0,n)}if(e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}};ia.event=null;ia.requote=function(e){return e.replace(Ta,"\\$&")};var Ta=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Sa={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]},Na=function(e,t){return t.querySelector(e)},Ca=function(e,t){return t.querySelectorAll(e)},La=la.matches||la[y(la,"matchesSelector")],Aa=function(e,t){return La.call(e,t)};if("function"==typeof Sizzle){Na=function(e,t){return Sizzle(e,t)[0]||null};Ca=Sizzle;Aa=Sizzle.matchesSelector}ia.selection=function(){return Oa};var Ia=ia.selection.prototype=[];Ia.select=function(e){var t,n,r,i,o=[];e=A(e);for(var s=-1,a=this.length;++s<a;){o.push(t=[]);t.parentNode=(r=this[s]).parentNode;for(var l=-1,u=r.length;++l<u;)if(i=r[l]){t.push(n=e.call(i,i.__data__,l,s));n&&"__data__"in i&&(n.__data__=i.__data__)}else t.push(null)}return L(o)};Ia.selectAll=function(e){var t,n,r=[];e=I(e);for(var i=-1,o=this.length;++i<o;)for(var s=this[i],a=-1,l=s.length;++a<l;)if(n=s[a]){r.push(t=sa(e.call(n,n.__data__,a,i)));t.parentNode=n}return L(r)};var wa={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};ia.ns={prefix:wa,qualify:function(e){var t=e.indexOf(":"),n=e;if(t>=0){n=e.slice(0,t);e=e.slice(t+1)}return wa.hasOwnProperty(n)?{space:wa[n],local:e}:e}};Ia.attr=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node();e=ia.ns.qualify(e);return e.local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(t in e)this.each(w(t,e[t]));return this}return this.each(w(e,t))};Ia.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=_(e)).length,i=-1;if(t=n.classList){for(;++i<r;)if(!t.contains(e[i]))return!1}else{t=n.getAttribute("class");for(;++i<r;)if(!O(e[i]).test(t))return!1}return!0}for(t in e)this.each(D(t,e[t]));return this}return this.each(D(e,t))};Ia.style=function(e,t,n){var r=arguments.length;if(3>r){if("string"!=typeof e){2>r&&(t="");for(n in e)this.each(k(n,e[n],t));return this}if(2>r)return ua.getComputedStyle(this.node(),null).getPropertyValue(e);n=""}return this.each(k(e,t,n))};Ia.property=function(e,t){if(arguments.length<2){if("string"==typeof e)return this.node()[e];for(t in e)this.each(P(t,e[t]));return this}return this.each(P(e,t))};Ia.text=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}:null==e?function(){this.textContent=""}:function(){this.textContent=e}):this.node().textContent};Ia.html=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}:null==e?function(){this.innerHTML=""}:function(){this.innerHTML=e}):this.node().innerHTML};Ia.append=function(e){e=M(e);return this.select(function(){return this.appendChild(e.apply(this,arguments))})};Ia.insert=function(e,t){e=M(e);t=A(t);return this.select(function(){return this.insertBefore(e.apply(this,arguments),t.apply(this,arguments)||null)})};Ia.remove=function(){return this.each(j)};Ia.data=function(e,t){function n(e,n){var r,i,o,s=e.length,p=n.length,d=Math.min(s,p),f=new Array(p),h=new Array(p),g=new Array(s);if(t){var m,v=new u,E=new Array(s);for(r=-1;++r<s;){v.has(m=t.call(i=e[r],i.__data__,r))?g[r]=i:v.set(m,i);E[r]=m}for(r=-1;++r<p;){if(i=v.get(m=t.call(n,o=n[r],r))){if(i!==!0){f[r]=i;i.__data__=o}}else h[r]=G(o);v.set(m,!0)}for(r=-1;++r<s;)v.get(E[r])!==!0&&(g[r]=e[r])}else{for(r=-1;++r<d;){i=e[r];o=n[r];if(i){i.__data__=o;f[r]=i}else h[r]=G(o)}for(;p>r;++r)h[r]=G(n[r]);for(;s>r;++r)g[r]=e[r]}h.update=f;h.parentNode=f.parentNode=g.parentNode=e.parentNode;a.push(h);l.push(f);c.push(g)}var r,i,o=-1,s=this.length;if(!arguments.length){e=new Array(s=(r=this[0]).length);for(;++o<s;)(i=r[o])&&(e[o]=i.__data__);return e}var a=H([]),l=L([]),c=L([]);if("function"==typeof e)for(;++o<s;)n(r=this[o],e.call(r,r.parentNode.__data__,o));else for(;++o<s;)n(r=this[o],e);l.enter=function(){return a};l.exit=function(){return c};return l};Ia.datum=function(e){return arguments.length?this.property("__data__",e):this.property("__data__")};Ia.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=U(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);t.parentNode=(n=this[o]).parentNode;for(var a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return L(i)};Ia.order=function(){for(var e=-1,t=this.length;++e<t;)for(var n,r=this[e],i=r.length-1,o=r[i];--i>=0;)if(n=r[i]){o&&o!==n.nextSibling&&o.parentNode.insertBefore(n,o);o=n}return this};Ia.sort=function(e){e=B.apply(this,arguments);for(var t=-1,n=this.length;++t<n;)this[t].sort(e);return this.order()};Ia.each=function(e){return q(this,function(t,n,r){e.call(t,t.__data__,n,r)})};Ia.call=function(e){var t=sa(arguments);e.apply(t[0]=this,t);return this};Ia.empty=function(){return!this.node()};Ia.node=function(){for(var e=0,t=this.length;t>e;e++)for(var n=this[e],r=0,i=n.length;i>r;r++){var o=n[r];if(o)return o}return null};Ia.size=function(){var e=0;q(this,function(){++e});return e};var Ra=[];ia.selection.enter=H;ia.selection.enter.prototype=Ra;Ra.append=Ia.append;Ra.empty=Ia.empty;Ra.node=Ia.node;Ra.call=Ia.call;Ra.size=Ia.size;Ra.select=function(e){for(var t,n,r,i,o,s=[],a=-1,l=this.length;++a<l;){r=(i=this[a]).update;s.push(t=[]);t.parentNode=i.parentNode;for(var u=-1,c=i.length;++u<c;)if(o=i[u]){t.push(r[u]=n=e.call(i.parentNode,o.__data__,u,a));n.__data__=o.__data__}else t.push(null)}return L(s)};Ra.insert=function(e,t){arguments.length<2&&(t=V(this));return Ia.insert.call(this,e,t)};ia.select=function(e){var t=["string"==typeof e?Na(e,aa):e];t.parentNode=la;return L([t])};ia.selectAll=function(e){var t=sa("string"==typeof e?Ca(e,aa):e);t.parentNode=la;return L([t])};var Oa=ia.select(la);Ia.on=function(e,t,n){var r=arguments.length;if(3>r){if("string"!=typeof e){2>r&&(t=!1);for(n in e)this.each(W(n,e[n],t));return this}if(2>r)return(r=this.node()["__on"+e])&&r._;n=!1}return this.each(W(e,t,n))};var _a=ia.map({mouseenter:"mouseover",mouseleave:"mouseout"});_a.forEach(function(e){"on"+e in aa&&_a.remove(e)});var Da="onselectstart"in aa?null:y(la.style,"userSelect"),Fa=0;ia.mouse=function(e){return Y(e,N())};var ka=/WebKit/.test(ua.navigator.userAgent)?-1:0;ia.touch=function(e,t,n){arguments.length<3&&(n=t,t=N().changedTouches);if(t)for(var r,i=0,o=t.length;o>i;++i)if((r=t[i]).identifier===n)return Y(e,r)};ia.behavior.drag=function(){function e(){this.on("mousedown.drag",i).on("touchstart.drag",o)}function t(e,t,i,o,s){return function(){function a(){var e,n,r=t(d,g);if(r){e=r[0]-y[0];n=r[1]-y[1];h|=e|n;y=r;f({type:"drag",x:r[0]+u[0],y:r[1]+u[1],dx:e,dy:n})}}function l(){if(t(d,g)){v.on(o+m,null).on(s+m,null);E(h&&ia.event.target===p);f({type:"dragend"})}}var u,c=this,p=ia.event.target,d=c.parentNode,f=n.of(c,arguments),h=0,g=e(),m=".drag"+(null==g?"":"-"+g),v=ia.select(i()).on(o+m,a).on(s+m,l),E=X(),y=t(d,g);if(r){u=r.apply(c,arguments);u=[u.x-y[0],u.y-y[1]]}else u=[0,0];f({type:"dragstart"})}}var n=C(e,"drag","dragstart","dragend"),r=null,i=t(x,ia.mouse,J,"mousemove","mouseup"),o=t(K,ia.touch,Q,"touchmove","touchend");e.origin=function(t){if(!arguments.length)return r;r=t;return e};return ia.rebind(e,n,"on")};ia.touches=function(e,t){arguments.length<2&&(t=N().touches);return t?sa(t).map(function(t){var n=Y(e,t);n.identifier=t.identifier;return n}):[]};var Pa=1e-6,Ma=Pa*Pa,ja=Math.PI,Ga=2*ja,Ua=Ga-Pa,Ba=ja/2,qa=ja/180,Ha=180/ja,Va=Math.SQRT2,Wa=2,za=4;ia.interpolateZoom=function(e,t){function n(e){var t=e*E;if(v){var n=it(g),s=o/(Wa*d)*(n*ot(Va*t+g)-rt(g));return[r+s*u,i+s*c,o*n/it(Va*t+g)]}return[r+e*u,i+e*c,o*Math.exp(Va*t)]}var r=e[0],i=e[1],o=e[2],s=t[0],a=t[1],l=t[2],u=s-r,c=a-i,p=u*u+c*c,d=Math.sqrt(p),f=(l*l-o*o+za*p)/(2*o*Wa*d),h=(l*l-o*o-za*p)/(2*l*Wa*d),g=Math.log(Math.sqrt(f*f+1)-f),m=Math.log(Math.sqrt(h*h+1)-h),v=m-g,E=(v||Math.log(l/o))/Va;n.duration=1e3*E;return n};ia.behavior.zoom=function(){function e(e){e.on(R,c).on(Ya+".zoom",d).on("dblclick.zoom",f).on(D,p)}function t(e){return[(e[0]-N.x)/N.k,(e[1]-N.y)/N.k]}function n(e){return[e[0]*N.k+N.x,e[1]*N.k+N.y]}function r(e){N.k=Math.max(A[0],Math.min(A[1],e))}function i(e,t){t=n(t);N.x+=e[0]-t[0];N.y+=e[1]-t[1]}function o(t,n,o,s){t.__chart__={x:N.x,y:N.y,k:N.k};r(Math.pow(2,s));i(g=n,o);t=ia.select(t);I>0&&(t=t.transition().duration(I));t.call(e.event)}function s(){x&&x.domain(y.range().map(function(e){return(e-N.x)/N.k}).map(y.invert));T&&T.domain(b.range().map(function(e){return(e-N.y)/N.k}).map(b.invert))}function a(e){w++||e({type:"zoomstart"})}function l(e){s();e({type:"zoom",scale:N.k,translate:[N.x,N.y]})}function u(e){--w||e({type:"zoomend"});g=null}function c(){function e(){c=1;i(ia.mouse(r),d);l(s)}function n(){p.on(O,null).on(_,null);f(c&&ia.event.target===o);u(s)}var r=this,o=ia.event.target,s=F.of(r,arguments),c=0,p=ia.select(ua).on(O,e).on(_,n),d=t(ia.mouse(r)),f=X();qu.call(r);a(s)}function p(){function e(){var e=ia.touches(h);f=N.k;e.forEach(function(e){e.identifier in m&&(m[e.identifier]=t(e))});return e}function n(){var t=ia.event.target;ia.select(t).on(x,s).on(b,d);T.push(t);for(var n=ia.event.changedTouches,r=0,i=n.length;i>r;++r)m[n[r].identifier]=null;var a=e(),l=Date.now();if(1===a.length){if(500>l-E){var u=a[0];o(h,u,m[u.identifier],Math.floor(Math.log(N.k)/Math.LN2)+1);S()}E=l}else if(a.length>1){var u=a[0],c=a[1],p=u[0]-c[0],f=u[1]-c[1];v=p*p+f*f}}function s(){var e,t,n,o,s=ia.touches(h);qu.call(h);for(var a=0,u=s.length;u>a;++a,o=null){n=s[a];if(o=m[n.identifier]){if(t)break;e=n,t=o}}if(o){var c=(c=n[0]-e[0])*c+(c=n[1]-e[1])*c,p=v&&Math.sqrt(c/v);e=[(e[0]+n[0])/2,(e[1]+n[1])/2];t=[(t[0]+o[0])/2,(t[1]+o[1])/2];r(p*f)}E=null;i(e,t);l(g)}function d(){if(ia.event.touches.length){for(var t=ia.event.changedTouches,n=0,r=t.length;r>n;++n)delete m[t[n].identifier];for(var i in m)return void e()}ia.selectAll(T).on(y,null);C.on(R,c).on(D,p);L();u(g)}var f,h=this,g=F.of(h,arguments),m={},v=0,y=".zoom-"+ia.event.changedTouches[0].identifier,x="touchmove"+y,b="touchend"+y,T=[],C=ia.select(h),L=X();n();a(g);C.on(R,null).on(D,n)}function d(){var e=F.of(this,arguments);v?clearTimeout(v):(h=t(g=m||ia.mouse(this)),qu.call(this),a(e));v=setTimeout(function(){v=null;u(e)},50);S();r(Math.pow(2,.002*$a())*N.k);i(g,h);l(e)}function f(){var e=ia.mouse(this),n=Math.log(N.k)/Math.LN2;o(this,e,t(e),ia.event.shiftKey?Math.ceil(n)-1:Math.floor(n)+1)}var h,g,m,v,E,y,x,b,T,N={x:0,y:0,k:1},L=[960,500],A=Xa,I=250,w=0,R="mousedown.zoom",O="mousemove.zoom",_="mouseup.zoom",D="touchstart.zoom",F=C(e,"zoomstart","zoom","zoomend");e.event=function(e){e.each(function(){var e=F.of(this,arguments),t=N;if(Uu)ia.select(this).transition().each("start.zoom",function(){N=this.__chart__||{x:0,y:0,k:1};a(e)}).tween("zoom:zoom",function(){var n=L[0],r=L[1],i=g?g[0]:n/2,o=g?g[1]:r/2,s=ia.interpolateZoom([(i-N.x)/N.k,(o-N.y)/N.k,n/N.k],[(i-t.x)/t.k,(o-t.y)/t.k,n/t.k]);return function(t){var r=s(t),a=n/r[2];this.__chart__=N={x:i-r[0]*a,y:o-r[1]*a,k:a};l(e)}}).each("interrupt.zoom",function(){u(e)}).each("end.zoom",function(){u(e)});else{this.__chart__=N;a(e);l(e);u(e)}})};e.translate=function(t){if(!arguments.length)return[N.x,N.y];N={x:+t[0],y:+t[1],k:N.k};s();return e};e.scale=function(t){if(!arguments.length)return N.k;N={x:N.x,y:N.y,k:+t};s();return e};e.scaleExtent=function(t){if(!arguments.length)return A;A=null==t?Xa:[+t[0],+t[1]];return e};e.center=function(t){if(!arguments.length)return m;m=t&&[+t[0],+t[1]];return e};e.size=function(t){if(!arguments.length)return L;L=t&&[+t[0],+t[1]];return e};e.duration=function(t){if(!arguments.length)return I;I=+t;return e};e.x=function(t){if(!arguments.length)return x;x=t;y=t.copy();N={x:0,y:0,k:1};return e};e.y=function(t){if(!arguments.length)return T;T=t;b=t.copy();N={x:0,y:0,k:1};return e};return ia.rebind(e,F,"on")};var $a,Xa=[0,1/0],Ya="onwheel"in aa?($a=function(){return-ia.event.deltaY*(ia.event.deltaMode?120:1)},"wheel"):"onmousewheel"in aa?($a=function(){return ia.event.wheelDelta},"mousewheel"):($a=function(){return-ia.event.detail},"MozMousePixelScroll");ia.color=at;at.prototype.toString=function(){return this.rgb()+""};ia.hsl=lt;var Ka=lt.prototype=new at;Ka.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);return new lt(this.h,this.s,this.l/e)};Ka.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new lt(this.h,this.s,e*this.l)};Ka.rgb=function(){return ut(this.h,this.s,this.l)};ia.hcl=ct;var Qa=ct.prototype=new at;Qa.brighter=function(e){return new ct(this.h,this.c,Math.min(100,this.l+Ja*(arguments.length?e:1)))};Qa.darker=function(e){return new ct(this.h,this.c,Math.max(0,this.l-Ja*(arguments.length?e:1)))};Qa.rgb=function(){return pt(this.h,this.c,this.l).rgb()};ia.lab=dt;var Ja=18,Za=.95047,el=1,tl=1.08883,nl=dt.prototype=new at;nl.brighter=function(e){return new dt(Math.min(100,this.l+Ja*(arguments.length?e:1)),this.a,this.b)};nl.darker=function(e){return new dt(Math.max(0,this.l-Ja*(arguments.length?e:1)),this.a,this.b)};nl.rgb=function(){return ft(this.l,this.a,this.b)};ia.rgb=Et;var rl=Et.prototype=new at;rl.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,i=30;if(!t&&!n&&!r)return new Et(i,i,i);t&&i>t&&(t=i);n&&i>n&&(n=i);r&&i>r&&(r=i);return new Et(Math.min(255,t/e),Math.min(255,n/e),Math.min(255,r/e))};rl.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new Et(e*this.r,e*this.g,e*this.b)};rl.hsl=function(){return St(this.r,this.g,this.b)};rl.toString=function(){return"#"+bt(this.r)+bt(this.g)+bt(this.b)};var il=ia.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});il.forEach(function(e,t){il.set(e,yt(t))});ia.functor=At;ia.xhr=wt(It);ia.dsv=function(e,t){function n(e,n,o){arguments.length<3&&(o=n,n=null);var s=Rt(e,t,null==n?r:i(n),o);s.row=function(e){return arguments.length?s.response(null==(n=e)?r:i(e)):n};return s}function r(e){return n.parse(e.responseText)}function i(e){return function(t){return n.parse(t.responseText,e)}}function o(t){return t.map(s).join(e)}function s(e){return a.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}var a=new RegExp('["'+e+"\n]"),l=e.charCodeAt(0);n.parse=function(e,t){var r;return n.parseRows(e,function(e,n){if(r)return r(e,n-1);var i=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");r=t?function(e,n){return t(i(e),n)}:i})};n.parseRows=function(e,t){function n(){if(c>=u)return s;if(i)return i=!1,o;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++<u;)if(34===e.charCodeAt(n)){if(34!==e.charCodeAt(n+1))break;++n}c=n+2;var r=e.charCodeAt(n+1);if(13===r){i=!0;10===e.charCodeAt(n+2)&&++c}else 10===r&&(i=!0);return e.slice(t+1,n).replace(/""/g,'"')}for(;u>c;){var r=e.charCodeAt(c++),a=1;if(10===r)i=!0;else if(13===r){i=!0;10===e.charCodeAt(c)&&(++c,++a)}else if(r!==l)continue;return e.slice(t,c-a)}return e.slice(t)}for(var r,i,o={},s={},a=[],u=e.length,c=0,p=0;(r=n())!==s;){for(var d=[];r!==o&&r!==s;){d.push(r);r=n()}t&&null==(d=t(d,p++))||a.push(d)}return a};n.format=function(t){if(Array.isArray(t[0]))return n.formatRows(t);var r=new v,i=[];t.forEach(function(e){for(var t in e)r.has(t)||i.push(r.add(t))});return[i.map(s).join(e)].concat(t.map(function(t){return i.map(function(e){return s(t[e])}).join(e)})).join("\n")};n.formatRows=function(e){return e.map(o).join("\n")};return n};ia.csv=ia.dsv(",","text/csv");ia.tsv=ia.dsv(" ","text/tab-separated-values");var ol,sl,al,ll,ul,cl=ua[y(ua,"requestAnimationFrame")]||function(e){setTimeout(e,17)};ia.timer=function(e,t,n){var r=arguments.length;2>r&&(t=0);3>r&&(n=Date.now());var i=n+t,o={c:e,t:i,f:!1,n:null};sl?sl.n=o:ol=o;sl=o;if(!al){ll=clearTimeout(ll);al=1;cl(Dt)}};ia.timer.flush=function(){Ft();kt()};ia.round=function(e,t){return t?Math.round(e*(t=Math.pow(10,t)))/t:Math.round(e)};var pl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Mt);ia.formatPrefix=function(e,t){var n=0;if(e){0>e&&(e*=-1);t&&(e=ia.round(e,Pt(e,t)));n=1+Math.floor(1e-12+Math.log(e)/Math.LN10);n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))}return pl[8+n/3]};var dl=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,fl=ia.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,t){return(e=ia.round(e,Pt(e,t))).toFixed(Math.max(0,Math.min(20,Pt(e*(1+1e-15),t))))}}),hl=ia.time={},gl=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ml.setUTCDate.apply(this._,arguments)},setDay:function(){ml.setUTCDay.apply(this._,arguments)},setFullYear:function(){ml.setUTCFullYear.apply(this._,arguments)},setHours:function(){ml.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ml.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ml.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ml.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ml.setUTCSeconds.apply(this._,arguments)},setTime:function(){ml.setTime.apply(this._,arguments)}};var ml=Date.prototype;hl.year=Bt(function(e){e=hl.day(e);e.setMonth(0,1);return e},function(e,t){e.setFullYear(e.getFullYear()+t)},function(e){return e.getFullYear()});hl.years=hl.year.range;hl.years.utc=hl.year.utc.range;hl.day=Bt(function(e){var t=new gl(2e3,0);t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate());return t},function(e,t){e.setDate(e.getDate()+t)},function(e){return e.getDate()-1});hl.days=hl.day.range;hl.days.utc=hl.day.utc.range;hl.dayOfYear=function(e){var t=hl.year(e);return Math.floor((e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)};["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(e,t){t=7-t;var n=hl[e]=Bt(function(e){(e=hl.day(e)).setDate(e.getDate()-(e.getDay()+t)%7);return e},function(e,t){e.setDate(e.getDate()+7*Math.floor(t))},function(e){var n=hl.year(e).getDay();return Math.floor((hl.dayOfYear(e)+(n+t)%7)/7)-(n!==t)});hl[e+"s"]=n.range;hl[e+"s"].utc=n.utc.range;hl[e+"OfYear"]=function(e){var n=hl.year(e).getDay();return Math.floor((hl.dayOfYear(e)+(n+t)%7)/7)}});hl.week=hl.sunday;hl.weeks=hl.sunday.range;hl.weeks.utc=hl.sunday.utc.range;hl.weekOfYear=hl.sundayOfYear;var vl={"-":"",_:" ",0:"0"},El=/^\s*\d+/,yl=/^%/;ia.locale=function(e){return{numberFormat:jt(e),timeFormat:Ht(e)}};var xl=ia.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ia.format=xl.numberFormat;ia.geo={};pn.prototype={s:0,t:0,add:function(e){dn(e,this.t,bl);dn(bl.s,this.s,this);this.s?this.t+=bl.t:this.s=bl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var bl=new pn;ia.geo.stream=function(e,t){e&&Tl.hasOwnProperty(e.type)?Tl[e.type](e,t):fn(e,t)};var Tl={Feature:function(e,t){fn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,i=n.length;++r<i;)fn(n[r].geometry,t)}},Sl={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates;t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){hn(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)hn(n[r],t,0)},Polygon:function(e,t){gn(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)gn(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,i=n.length;++r<i;)fn(n[r],t)}};ia.geo.area=function(e){Nl=0;ia.geo.stream(e,Ll);return Nl};var Nl,Cl=new pn,Ll={sphere:function(){Nl+=4*ja},point:x,lineStart:x,lineEnd:x,polygonStart:function(){Cl.reset();Ll.lineStart=mn},polygonEnd:function(){var e=2*Cl;Nl+=0>e?4*ja+e:e;Ll.lineStart=Ll.lineEnd=Ll.point=x}};ia.geo.bounds=function(){function e(e,t){y.push(x=[c=e,d=e]);p>t&&(p=t);t>f&&(f=t)}function t(t,n){var r=vn([t*qa,n*qa]);if(v){var i=yn(v,r),o=[i[1],-i[0],0],s=yn(o,i);Tn(s);s=Sn(s);var l=t-h,u=l>0?1:-1,g=s[0]*Ha*u,m=Ea(l)>180;if(m^(g>u*h&&u*t>g)){var E=s[1]*Ha;E>f&&(f=E)}else if(g=(g+360)%360-180,m^(g>u*h&&u*t>g)){var E=-s[1]*Ha;p>E&&(p=E)}else{p>n&&(p=n);n>f&&(f=n)}if(m)h>t?a(c,t)>a(c,d)&&(d=t):a(t,d)>a(c,d)&&(c=t);else if(d>=c){c>t&&(c=t);t>d&&(d=t)}else t>h?a(c,t)>a(c,d)&&(d=t):a(t,d)>a(c,d)&&(c=t)}else e(t,n);v=r,h=t}function n(){b.point=t}function r(){x[0]=c,x[1]=d;b.point=e;v=null}function i(e,n){if(v){var r=e-h;E+=Ea(r)>180?r+(r>0?360:-360):r}else g=e,m=n;Ll.point(e,n);t(e,n)}function o(){Ll.lineStart()}function s(){i(g,m);Ll.lineEnd();Ea(E)>Pa&&(c=-(d=180));x[0]=c,x[1]=d;v=null}function a(e,t){return(t-=e)<0?t+360:t}function l(e,t){return e[0]-t[0]}function u(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}var c,p,d,f,h,g,m,v,E,y,x,b={point:e,lineStart:n,lineEnd:r,polygonStart:function(){b.point=i;b.lineStart=o;b.lineEnd=s;E=0;Ll.polygonStart()},polygonEnd:function(){Ll.polygonEnd();b.point=e;b.lineStart=n;b.lineEnd=r;0>Cl?(c=-(d=180),p=-(f=90)):E>Pa?f=90:-Pa>E&&(p=-90);x[0]=c,x[1]=d}};return function(e){f=d=-(c=p=1/0);y=[];ia.geo.stream(e,b);var t=y.length;if(t){y.sort(l);for(var n,r=1,i=y[0],o=[i];t>r;++r){n=y[r];if(u(n[0],i)||u(n[1],i)){a(i[0],n[1])>a(i[0],i[1])&&(i[1]=n[1]);a(n[0],i[1])>a(i[0],i[1])&&(i[0]=n[0])}else o.push(i=n)}for(var s,n,h=-1/0,t=o.length-1,r=0,i=o[t];t>=r;i=n,++r){n=o[r];(s=a(i[1],n[0]))>h&&(h=s,c=n[0],d=i[1])}}y=x=null;return 1/0===c||1/0===p?[[0/0,0/0],[0/0,0/0]]:[[c,p],[d,f]]}}();ia.geo.centroid=function(e){Al=Il=wl=Rl=Ol=_l=Dl=Fl=kl=Pl=Ml=0;ia.geo.stream(e,jl);var t=kl,n=Pl,r=Ml,i=t*t+n*n+r*r;if(Ma>i){t=_l,n=Dl,r=Fl;Pa>Il&&(t=wl,n=Rl,r=Ol);i=t*t+n*n+r*r;if(Ma>i)return[0/0,0/0]}return[Math.atan2(n,t)*Ha,nt(r/Math.sqrt(i))*Ha]};var Al,Il,wl,Rl,Ol,_l,Dl,Fl,kl,Pl,Ml,jl={sphere:x,point:Cn,lineStart:An,lineEnd:In,polygonStart:function(){jl.lineStart=wn},polygonEnd:function(){jl.lineStart=An}},Gl=kn(On,Gn,Bn,[-ja,-ja/2]),Ul=1e9;ia.geo.clipExtent=function(){var e,t,n,r,i,o,s={stream:function(e){i&&(i.valid=!1);i=o(e);i.valid=!0;return i},extent:function(a){if(!arguments.length)return[[e,t],[n,r]];o=Wn(e=+a[0][0],t=+a[0][1],n=+a[1][0],r=+a[1][1]);i&&(i.valid=!1,i=null);return s}};return s.extent([[0,0],[960,500]])};(ia.geo.conicEqualArea=function(){return zn($n)}).raw=$n;ia.geo.albers=function(){return ia.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};ia.geo.albersUsa=function(){function e(e){var o=e[0],s=e[1];t=null;(n(o,s),t)||(r(o,s),t)||i(o,s);return t}var t,n,r,i,o=ia.geo.albers(),s=ia.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ia.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,n){t=[e,n]}};e.invert=function(e){var t=o.scale(),n=o.translate(),r=(e[0]-n[0])/t,i=(e[1]-n[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?s:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:o).invert(e)};e.stream=function(e){var t=o.stream(e),n=s.stream(e),r=a.stream(e);return{point:function(e,i){t.point(e,i);n.point(e,i);r.point(e,i)},sphere:function(){t.sphere();n.sphere();r.sphere()},lineStart:function(){t.lineStart();n.lineStart();r.lineStart()},lineEnd:function(){t.lineEnd();n.lineEnd();r.lineEnd()},polygonStart:function(){t.polygonStart();n.polygonStart();r.polygonStart()},polygonEnd:function(){t.polygonEnd();n.polygonEnd();r.polygonEnd()}}};e.precision=function(t){if(!arguments.length)return o.precision();o.precision(t);s.precision(t);a.precision(t);return e};e.scale=function(t){if(!arguments.length)return o.scale();o.scale(t);s.scale(.35*t);a.scale(t);return e.translate(o.translate())};e.translate=function(t){if(!arguments.length)return o.translate();var u=o.scale(),c=+t[0],p=+t[1];n=o.translate(t).clipExtent([[c-.455*u,p-.238*u],[c+.455*u,p+.238*u]]).stream(l).point;r=s.translate([c-.307*u,p+.201*u]).clipExtent([[c-.425*u+Pa,p+.12*u+Pa],[c-.214*u-Pa,p+.234*u-Pa]]).stream(l).point;i=a.translate([c-.205*u,p+.212*u]).clipExtent([[c-.214*u+Pa,p+.166*u+Pa],[c-.115*u-Pa,p+.234*u-Pa]]).stream(l).point;return e};return e.scale(1070)};var Bl,ql,Hl,Vl,Wl,zl,$l={point:x,lineStart:x,lineEnd:x,polygonStart:function(){ql=0;$l.lineStart=Xn},polygonEnd:function(){$l.lineStart=$l.lineEnd=$l.point=x;Bl+=Ea(ql/2)}},Xl={point:Yn,lineStart:x,lineEnd:x,polygonStart:x,polygonEnd:x},Yl={point:Jn,lineStart:Zn,lineEnd:er,polygonStart:function(){Yl.lineStart=tr
},polygonEnd:function(){Yl.point=Jn;Yl.lineStart=Zn;Yl.lineEnd=er}};ia.geo.path=function(){function e(e){if(e){"function"==typeof a&&o.pointRadius(+a.apply(this,arguments));s&&s.valid||(s=i(o));ia.geo.stream(e,s)}return o.result()}function t(){s=null;return e}var n,r,i,o,s,a=4.5;e.area=function(e){Bl=0;ia.geo.stream(e,i($l));return Bl};e.centroid=function(e){wl=Rl=Ol=_l=Dl=Fl=kl=Pl=Ml=0;ia.geo.stream(e,i(Yl));return Ml?[kl/Ml,Pl/Ml]:Fl?[_l/Fl,Dl/Fl]:Ol?[wl/Ol,Rl/Ol]:[0/0,0/0]};e.bounds=function(e){Wl=zl=-(Hl=Vl=1/0);ia.geo.stream(e,i(Xl));return[[Hl,Vl],[Wl,zl]]};e.projection=function(e){if(!arguments.length)return n;i=(n=e)?e.stream||ir(e):It;return t()};e.context=function(e){if(!arguments.length)return r;o=null==(r=e)?new Kn:new nr(e);"function"!=typeof a&&o.pointRadius(a);return t()};e.pointRadius=function(t){if(!arguments.length)return a;a="function"==typeof t?t:(o.pointRadius(+t),+t);return e};return e.projection(ia.geo.albersUsa()).context(null)};ia.geo.transform=function(e){return{stream:function(t){var n=new or(t);for(var r in e)n[r]=e[r];return n}}};or.prototype={point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};ia.geo.projection=ar;ia.geo.projectionMutator=lr;(ia.geo.equirectangular=function(){return ar(cr)}).raw=cr.invert=cr;ia.geo.rotation=function(e){function t(t){t=e(t[0]*qa,t[1]*qa);return t[0]*=Ha,t[1]*=Ha,t}e=dr(e[0]%360*qa,e[1]*qa,e.length>2?e[2]*qa:0);t.invert=function(t){t=e.invert(t[0]*qa,t[1]*qa);return t[0]*=Ha,t[1]*=Ha,t};return t};pr.invert=cr;ia.geo.circle=function(){function e(){var e="function"==typeof r?r.apply(this,arguments):r,t=dr(-e[0]*qa,-e[1]*qa,0).invert,i=[];n(null,null,1,{point:function(e,n){i.push(e=t(e,n));e[0]*=Ha,e[1]*=Ha}});return{type:"Polygon",coordinates:[i]}}var t,n,r=[0,0],i=6;e.origin=function(t){if(!arguments.length)return r;r=t;return e};e.angle=function(r){if(!arguments.length)return t;n=mr((t=+r)*qa,i*qa);return e};e.precision=function(r){if(!arguments.length)return i;n=mr(t*qa,(i=+r)*qa);return e};return e.angle(90)};ia.geo.distance=function(e,t){var n,r=(t[0]-e[0])*qa,i=e[1]*qa,o=t[1]*qa,s=Math.sin(r),a=Math.cos(r),l=Math.sin(i),u=Math.cos(i),c=Math.sin(o),p=Math.cos(o);return Math.atan2(Math.sqrt((n=p*s)*n+(n=u*c-l*p*a)*n),l*c+u*p*a)};ia.geo.graticule=function(){function e(){return{type:"MultiLineString",coordinates:t()}}function t(){return ia.range(Math.ceil(o/m)*m,i,m).map(d).concat(ia.range(Math.ceil(u/v)*v,l,v).map(f)).concat(ia.range(Math.ceil(r/h)*h,n,h).filter(function(e){return Ea(e%m)>Pa}).map(c)).concat(ia.range(Math.ceil(a/g)*g,s,g).filter(function(e){return Ea(e%v)>Pa}).map(p))}var n,r,i,o,s,a,l,u,c,p,d,f,h=10,g=h,m=90,v=360,E=2.5;e.lines=function(){return t().map(function(e){return{type:"LineString",coordinates:e}})};e.outline=function(){return{type:"Polygon",coordinates:[d(o).concat(f(l).slice(1),d(i).reverse().slice(1),f(u).reverse().slice(1))]}};e.extent=function(t){return arguments.length?e.majorExtent(t).minorExtent(t):e.minorExtent()};e.majorExtent=function(t){if(!arguments.length)return[[o,u],[i,l]];o=+t[0][0],i=+t[1][0];u=+t[0][1],l=+t[1][1];o>i&&(t=o,o=i,i=t);u>l&&(t=u,u=l,l=t);return e.precision(E)};e.minorExtent=function(t){if(!arguments.length)return[[r,a],[n,s]];r=+t[0][0],n=+t[1][0];a=+t[0][1],s=+t[1][1];r>n&&(t=r,r=n,n=t);a>s&&(t=a,a=s,s=t);return e.precision(E)};e.step=function(t){return arguments.length?e.majorStep(t).minorStep(t):e.minorStep()};e.majorStep=function(t){if(!arguments.length)return[m,v];m=+t[0],v=+t[1];return e};e.minorStep=function(t){if(!arguments.length)return[h,g];h=+t[0],g=+t[1];return e};e.precision=function(t){if(!arguments.length)return E;E=+t;c=Er(a,s,90);p=yr(r,n,E);d=Er(u,l,90);f=yr(o,i,E);return e};return e.majorExtent([[-180,-90+Pa],[180,90-Pa]]).minorExtent([[-180,-80-Pa],[180,80+Pa]])};ia.geo.greatArc=function(){function e(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),n||i.apply(this,arguments)]}}var t,n,r=xr,i=br;e.distance=function(){return ia.geo.distance(t||r.apply(this,arguments),n||i.apply(this,arguments))};e.source=function(n){if(!arguments.length)return r;r=n,t="function"==typeof n?null:n;return e};e.target=function(t){if(!arguments.length)return i;i=t,n="function"==typeof t?null:t;return e};e.precision=function(){return arguments.length?e:0};return e};ia.geo.interpolate=function(e,t){return Tr(e[0]*qa,e[1]*qa,t[0]*qa,t[1]*qa)};ia.geo.length=function(e){Kl=0;ia.geo.stream(e,Ql);return Kl};var Kl,Ql={sphere:x,point:x,lineStart:Sr,lineEnd:x,polygonStart:x,polygonEnd:x},Jl=Nr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(ia.geo.azimuthalEqualArea=function(){return ar(Jl)}).raw=Jl;var Zl=Nr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},It);(ia.geo.azimuthalEquidistant=function(){return ar(Zl)}).raw=Zl;(ia.geo.conicConformal=function(){return zn(Cr)}).raw=Cr;(ia.geo.conicEquidistant=function(){return zn(Lr)}).raw=Lr;var eu=Nr(function(e){return 1/e},Math.atan);(ia.geo.gnomonic=function(){return ar(eu)}).raw=eu;Ar.invert=function(e,t){return[e,2*Math.atan(Math.exp(t))-Ba]};(ia.geo.mercator=function(){return Ir(Ar)}).raw=Ar;var tu=Nr(function(){return 1},Math.asin);(ia.geo.orthographic=function(){return ar(tu)}).raw=tu;var nu=Nr(function(e){return 1/(1+e)},function(e){return 2*Math.atan(e)});(ia.geo.stereographic=function(){return ar(nu)}).raw=nu;wr.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ba]};(ia.geo.transverseMercator=function(){var e=Ir(wr),t=e.center,n=e.rotate;e.center=function(e){return e?t([-e[1],e[0]]):(e=t(),[e[1],-e[0]])};e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):(e=n(),[e[0],e[1],e[2]-90])};return n([0,0,90])}).raw=wr;ia.geom={};ia.geom.hull=function(e){function t(e){if(e.length<3)return[];var t,i=At(n),o=At(r),s=e.length,a=[],l=[];for(t=0;s>t;t++)a.push([+i.call(this,e[t],t),+o.call(this,e[t],t),t]);a.sort(Dr);for(t=0;s>t;t++)l.push([a[t][0],-a[t][1]]);var u=_r(a),c=_r(l),p=c[0]===u[0],d=c[c.length-1]===u[u.length-1],f=[];for(t=u.length-1;t>=0;--t)f.push(e[a[u[t]][2]]);for(t=+p;t<c.length-d;++t)f.push(e[a[c[t]][2]]);return f}var n=Rr,r=Or;if(arguments.length)return t(e);t.x=function(e){return arguments.length?(n=e,t):n};t.y=function(e){return arguments.length?(r=e,t):r};return t};ia.geom.polygon=function(e){Sa(e,ru);return e};var ru=ia.geom.polygon.prototype=[];ru.area=function(){for(var e,t=-1,n=this.length,r=this[n-1],i=0;++t<n;){e=r;r=this[t];i+=e[1]*r[0]-e[0]*r[1]}return.5*i};ru.centroid=function(e){var t,n,r=-1,i=this.length,o=0,s=0,a=this[i-1];arguments.length||(e=-1/(6*this.area()));for(;++r<i;){t=a;a=this[r];n=t[0]*a[1]-a[0]*t[1];o+=(t[0]+a[0])*n;s+=(t[1]+a[1])*n}return[o*e,s*e]};ru.clip=function(e){for(var t,n,r,i,o,s,a=Pr(e),l=-1,u=this.length-Pr(this),c=this[u-1];++l<u;){t=e.slice();e.length=0;i=this[l];o=t[(r=t.length-a)-1];n=-1;for(;++n<r;){s=t[n];if(Fr(s,c,i)){Fr(o,c,i)||e.push(kr(o,s,c,i));e.push(s)}else Fr(o,c,i)&&e.push(kr(o,s,c,i));o=s}a&&e.push(e[0]);c=i}return e};var iu,ou,su,au,lu,uu=[],cu=[];Vr.prototype.prepare=function(){for(var e,t=this.edges,n=t.length;n--;){e=t[n].edge;e.b&&e.a||t.splice(n,1)}t.sort(zr);return t.length};ni.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}};ri.prototype={insert:function(e,t){var n,r,i;if(e){t.P=e;t.N=e.N;e.N&&(e.N.P=t);e.N=t;if(e.R){e=e.R;for(;e.L;)e=e.L;e.L=t}else e.R=t;n=e}else if(this._){e=ai(this._);t.P=null;t.N=e;e.P=e.L=t;n=e}else{t.P=t.N=null;this._=t;n=null}t.L=t.R=null;t.U=n;t.C=!0;e=t;for(;n&&n.C;){r=n.U;if(n===r.L){i=r.R;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.R){oi(this,n);e=n;n=e.U}n.C=!1;r.C=!0;si(this,r)}}else{i=r.L;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.L){si(this,n);e=n;n=e.U}n.C=!1;r.C=!0;oi(this,r)}}n=e.U}this._.C=!1},remove:function(e){e.N&&(e.N.P=e.P);e.P&&(e.P.N=e.N);e.N=e.P=null;var t,n,r,i=e.U,o=e.L,s=e.R;n=o?s?ai(s):o:s;i?i.L===e?i.L=n:i.R=n:this._=n;if(o&&s){r=n.C;n.C=e.C;n.L=o;o.U=n;if(n!==s){i=n.U;n.U=e.U;e=n.R;i.L=e;n.R=s;s.U=n}else{n.U=i;i=n;e=n.R}}else{r=e.C;e=n}e&&(e.U=i);if(!r)if(e&&e.C)e.C=!1;else{do{if(e===this._)break;if(e===i.L){t=i.R;if(t.C){t.C=!1;i.C=!0;oi(this,i);t=i.R}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.R||!t.R.C){t.L.C=!1;t.C=!0;si(this,t);t=i.R}t.C=i.C;i.C=t.R.C=!1;oi(this,i);e=this._;break}}else{t=i.L;if(t.C){t.C=!1;i.C=!0;si(this,i);t=i.L}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.L||!t.L.C){t.R.C=!1;t.C=!0;oi(this,t);t=i.L}t.C=i.C;i.C=t.L.C=!1;si(this,i);e=this._;break}}t.C=!0;e=i;i=i.U}while(!e.C);e&&(e.C=!1)}}};ia.geom.voronoi=function(e){function t(e){var t=new Array(e.length),r=a[0][0],i=a[0][1],o=a[1][0],s=a[1][1];li(n(e),a).cells.forEach(function(n,a){var l=n.edges,u=n.site,c=t[a]=l.length?l.map(function(e){var t=e.start();return[t.x,t.y]}):u.x>=r&&u.x<=o&&u.y>=i&&u.y<=s?[[r,s],[o,s],[o,i],[r,i]]:[];c.point=e[a]});return t}function n(e){return e.map(function(e,t){return{x:Math.round(o(e,t)/Pa)*Pa,y:Math.round(s(e,t)/Pa)*Pa,i:t}})}var r=Rr,i=Or,o=r,s=i,a=pu;if(e)return t(e);t.links=function(e){return li(n(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})};t.triangles=function(e){var t=[];li(n(e)).cells.forEach(function(n,r){for(var i,o,s=n.site,a=n.edges.sort(zr),l=-1,u=a.length,c=a[u-1].edge,p=c.l===s?c.r:c.l;++l<u;){i=c;o=p;c=a[l].edge;p=c.l===s?c.r:c.l;r<o.i&&r<p.i&&ci(s,o,p)<0&&t.push([e[r],e[o.i],e[p.i]])}});return t};t.x=function(e){return arguments.length?(o=At(r=e),t):r};t.y=function(e){return arguments.length?(s=At(i=e),t):i};t.clipExtent=function(e){if(!arguments.length)return a===pu?null:a;a=null==e?pu:e;return t};t.size=function(e){return arguments.length?t.clipExtent(e&&[[0,0],e]):a===pu?null:a&&a[1]};return t};var pu=[[-1e6,-1e6],[1e6,1e6]];ia.geom.delaunay=function(e){return ia.geom.voronoi().triangles(e)};ia.geom.quadtree=function(e,t,n,r,i){function o(e){function o(e,t,n,r,i,o,s,a){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var l=e.x,c=e.y;if(null!=l)if(Ea(l-n)+Ea(c-r)<.01)u(e,t,n,r,i,o,s,a);else{var p=e.point;e.x=e.y=e.point=null;u(e,p,l,c,i,o,s,a);u(e,t,n,r,i,o,s,a)}else e.x=n,e.y=r,e.point=t}else u(e,t,n,r,i,o,s,a)}function u(e,t,n,r,i,s,a,l){var u=.5*(i+a),c=.5*(s+l),p=n>=u,d=r>=c,f=d<<1|p;e.leaf=!1;e=e.nodes[f]||(e.nodes[f]=fi());p?i=u:a=u;d?s=c:l=c;o(e,t,n,r,i,s,a,l)}var c,p,d,f,h,g,m,v,E,y=At(a),x=At(l);if(null!=t)g=t,m=n,v=r,E=i;else{v=E=-(g=m=1/0);p=[],d=[];h=e.length;if(s)for(f=0;h>f;++f){c=e[f];c.x<g&&(g=c.x);c.y<m&&(m=c.y);c.x>v&&(v=c.x);c.y>E&&(E=c.y);p.push(c.x);d.push(c.y)}else for(f=0;h>f;++f){var b=+y(c=e[f],f),T=+x(c,f);g>b&&(g=b);m>T&&(m=T);b>v&&(v=b);T>E&&(E=T);p.push(b);d.push(T)}}var S=v-g,N=E-m;S>N?E=m+S:v=g+N;var C=fi();C.add=function(e){o(C,e,+y(e,++f),+x(e,f),g,m,v,E)};C.visit=function(e){hi(e,C,g,m,v,E)};C.find=function(e){return gi(C,e[0],e[1],g,m,v,E)};f=-1;if(null==t){for(;++f<h;)o(C,e[f],p[f],d[f],g,m,v,E);--f}else e.forEach(C.add);p=d=e=c=null;return C}var s,a=Rr,l=Or;if(s=arguments.length){a=pi;l=di;if(3===s){i=n;r=t;n=t=0}return o(e)}o.x=function(e){return arguments.length?(a=e,o):a};o.y=function(e){return arguments.length?(l=e,o):l};o.extent=function(e){if(!arguments.length)return null==t?null:[[t,n],[r,i]];null==e?t=n=r=i=null:(t=+e[0][0],n=+e[0][1],r=+e[1][0],i=+e[1][1]);return o};o.size=function(e){if(!arguments.length)return null==t?null:[r-t,i-n];null==e?t=n=r=i=null:(t=n=0,r=+e[0],i=+e[1]);return o};return o};ia.interpolateRgb=mi;ia.interpolateObject=vi;ia.interpolateNumber=Ei;ia.interpolateString=yi;var du=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fu=new RegExp(du.source,"g");ia.interpolate=xi;ia.interpolators=[function(e,t){var n=typeof t;return("string"===n?il.has(t)||/^(#|rgb\(|hsl\()/.test(t)?mi:yi:t instanceof at?mi:Array.isArray(t)?bi:"object"===n&&isNaN(t)?vi:Ei)(e,t)}];ia.interpolateArray=bi;var hu=function(){return It},gu=ia.map({linear:hu,poly:Ii,quad:function(){return Ci},cubic:function(){return Li},sin:function(){return wi},exp:function(){return Ri},circle:function(){return Oi},elastic:_i,back:Di,bounce:function(){return Fi}}),mu=ia.map({"in":It,out:Si,"in-out":Ni,"out-in":function(e){return Ni(Si(e))}});ia.ease=function(e){var t=e.indexOf("-"),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):"in";n=gu.get(n)||hu;r=mu.get(r)||It;return Ti(r(n.apply(null,oa.call(arguments,1))))};ia.interpolateHcl=ki;ia.interpolateHsl=Pi;ia.interpolateLab=Mi;ia.interpolateRound=ji;ia.transform=function(e){var t=aa.createElementNS(ia.ns.prefix.svg,"g");return(ia.transform=function(e){if(null!=e){t.setAttribute("transform",e);var n=t.transform.baseVal.consolidate()}return new Gi(n?n.matrix:vu)})(e)};Gi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var vu={a:1,b:0,c:0,d:1,e:0,f:0};ia.interpolateTransform=Hi;ia.layout={};ia.layout.bundle=function(){return function(e){for(var t=[],n=-1,r=e.length;++n<r;)t.push(zi(e[n]));return t}};ia.layout.chord=function(){function e(){var e,u,p,d,f,h={},g=[],m=ia.range(o),v=[];n=[];r=[];e=0,d=-1;for(;++d<o;){u=0,f=-1;for(;++f<o;)u+=i[d][f];g.push(u);v.push(ia.range(o));e+=u}s&&m.sort(function(e,t){return s(g[e],g[t])});a&&v.forEach(function(e,t){e.sort(function(e,n){return a(i[t][e],i[t][n])})});e=(Ga-c*o)/e;u=0,d=-1;for(;++d<o;){p=u,f=-1;for(;++f<o;){var E=m[d],y=v[E][f],x=i[E][y],b=u,T=u+=x*e;h[E+"-"+y]={index:E,subindex:y,startAngle:b,endAngle:T,value:x}}r[E]={index:E,startAngle:p,endAngle:u,value:(u-p)/e};u+=c}d=-1;for(;++d<o;){f=d-1;for(;++f<o;){var S=h[d+"-"+f],N=h[f+"-"+d];(S.value||N.value)&&n.push(S.value<N.value?{source:N,target:S}:{source:S,target:N})}}l&&t()}function t(){n.sort(function(e,t){return l((e.source.value+e.target.value)/2,(t.source.value+t.target.value)/2)})}var n,r,i,o,s,a,l,u={},c=0;u.matrix=function(e){if(!arguments.length)return i;o=(i=e)&&i.length;n=r=null;return u};u.padding=function(e){if(!arguments.length)return c;c=e;n=r=null;return u};u.sortGroups=function(e){if(!arguments.length)return s;s=e;n=r=null;return u};u.sortSubgroups=function(e){if(!arguments.length)return a;a=e;n=null;return u};u.sortChords=function(e){if(!arguments.length)return l;l=e;n&&t();return u};u.chords=function(){n||e();return n};u.groups=function(){r||e();return r};return u};ia.layout.force=function(){function e(e){return function(t,n,r,i){if(t.point!==e){var o=t.cx-e.x,s=t.cy-e.y,a=i-n,l=o*o+s*s;if(l>a*a/m){if(h>l){var u=t.charge/l;e.px-=o*u;e.py-=s*u}return!0}if(t.point&&l&&h>l){var u=t.pointCharge/l;e.px-=o*u;e.py-=s*u}}return!t.charge}}function t(e){e.px=ia.event.x,e.py=ia.event.y;a.resume()}var n,r,i,o,s,a={},l=ia.dispatch("start","tick","end"),u=[1,1],c=.9,p=Eu,d=yu,f=-30,h=xu,g=.1,m=.64,v=[],E=[];a.tick=function(){if((r*=.99)<.005){l.end({type:"end",alpha:r=0});return!0}var t,n,a,p,d,h,m,y,x,b=v.length,T=E.length;for(n=0;T>n;++n){a=E[n];p=a.source;d=a.target;y=d.x-p.x;x=d.y-p.y;if(h=y*y+x*x){h=r*o[n]*((h=Math.sqrt(h))-i[n])/h;y*=h;x*=h;d.x-=y*(m=p.weight/(d.weight+p.weight));d.y-=x*m;p.x+=y*(m=1-m);p.y+=x*m}}if(m=r*g){y=u[0]/2;x=u[1]/2;n=-1;if(m)for(;++n<b;){a=v[n];a.x+=(y-a.x)*m;a.y+=(x-a.y)*m}}if(f){Zi(t=ia.geom.quadtree(v),r,s);n=-1;for(;++n<b;)(a=v[n]).fixed||t.visit(e(a))}n=-1;for(;++n<b;){a=v[n];if(a.fixed){a.x=a.px;a.y=a.py}else{a.x-=(a.px-(a.px=a.x))*c;a.y-=(a.py-(a.py=a.y))*c}}l.tick({type:"tick",alpha:r})};a.nodes=function(e){if(!arguments.length)return v;v=e;return a};a.links=function(e){if(!arguments.length)return E;E=e;return a};a.size=function(e){if(!arguments.length)return u;u=e;return a};a.linkDistance=function(e){if(!arguments.length)return p;p="function"==typeof e?e:+e;return a};a.distance=a.linkDistance;a.linkStrength=function(e){if(!arguments.length)return d;d="function"==typeof e?e:+e;return a};a.friction=function(e){if(!arguments.length)return c;c=+e;return a};a.charge=function(e){if(!arguments.length)return f;f="function"==typeof e?e:+e;return a};a.chargeDistance=function(e){if(!arguments.length)return Math.sqrt(h);h=e*e;return a};a.gravity=function(e){if(!arguments.length)return g;g=+e;return a};a.theta=function(e){if(!arguments.length)return Math.sqrt(m);m=e*e;return a};a.alpha=function(e){if(!arguments.length)return r;e=+e;if(r)r=e>0?e:0;else if(e>0){l.start({type:"start",alpha:r=e});ia.timer(a.tick)}return a};a.start=function(){function e(e,r){if(!n){n=new Array(l);for(a=0;l>a;++a)n[a]=[];for(a=0;u>a;++a){var i=E[a];n[i.source.index].push(i.target);n[i.target.index].push(i.source)}}for(var o,s=n[t],a=-1,u=s.length;++a<u;)if(!isNaN(o=s[a][e]))return o;return Math.random()*r}var t,n,r,l=v.length,c=E.length,h=u[0],g=u[1];for(t=0;l>t;++t){(r=v[t]).index=t;r.weight=0}for(t=0;c>t;++t){r=E[t];"number"==typeof r.source&&(r.source=v[r.source]);"number"==typeof r.target&&(r.target=v[r.target]);++r.source.weight;++r.target.weight}for(t=0;l>t;++t){r=v[t];isNaN(r.x)&&(r.x=e("x",h));isNaN(r.y)&&(r.y=e("y",g));isNaN(r.px)&&(r.px=r.x);isNaN(r.py)&&(r.py=r.y)}i=[];if("function"==typeof p)for(t=0;c>t;++t)i[t]=+p.call(this,E[t],t);else for(t=0;c>t;++t)i[t]=p;o=[];if("function"==typeof d)for(t=0;c>t;++t)o[t]=+d.call(this,E[t],t);else for(t=0;c>t;++t)o[t]=d;s=[];if("function"==typeof f)for(t=0;l>t;++t)s[t]=+f.call(this,v[t],t);else for(t=0;l>t;++t)s[t]=f;return a.resume()};a.resume=function(){return a.alpha(.1)};a.stop=function(){return a.alpha(0)};a.drag=function(){n||(n=ia.behavior.drag().origin(It).on("dragstart.force",Yi).on("drag.force",t).on("dragend.force",Ki));if(!arguments.length)return n;this.on("mouseover.force",Qi).on("mouseout.force",Ji).call(n);return void 0};return ia.rebind(a,l,"on")};var Eu=20,yu=1,xu=1/0;ia.layout.hierarchy=function(){function e(i){var o,s=[i],a=[];i.depth=0;for(;null!=(o=s.pop());){a.push(o);if((u=n.call(e,o,o.depth))&&(l=u.length)){for(var l,u,c;--l>=0;){s.push(c=u[l]);c.parent=o;c.depth=o.depth+1}r&&(o.value=0);o.children=u}else{r&&(o.value=+r.call(e,o,o.depth)||0);delete o.children}}no(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t);r&&(i=e.parent)&&(i.value+=e.value)});return a}var t=oo,n=ro,r=io;e.sort=function(n){if(!arguments.length)return t;t=n;return e};e.children=function(t){if(!arguments.length)return n;n=t;return e};e.value=function(t){if(!arguments.length)return r;r=t;return e};e.revalue=function(t){if(r){to(t,function(e){e.children&&(e.value=0)});no(t,function(t){var n;t.children||(t.value=+r.call(e,t,t.depth)||0);(n=t.parent)&&(n.value+=t.value)})}return t};return e};ia.layout.partition=function(){function e(t,n,r,i){var o=t.children;t.x=n;t.y=t.depth*i;t.dx=r;t.dy=i;if(o&&(s=o.length)){var s,a,l,u=-1;r=t.value?r/t.value:0;for(;++u<s;){e(a=o[u],n,l=a.value*r,i);n+=l}}}function t(e){var n=e.children,r=0;if(n&&(i=n.length))for(var i,o=-1;++o<i;)r=Math.max(r,t(n[o]));return 1+r}function n(n,o){var s=r.call(this,n,o);e(s[0],0,i[0],i[1]/t(s[0]));return s}var r=ia.layout.hierarchy(),i=[1,1];n.size=function(e){if(!arguments.length)return i;i=e;return n};return eo(n,r)};ia.layout.pie=function(){function e(s){var a,l=s.length,u=s.map(function(n,r){return+t.call(e,n,r)}),c=+("function"==typeof r?r.apply(this,arguments):r),p=("function"==typeof i?i.apply(this,arguments):i)-c,d=Math.min(Math.abs(p)/l,+("function"==typeof o?o.apply(this,arguments):o)),f=d*(0>p?-1:1),h=(p-l*f)/ia.sum(u),g=ia.range(l),m=[];null!=n&&g.sort(n===bu?function(e,t){return u[t]-u[e]}:function(e,t){return n(s[e],s[t])});g.forEach(function(e){m[e]={data:s[e],value:a=u[e],startAngle:c,endAngle:c+=a*h+f,padAngle:d}});return m}var t=Number,n=bu,r=0,i=Ga,o=0;e.value=function(n){if(!arguments.length)return t;t=n;return e};e.sort=function(t){if(!arguments.length)return n;n=t;return e};e.startAngle=function(t){if(!arguments.length)return r;r=t;return e};e.endAngle=function(t){if(!arguments.length)return i;i=t;return e};e.padAngle=function(t){if(!arguments.length)return o;o=t;return e};return e};var bu={};ia.layout.stack=function(){function e(a,l){if(!(d=a.length))return a;var u=a.map(function(n,r){return t.call(e,n,r)}),c=u.map(function(t){return t.map(function(t,n){return[o.call(e,t,n),s.call(e,t,n)]})}),p=n.call(e,c,l);u=ia.permute(u,p);c=ia.permute(c,p);var d,f,h,g,m=r.call(e,c,l),v=u[0].length;for(h=0;v>h;++h){i.call(e,u[0][h],g=m[h],c[0][h][1]);for(f=1;d>f;++f)i.call(e,u[f][h],g+=c[f-1][h][1],c[f][h][1])}return a}var t=It,n=co,r=po,i=uo,o=ao,s=lo;e.values=function(n){if(!arguments.length)return t;t=n;return e};e.order=function(t){if(!arguments.length)return n;n="function"==typeof t?t:Tu.get(t)||co;return e};e.offset=function(t){if(!arguments.length)return r;r="function"==typeof t?t:Su.get(t)||po;return e};e.x=function(t){if(!arguments.length)return o;o=t;return e};e.y=function(t){if(!arguments.length)return s;s=t;return e};e.out=function(t){if(!arguments.length)return i;i=t;return e};return e};var Tu=ia.map({"inside-out":function(e){var t,n,r=e.length,i=e.map(fo),o=e.map(ho),s=ia.range(r).sort(function(e,t){return i[e]-i[t]}),a=0,l=0,u=[],c=[];for(t=0;r>t;++t){n=s[t];if(l>a){a+=o[n];u.push(n)}else{l+=o[n];c.push(n)}}return c.reverse().concat(u)},reverse:function(e){return ia.range(e.length).reverse()},"default":co}),Su=ia.map({silhouette:function(e){var t,n,r,i=e.length,o=e[0].length,s=[],a=0,l=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];r>a&&(a=r);s.push(r)}for(n=0;o>n;++n)l[n]=(a-s[n])/2;return l},wiggle:function(e){var t,n,r,i,o,s,a,l,u,c=e.length,p=e[0],d=p.length,f=[];f[0]=l=u=0;for(n=1;d>n;++n){for(t=0,i=0;c>t;++t)i+=e[t][n][1];for(t=0,o=0,a=p[n][0]-p[n-1][0];c>t;++t){for(r=0,s=(e[t][n][1]-e[t][n-1][1])/(2*a);t>r;++r)s+=(e[r][n][1]-e[r][n-1][1])/a;o+=s*e[t][n][1]}f[n]=l-=i?o/i*a:0;u>l&&(u=l)}for(n=0;d>n;++n)f[n]-=u;return f},expand:function(e){var t,n,r,i=e.length,o=e[0].length,s=1/i,a=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];if(r)for(t=0;i>t;t++)e[t][n][1]/=r;else for(t=0;i>t;t++)e[t][n][1]=s}for(n=0;o>n;++n)a[n]=0;return a},zero:po});ia.layout.histogram=function(){function e(e,o){for(var s,a,l=[],u=e.map(n,this),c=r.call(this,u,o),p=i.call(this,c,u,o),o=-1,d=u.length,f=p.length-1,h=t?1:1/d;++o<f;){s=l[o]=[];s.dx=p[o+1]-(s.x=p[o]);s.y=0}if(f>0){o=-1;for(;++o<d;){a=u[o];if(a>=c[0]&&a<=c[1]){s=l[ia.bisect(p,a,1,f)-1];s.y+=h;s.push(e[o])}}}return l}var t=!0,n=Number,r=Eo,i=mo;e.value=function(t){if(!arguments.length)return n;n=t;return e};e.range=function(t){if(!arguments.length)return r;r=At(t);return e};e.bins=function(t){if(!arguments.length)return i;i="number"==typeof t?function(e){return vo(e,t)}:At(t);return e};e.frequency=function(n){if(!arguments.length)return t;t=!!n;return e};return e};ia.layout.pack=function(){function e(e,o){var s=n.call(this,e,o),a=s[0],l=i[0],u=i[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};a.x=a.y=0;no(a,function(e){e.r=+c(e.value)});no(a,So);if(r){var p=r*(t?1:Math.max(2*a.r/l,2*a.r/u))/2;no(a,function(e){e.r+=p});no(a,So);no(a,function(e){e.r-=p})}Lo(a,l/2,u/2,t?1:1/Math.max(2*a.r/l,2*a.r/u));return s}var t,n=ia.layout.hierarchy().sort(yo),r=0,i=[1,1];e.size=function(t){if(!arguments.length)return i;i=t;return e};e.radius=function(n){if(!arguments.length)return t;t=null==n||"function"==typeof n?n:+n;return e};e.padding=function(t){if(!arguments.length)return r;r=+t;return e};return eo(e,n)};ia.layout.tree=function(){function e(e,i){var c=s.call(this,e,i),p=c[0],d=t(p);no(d,n),d.parent.m=-d.z;to(d,r);if(u)to(p,o);else{var f=p,h=p,g=p;to(p,function(e){e.x<f.x&&(f=e);e.x>h.x&&(h=e);e.depth>g.depth&&(g=e)});var m=a(f,h)/2-f.x,v=l[0]/(h.x+a(h,f)/2+m),E=l[1]/(g.depth||1);to(p,function(e){e.x=(e.x+m)*v;e.y=e.depth*E})}return c}function t(e){for(var t,n={A:null,children:[e]},r=[n];null!=(t=r.pop());)for(var i,o=t.children,s=0,a=o.length;a>s;++s)r.push((o[s]=i={_:o[s],parent:t,children:(i=o[s].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:s}).a=i);return n.children[0]}function n(e){var t=e.children,n=e.parent.children,r=e.i?n[e.i-1]:null;if(t.length){_o(e);var o=(t[0].z+t[t.length-1].z)/2;if(r){e.z=r.z+a(e._,r._);e.m=e.z-o}else e.z=o}else r&&(e.z=r.z+a(e._,r._));e.parent.A=i(e,r,e.parent.A||n[0])}function r(e){e._.x=e.z+e.parent.m;e.m+=e.parent.m}function i(e,t,n){if(t){for(var r,i=e,o=e,s=t,l=i.parent.children[0],u=i.m,c=o.m,p=s.m,d=l.m;s=Ro(s),i=wo(i),s&&i;){l=wo(l);o=Ro(o);o.a=e;r=s.z+p-i.z-u+a(s._,i._);if(r>0){Oo(Do(s,e,n),e,r);u+=r;c+=r}p+=s.m;u+=i.m;d+=l.m;c+=o.m}if(s&&!Ro(o)){o.t=s;o.m+=p-c}if(i&&!wo(l)){l.t=i;l.m+=u-d;n=e}}return n}function o(e){e.x*=l[0];e.y=e.depth*l[1]}var s=ia.layout.hierarchy().sort(null).value(null),a=Io,l=[1,1],u=null;e.separation=function(t){if(!arguments.length)return a;a=t;return e};e.size=function(t){if(!arguments.length)return u?null:l;u=null==(l=t)?o:null;return e};e.nodeSize=function(t){if(!arguments.length)return u?l:null;u=null==(l=t)?null:o;return e};return eo(e,s)};ia.layout.cluster=function(){function e(e,o){var s,a=t.call(this,e,o),l=a[0],u=0;no(l,function(e){var t=e.children;if(t&&t.length){e.x=ko(t);e.y=Fo(t)}else{e.x=s?u+=n(e,s):0;e.y=0;s=e}});var c=Po(l),p=Mo(l),d=c.x-n(c,p)/2,f=p.x+n(p,c)/2;no(l,i?function(e){e.x=(e.x-l.x)*r[0];e.y=(l.y-e.y)*r[1]}:function(e){e.x=(e.x-d)/(f-d)*r[0];e.y=(1-(l.y?e.y/l.y:1))*r[1]});return a}var t=ia.layout.hierarchy().sort(null).value(null),n=Io,r=[1,1],i=!1;e.separation=function(t){if(!arguments.length)return n;n=t;return e};e.size=function(t){if(!arguments.length)return i?null:r;i=null==(r=t);return e};e.nodeSize=function(t){if(!arguments.length)return i?r:null;i=null!=(r=t);return e};return eo(e,t)};ia.layout.treemap=function(){function e(e,t){for(var n,r,i=-1,o=e.length;++i<o;){r=(n=e[i]).value*(0>t?0:t);n.area=isNaN(r)||0>=r?0:r}}function t(n){var o=n.children;if(o&&o.length){var s,a,l,u=p(n),c=[],d=o.slice(),h=1/0,g="slice"===f?u.dx:"dice"===f?u.dy:"slice-dice"===f?1&n.depth?u.dy:u.dx:Math.min(u.dx,u.dy);e(d,u.dx*u.dy/n.value);c.area=0;for(;(l=d.length)>0;){c.push(s=d[l-1]);c.area+=s.area;if("squarify"!==f||(a=r(c,g))<=h){d.pop();h=a}else{c.area-=c.pop().area;i(c,g,u,!1);g=Math.min(u.dx,u.dy);c.length=c.area=0;h=1/0}}if(c.length){i(c,g,u,!0);c.length=c.area=0}o.forEach(t)}}function n(t){var r=t.children;if(r&&r.length){var o,s=p(t),a=r.slice(),l=[];e(a,s.dx*s.dy/t.value);l.area=0;for(;o=a.pop();){l.push(o);l.area+=o.area;if(null!=o.z){i(l,o.z?s.dx:s.dy,s,!a.length);l.length=l.area=0}}r.forEach(n)}}function r(e,t){for(var n,r=e.area,i=0,o=1/0,s=-1,a=e.length;++s<a;)if(n=e[s].area){o>n&&(o=n);n>i&&(i=n)}r*=r;t*=t;return r?Math.max(t*i*h/r,r/(t*o*h)):1/0}function i(e,t,n,r){var i,o=-1,s=e.length,a=n.x,u=n.y,c=t?l(e.area/t):0;if(t==n.dx){(r||c>n.dy)&&(c=n.dy);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dy=c;a+=i.dx=Math.min(n.x+n.dx-a,c?l(i.area/c):0)}i.z=!0;i.dx+=n.x+n.dx-a;n.y+=c;n.dy-=c}else{(r||c>n.dx)&&(c=n.dx);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dx=c;u+=i.dy=Math.min(n.y+n.dy-u,c?l(i.area/c):0)}i.z=!1;i.dy+=n.y+n.dy-u;n.x+=c;n.dx-=c}}function o(r){var i=s||a(r),o=i[0];o.x=0;o.y=0;o.dx=u[0];o.dy=u[1];s&&a.revalue(o);e([o],o.dx*o.dy/o.value);(s?n:t)(o);d&&(s=i);return i}var s,a=ia.layout.hierarchy(),l=Math.round,u=[1,1],c=null,p=jo,d=!1,f="squarify",h=.5*(1+Math.sqrt(5));o.size=function(e){if(!arguments.length)return u;u=e;return o};o.padding=function(e){function t(t){var n=e.call(o,t,t.depth);return null==n?jo(t):Go(t,"number"==typeof n?[n,n,n,n]:n)}function n(t){return Go(t,e)}if(!arguments.length)return c;var r;p=null==(c=e)?jo:"function"==(r=typeof e)?t:"number"===r?(e=[e,e,e,e],n):n;return o};o.round=function(e){if(!arguments.length)return l!=Number;l=e?Math.round:Number;return o};o.sticky=function(e){if(!arguments.length)return d;d=e;s=null;return o};o.ratio=function(e){if(!arguments.length)return h;h=e;return o};o.mode=function(e){if(!arguments.length)return f;f=e+"";return o};return eo(o,a)};ia.random={normal:function(e,t){var n=arguments.length;2>n&&(t=1);1>n&&(e=0);return function(){var n,r,i;do{n=2*Math.random()-1;r=2*Math.random()-1;i=n*n+r*r}while(!i||i>1);return e+t*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=ia.random.normal.apply(ia,arguments);return function(){return Math.exp(e())}},bates:function(e){var t=ia.random.irwinHall(e);return function(){return t()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;e>n;n++)t+=Math.random();return t}}};ia.scale={};var Nu={floor:It,ceil:It};ia.scale.linear=function(){return zo([0,1],[0,1],xi,!1)};var Cu={s:1,g:1,p:1,r:1,e:1};ia.scale.log=function(){return es(ia.scale.linear().domain([0,1]),10,!0,[1,10])};var Lu=ia.format(".0e"),Au={floor:function(e){return-Math.ceil(-e)},ceil:function(e){return-Math.floor(-e)}};ia.scale.pow=function(){return ts(ia.scale.linear(),1,[0,1])};ia.scale.sqrt=function(){return ia.scale.pow().exponent(.5)};ia.scale.ordinal=function(){return rs([],{t:"range",a:[[]]})};ia.scale.category10=function(){return ia.scale.ordinal().range(Iu)};ia.scale.category20=function(){return ia.scale.ordinal().range(wu)};ia.scale.category20b=function(){return ia.scale.ordinal().range(Ru)};ia.scale.category20c=function(){return ia.scale.ordinal().range(Ou)};var Iu=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xt),wu=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xt),Ru=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xt),Ou=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xt);ia.scale.quantile=function(){return is([],[])};ia.scale.quantize=function(){return os(0,1,[0,1])};ia.scale.threshold=function(){return ss([.5],[0,1])};ia.scale.identity=function(){return as([0,1])};ia.svg={};ia.svg.arc=function(){function e(){var e=Math.max(0,+n.apply(this,arguments)),u=Math.max(0,+r.apply(this,arguments)),c=s.apply(this,arguments)-Ba,p=a.apply(this,arguments)-Ba,d=Math.abs(p-c),f=c>p?0:1;e>u&&(h=u,u=e,e=h);if(d>=Ua)return t(u,f)+(e?t(e,1-f):"")+"Z";var h,g,m,v,E,y,x,b,T,S,N,C,L=0,A=0,I=[];if(v=(+l.apply(this,arguments)||0)/2){m=o===_u?Math.sqrt(e*e+u*u):+o.apply(this,arguments);f||(A*=-1);u&&(A=nt(m/u*Math.sin(v)));e&&(L=nt(m/e*Math.sin(v)))}if(u){E=u*Math.cos(c+A);y=u*Math.sin(c+A);x=u*Math.cos(p-A);b=u*Math.sin(p-A);var w=Math.abs(p-c-2*A)<=ja?0:1;if(A&&hs(E,y,x,b)===f^w){var R=(c+p)/2;E=u*Math.cos(R);y=u*Math.sin(R);x=b=null}}else E=y=0;if(e){T=e*Math.cos(p-L);S=e*Math.sin(p-L);N=e*Math.cos(c+L);C=e*Math.sin(c+L);var O=Math.abs(c-p+2*L)<=ja?0:1;if(L&&hs(T,S,N,C)===1-f^O){var _=(c+p)/2;T=e*Math.cos(_);S=e*Math.sin(_);N=C=null}}else T=S=0;if((h=Math.min(Math.abs(u-e)/2,+i.apply(this,arguments)))>.001){g=u>e^f?0:1;var D=null==N?[T,S]:null==x?[E,y]:kr([E,y],[N,C],[x,b],[T,S]),F=E-D[0],k=y-D[1],P=x-D[0],M=b-D[1],j=1/Math.sin(Math.acos((F*P+k*M)/(Math.sqrt(F*F+k*k)*Math.sqrt(P*P+M*M)))/2),G=Math.sqrt(D[0]*D[0]+D[1]*D[1]);if(null!=x){var U=Math.min(h,(u-G)/(j+1)),B=gs(null==N?[T,S]:[N,C],[E,y],u,U,f),q=gs([x,b],[T,S],u,U,f);h===U?I.push("M",B[0],"A",U,",",U," 0 0,",g," ",B[1],"A",u,",",u," 0 ",1-f^hs(B[1][0],B[1][1],q[1][0],q[1][1]),",",f," ",q[1],"A",U,",",U," 0 0,",g," ",q[0]):I.push("M",B[0],"A",U,",",U," 0 1,",g," ",q[0])}else I.push("M",E,",",y);if(null!=N){var H=Math.min(h,(e-G)/(j-1)),V=gs([E,y],[N,C],e,-H,f),W=gs([T,S],null==x?[E,y]:[x,b],e,-H,f);h===H?I.push("L",W[0],"A",H,",",H," 0 0,",g," ",W[1],"A",e,",",e," 0 ",f^hs(W[1][0],W[1][1],V[1][0],V[1][1]),",",1-f," ",V[1],"A",H,",",H," 0 0,",g," ",V[0]):I.push("L",W[0],"A",H,",",H," 0 0,",g," ",V[0])}else I.push("L",T,",",S)}else{I.push("M",E,",",y);null!=x&&I.push("A",u,",",u," 0 ",w,",",f," ",x,",",b);I.push("L",T,",",S);null!=N&&I.push("A",e,",",e," 0 ",O,",",1-f," ",N,",",C)}I.push("Z");return I.join("")}function t(e,t){return"M0,"+e+"A"+e+","+e+" 0 1,"+t+" 0,"+-e+"A"+e+","+e+" 0 1,"+t+" 0,"+e
}var n=us,r=cs,i=ls,o=_u,s=ps,a=ds,l=fs;e.innerRadius=function(t){if(!arguments.length)return n;n=At(t);return e};e.outerRadius=function(t){if(!arguments.length)return r;r=At(t);return e};e.cornerRadius=function(t){if(!arguments.length)return i;i=At(t);return e};e.padRadius=function(t){if(!arguments.length)return o;o=t==_u?_u:At(t);return e};e.startAngle=function(t){if(!arguments.length)return s;s=At(t);return e};e.endAngle=function(t){if(!arguments.length)return a;a=At(t);return e};e.padAngle=function(t){if(!arguments.length)return l;l=At(t);return e};e.centroid=function(){var e=(+n.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+s.apply(this,arguments)+ +a.apply(this,arguments))/2-Ba;return[Math.cos(t)*e,Math.sin(t)*e]};return e};var _u="auto";ia.svg.line=function(){return ms(It)};var Du=ia.map({linear:vs,"linear-closed":Es,step:ys,"step-before":xs,"step-after":bs,basis:As,"basis-open":Is,"basis-closed":ws,bundle:Rs,cardinal:Ns,"cardinal-open":Ts,"cardinal-closed":Ss,monotone:Ps});Du.forEach(function(e,t){t.key=e;t.closed=/-closed$/.test(e)});var Fu=[0,2/3,1/3,0],ku=[0,1/3,2/3,0],Pu=[0,1/6,2/3,1/6];ia.svg.line.radial=function(){var e=ms(Ms);e.radius=e.x,delete e.x;e.angle=e.y,delete e.y;return e};xs.reverse=bs;bs.reverse=xs;ia.svg.area=function(){return js(It)};ia.svg.area.radial=function(){var e=js(Ms);e.radius=e.x,delete e.x;e.innerRadius=e.x0,delete e.x0;e.outerRadius=e.x1,delete e.x1;e.angle=e.y,delete e.y;e.startAngle=e.y0,delete e.y0;e.endAngle=e.y1,delete e.y1;return e};ia.svg.chord=function(){function e(e,a){var l=t(this,o,e,a),u=t(this,s,e,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(n(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+r(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function t(e,t,n,r){var i=t.call(e,n,r),o=a.call(e,i,r),s=l.call(e,i,r)-Ba,c=u.call(e,i,r)-Ba;return{r:o,a0:s,a1:c,p0:[o*Math.cos(s),o*Math.sin(s)],p1:[o*Math.cos(c),o*Math.sin(c)]}}function n(e,t){return e.a0==t.a0&&e.a1==t.a1}function r(e,t,n){return"A"+e+","+e+" 0 "+ +(n>ja)+",1 "+t}function i(e,t,n,r){return"Q 0,0 "+r}var o=xr,s=br,a=Gs,l=ps,u=ds;e.radius=function(t){if(!arguments.length)return a;a=At(t);return e};e.source=function(t){if(!arguments.length)return o;o=At(t);return e};e.target=function(t){if(!arguments.length)return s;s=At(t);return e};e.startAngle=function(t){if(!arguments.length)return l;l=At(t);return e};e.endAngle=function(t){if(!arguments.length)return u;u=At(t);return e};return e};ia.svg.diagonal=function(){function e(e,i){var o=t.call(this,e,i),s=n.call(this,e,i),a=(o.y+s.y)/2,l=[o,{x:o.x,y:a},{x:s.x,y:a},s];l=l.map(r);return"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=xr,n=br,r=Us;e.source=function(n){if(!arguments.length)return t;t=At(n);return e};e.target=function(t){if(!arguments.length)return n;n=At(t);return e};e.projection=function(t){if(!arguments.length)return r;r=t;return e};return e};ia.svg.diagonal.radial=function(){var e=ia.svg.diagonal(),t=Us,n=e.projection;e.projection=function(e){return arguments.length?n(Bs(t=e)):t};return e};ia.svg.symbol=function(){function e(e,r){return(Mu.get(t.call(this,e,r))||Vs)(n.call(this,e,r))}var t=Hs,n=qs;e.type=function(n){if(!arguments.length)return t;t=At(n);return e};e.size=function(t){if(!arguments.length)return n;n=At(t);return e};return e};var Mu=ia.map({circle:Vs,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*Gu)),n=t*Gu;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/ju),n=t*ju/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/ju),n=t*ju/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});ia.svg.symbolTypes=Mu.keys();var ju=Math.sqrt(3),Gu=Math.tan(30*qa);Ia.transition=function(e){for(var t,n,r=Uu||++Vu,i=Ys(e),o=[],s=Bu||{time:Date.now(),ease:Ai,delay:0,duration:250},a=-1,l=this.length;++a<l;){o.push(t=[]);for(var u=this[a],c=-1,p=u.length;++c<p;){(n=u[c])&&Ks(n,c,i,r,s);t.push(n)}}return zs(o,i,r)};Ia.interrupt=function(e){return this.each(null==e?qu:Ws(Ys(e)))};var Uu,Bu,qu=Ws(Ys()),Hu=[],Vu=0;Hu.call=Ia.call;Hu.empty=Ia.empty;Hu.node=Ia.node;Hu.size=Ia.size;ia.transition=function(e,t){return e&&e.transition?Uu?e.transition(t):e:Oa.transition(e)};ia.transition.prototype=Hu;Hu.select=function(e){var t,n,r,i=this.id,o=this.namespace,s=[];e=A(e);for(var a=-1,l=this.length;++a<l;){s.push(t=[]);for(var u=this[a],c=-1,p=u.length;++c<p;)if((r=u[c])&&(n=e.call(r,r.__data__,c,a))){"__data__"in r&&(n.__data__=r.__data__);Ks(n,c,o,i,r[o][i]);t.push(n)}else t.push(null)}return zs(s,o,i)};Hu.selectAll=function(e){var t,n,r,i,o,s=this.id,a=this.namespace,l=[];e=I(e);for(var u=-1,c=this.length;++u<c;)for(var p=this[u],d=-1,f=p.length;++d<f;)if(r=p[d]){o=r[a][s];n=e.call(r,r.__data__,d,u);l.push(t=[]);for(var h=-1,g=n.length;++h<g;){(i=n[h])&&Ks(i,h,a,s,o);t.push(i)}}return zs(l,a,s)};Hu.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=U(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);for(var n=this[o],a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return zs(i,this.namespace,this.id)};Hu.tween=function(e,t){var n=this.id,r=this.namespace;return arguments.length<2?this.node()[r][n].tween.get(e):q(this,null==t?function(t){t[r][n].tween.remove(e)}:function(i){i[r][n].tween.set(e,t)})};Hu.attr=function(e,t){function n(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(e){return null==e?n:(e+="",function(){var t,n=this.getAttribute(a);return n!==e&&(t=s(n,e),function(e){this.setAttribute(a,t(e))})})}function o(e){return null==e?r:(e+="",function(){var t,n=this.getAttributeNS(a.space,a.local);return n!==e&&(t=s(n,e),function(e){this.setAttributeNS(a.space,a.local,t(e))})})}if(arguments.length<2){for(t in e)this.attr(t,e[t]);return this}var s="transform"==e?Hi:xi,a=ia.ns.qualify(e);return $s(this,"attr."+e,t,a.local?o:i)};Hu.attrTween=function(e,t){function n(e,n){var r=t.call(this,e,n,this.getAttribute(i));return r&&function(e){this.setAttribute(i,r(e))}}function r(e,n){var r=t.call(this,e,n,this.getAttributeNS(i.space,i.local));return r&&function(e){this.setAttributeNS(i.space,i.local,r(e))}}var i=ia.ns.qualify(e);return this.tween("attr."+e,i.local?r:n)};Hu.style=function(e,t,n){function r(){this.style.removeProperty(e)}function i(t){return null==t?r:(t+="",function(){var r,i=ua.getComputedStyle(this,null).getPropertyValue(e);return i!==t&&(r=xi(i,t),function(t){this.style.setProperty(e,r(t),n)})})}var o=arguments.length;if(3>o){if("string"!=typeof e){2>o&&(t="");for(n in e)this.style(n,e[n],t);return this}n=""}return $s(this,"style."+e,t,i)};Hu.styleTween=function(e,t,n){function r(r,i){var o=t.call(this,r,i,ua.getComputedStyle(this,null).getPropertyValue(e));return o&&function(t){this.style.setProperty(e,o(t),n)}}arguments.length<3&&(n="");return this.tween("style."+e,r)};Hu.text=function(e){return $s(this,"text",e,Xs)};Hu.remove=function(){var e=this.namespace;return this.each("end.transition",function(){var t;this[e].count<2&&(t=this.parentNode)&&t.removeChild(this)})};Hu.ease=function(e){var t=this.id,n=this.namespace;if(arguments.length<1)return this.node()[n][t].ease;"function"!=typeof e&&(e=ia.ease.apply(ia,arguments));return q(this,function(r){r[n][t].ease=e})};Hu.delay=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].delay:q(this,"function"==typeof e?function(r,i,o){r[n][t].delay=+e.call(r,r.__data__,i,o)}:(e=+e,function(r){r[n][t].delay=e}))};Hu.duration=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].duration:q(this,"function"==typeof e?function(r,i,o){r[n][t].duration=Math.max(1,e.call(r,r.__data__,i,o))}:(e=Math.max(1,e),function(r){r[n][t].duration=e}))};Hu.each=function(e,t){var n=this.id,r=this.namespace;if(arguments.length<2){var i=Bu,o=Uu;try{Uu=n;q(this,function(t,i,o){Bu=t[r][n];e.call(t,t.__data__,i,o)})}finally{Bu=i;Uu=o}}else q(this,function(i){var o=i[r][n];(o.event||(o.event=ia.dispatch("start","end","interrupt"))).on(e,t)});return this};Hu.transition=function(){for(var e,t,n,r,i=this.id,o=++Vu,s=this.namespace,a=[],l=0,u=this.length;u>l;l++){a.push(e=[]);for(var t=this[l],c=0,p=t.length;p>c;c++){if(n=t[c]){r=n[s][i];Ks(n,c,s,o,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})}e.push(n)}}return zs(a,s,o)};ia.svg.axis=function(){function e(e){e.each(function(){var e,u=ia.select(this),c=this.__chart__||n,p=this.__chart__=n.copy(),d=null==l?p.ticks?p.ticks.apply(p,a):p.domain():l,f=null==t?p.tickFormat?p.tickFormat.apply(p,a):It:t,h=u.selectAll(".tick").data(d,p),g=h.enter().insert("g",".domain").attr("class","tick").style("opacity",Pa),m=ia.transition(h.exit()).style("opacity",Pa).remove(),v=ia.transition(h.order()).style("opacity",1),E=Math.max(i,0)+s,y=Bo(p),x=u.selectAll(".domain").data([0]),b=(x.enter().append("path").attr("class","domain"),ia.transition(x));g.append("line");g.append("text");var T,S,N,C,L=g.select("line"),A=v.select("line"),I=h.select("text").text(f),w=g.select("text"),R=v.select("text"),O="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r){e=Qs,T="x",N="y",S="x2",C="y2";I.attr("dy",0>O?"0em":".71em").style("text-anchor","middle");b.attr("d","M"+y[0]+","+O*o+"V0H"+y[1]+"V"+O*o)}else{e=Js,T="y",N="x",S="y2",C="x2";I.attr("dy",".32em").style("text-anchor",0>O?"end":"start");b.attr("d","M"+O*o+","+y[0]+"H0V"+y[1]+"H"+O*o)}L.attr(C,O*i);w.attr(N,O*E);A.attr(S,0).attr(C,O*i);R.attr(T,0).attr(N,O*E);if(p.rangeBand){var _=p,D=_.rangeBand()/2;c=p=function(e){return _(e)+D}}else c.rangeBand?c=p:m.call(e,p,c);g.call(e,c,p);v.call(e,p,p)})}var t,n=ia.scale.linear(),r=Wu,i=6,o=6,s=3,a=[10],l=null;e.scale=function(t){if(!arguments.length)return n;n=t;return e};e.orient=function(t){if(!arguments.length)return r;r=t in zu?t+"":Wu;return e};e.ticks=function(){if(!arguments.length)return a;a=arguments;return e};e.tickValues=function(t){if(!arguments.length)return l;l=t;return e};e.tickFormat=function(n){if(!arguments.length)return t;t=n;return e};e.tickSize=function(t){var n=arguments.length;if(!n)return i;i=+t;o=+arguments[n-1];return e};e.innerTickSize=function(t){if(!arguments.length)return i;i=+t;return e};e.outerTickSize=function(t){if(!arguments.length)return o;o=+t;return e};e.tickPadding=function(t){if(!arguments.length)return s;s=+t;return e};e.tickSubdivide=function(){return arguments.length&&e};return e};var Wu="bottom",zu={top:1,right:1,bottom:1,left:1};ia.svg.brush=function(){function e(o){o.each(function(){var o=ia.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",i).on("touchstart.brush",i),s=o.selectAll(".background").data([0]);s.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");o.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=o.selectAll(".resize").data(h,It);a.exit().remove();a.enter().append("g").attr("class",function(e){return"resize "+e}).style("cursor",function(e){return $u[e]}).append("rect").attr("x",function(e){return/[ew]$/.test(e)?-3:null}).attr("y",function(e){return/^[ns]/.test(e)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");a.style("display",e.empty()?"none":null);var c,p=ia.transition(o),d=ia.transition(s);if(l){c=Bo(l);d.attr("x",c[0]).attr("width",c[1]-c[0]);n(p)}if(u){c=Bo(u);d.attr("y",c[0]).attr("height",c[1]-c[0]);r(p)}t(p)})}function t(e){e.selectAll(".resize").attr("transform",function(e){return"translate("+c[+/e$/.test(e)]+","+p[+/^s/.test(e)]+")"})}function n(e){e.select(".extent").attr("x",c[0]);e.selectAll(".extent,.n>rect,.s>rect").attr("width",c[1]-c[0])}function r(e){e.select(".extent").attr("y",p[0]);e.selectAll(".extent,.e>rect,.w>rect").attr("height",p[1]-p[0])}function i(){function i(){if(32==ia.event.keyCode){if(!I){E=null;R[0]-=c[1];R[1]-=p[1];I=2}S()}}function h(){if(32==ia.event.keyCode&&2==I){R[0]+=c[1];R[1]+=p[1];I=0;S()}}function g(){var e=ia.mouse(x),i=!1;if(y){e[0]+=y[0];e[1]+=y[1]}if(!I)if(ia.event.altKey){E||(E=[(c[0]+c[1])/2,(p[0]+p[1])/2]);R[0]=c[+(e[0]<E[0])];R[1]=p[+(e[1]<E[1])]}else E=null;if(L&&m(e,l,0)){n(N);i=!0}if(A&&m(e,u,1)){r(N);i=!0}if(i){t(N);T({type:"brush",mode:I?"move":"resize"})}}function m(e,t,n){var r,i,a=Bo(t),l=a[0],u=a[1],h=R[n],g=n?p:c,m=g[1]-g[0];if(I){l-=h;u-=m+h}r=(n?f:d)?Math.max(l,Math.min(u,e[n])):e[n];if(I)i=(r+=h)+m;else{E&&(h=Math.max(l,Math.min(u,2*E[n]-r)));if(r>h){i=r;r=h}else i=h}if(g[0]!=r||g[1]!=i){n?s=null:o=null;g[0]=r;g[1]=i;return!0}}function v(){g();N.style("pointer-events","all").selectAll(".resize").style("display",e.empty()?"none":null);ia.select("body").style("cursor",null);O.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);w();T({type:"brushend"})}var E,y,x=this,b=ia.select(ia.event.target),T=a.of(x,arguments),N=ia.select(x),C=b.datum(),L=!/^(n|s)$/.test(C)&&l,A=!/^(e|w)$/.test(C)&&u,I=b.classed("extent"),w=X(),R=ia.mouse(x),O=ia.select(ua).on("keydown.brush",i).on("keyup.brush",h);ia.event.changedTouches?O.on("touchmove.brush",g).on("touchend.brush",v):O.on("mousemove.brush",g).on("mouseup.brush",v);N.interrupt().selectAll("*").interrupt();if(I){R[0]=c[0]-R[0];R[1]=p[0]-R[1]}else if(C){var _=+/w$/.test(C),D=+/^n/.test(C);y=[c[1-_]-R[0],p[1-D]-R[1]];R[0]=c[_];R[1]=p[D]}else ia.event.altKey&&(E=R.slice());N.style("pointer-events","none").selectAll(".resize").style("display",null);ia.select("body").style("cursor",b.style("cursor"));T({type:"brushstart"});g()}var o,s,a=C(e,"brushstart","brush","brushend"),l=null,u=null,c=[0,0],p=[0,0],d=!0,f=!0,h=Xu[0];e.event=function(e){e.each(function(){var e=a.of(this,arguments),t={x:c,y:p,i:o,j:s},n=this.__chart__||t;this.__chart__=t;if(Uu)ia.select(this).transition().each("start.brush",function(){o=n.i;s=n.j;c=n.x;p=n.y;e({type:"brushstart"})}).tween("brush:brush",function(){var n=bi(c,t.x),r=bi(p,t.y);o=s=null;return function(i){c=t.x=n(i);p=t.y=r(i);e({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i;s=t.j;e({type:"brush",mode:"resize"});e({type:"brushend"})});else{e({type:"brushstart"});e({type:"brush",mode:"resize"});e({type:"brushend"})}})};e.x=function(t){if(!arguments.length)return l;l=t;h=Xu[!l<<1|!u];return e};e.y=function(t){if(!arguments.length)return u;u=t;h=Xu[!l<<1|!u];return e};e.clamp=function(t){if(!arguments.length)return l&&u?[d,f]:l?d:u?f:null;l&&u?(d=!!t[0],f=!!t[1]):l?d=!!t:u&&(f=!!t);return e};e.extent=function(t){var n,r,i,a,d;if(!arguments.length){if(l)if(o)n=o[0],r=o[1];else{n=c[0],r=c[1];l.invert&&(n=l.invert(n),r=l.invert(r));n>r&&(d=n,n=r,r=d)}if(u)if(s)i=s[0],a=s[1];else{i=p[0],a=p[1];u.invert&&(i=u.invert(i),a=u.invert(a));i>a&&(d=i,i=a,a=d)}return l&&u?[[n,i],[r,a]]:l?[n,r]:u&&[i,a]}if(l){n=t[0],r=t[1];u&&(n=n[0],r=r[0]);o=[n,r];l.invert&&(n=l(n),r=l(r));n>r&&(d=n,n=r,r=d);(n!=c[0]||r!=c[1])&&(c=[n,r])}if(u){i=t[0],a=t[1];l&&(i=i[1],a=a[1]);s=[i,a];u.invert&&(i=u(i),a=u(a));i>a&&(d=i,i=a,a=d);(i!=p[0]||a!=p[1])&&(p=[i,a])}return e};e.clear=function(){if(!e.empty()){c=[0,0],p=[0,0];o=s=null}return e};e.empty=function(){return!!l&&c[0]==c[1]||!!u&&p[0]==p[1]};return ia.rebind(e,a,"on")};var $u={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Xu=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Yu=hl.format=xl.timeFormat,Ku=Yu.utc,Qu=Ku("%Y-%m-%dT%H:%M:%S.%LZ");Yu.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Zs:Qu;Zs.parse=function(e){var t=new Date(e);return isNaN(t)?null:t};Zs.toString=Qu.toString;hl.second=Bt(function(e){return new gl(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()});hl.seconds=hl.second.range;hl.seconds.utc=hl.second.utc.range;hl.minute=Bt(function(e){return new gl(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()});hl.minutes=hl.minute.range;hl.minutes.utc=hl.minute.utc.range;hl.hour=Bt(function(e){var t=e.getTimezoneOffset()/60;return new gl(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()});hl.hours=hl.hour.range;hl.hours.utc=hl.hour.utc.range;hl.month=Bt(function(e){e=hl.day(e);e.setDate(1);return e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()});hl.months=hl.month.range;hl.months.utc=hl.month.utc.range;var Ju=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Zu=[[hl.second,1],[hl.second,5],[hl.second,15],[hl.second,30],[hl.minute,1],[hl.minute,5],[hl.minute,15],[hl.minute,30],[hl.hour,1],[hl.hour,3],[hl.hour,6],[hl.hour,12],[hl.day,1],[hl.day,2],[hl.week,1],[hl.month,1],[hl.month,3],[hl.year,1]],ec=Yu.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",On]]),tc={range:function(e,t,n){return ia.range(Math.ceil(e/n)*n,+t,n).map(ta)},floor:It,ceil:It};Zu.year=hl.year;hl.scale=function(){return ea(ia.scale.linear(),Zu,ec)};var nc=Zu.map(function(e){return[e[0].utc,e[1]]}),rc=Ku.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",On]]);nc.year=hl.year.utc;hl.scale.utc=function(){return ea(ia.scale.linear(),nc,rc)};ia.text=wt(function(e){return e.responseText});ia.json=function(e,t){return Rt(e,"application/json",na,t)};ia.html=function(e,t){return Rt(e,"text/html",ra,t)};ia.xml=wt(function(e){return e.responseXML});"function"==typeof e&&e.amd?e(ia):"object"==typeof n&&n.exports&&(n.exports=ia);this.d3=ia}()},{}],59:[function(e){var t=e("jquery");(function(e,t){function n(t,n){var i,o,s,a=t.nodeName.toLowerCase();if("area"===a){i=t.parentNode;o=i.name;if(!t.href||!o||"map"!==i.nodeName.toLowerCase())return!1;s=e("img[usemap=#"+o+"]")[0];return!!s&&r(s)}return(/input|select|textarea|button|object/.test(a)?!t.disabled:"a"===a?t.href||n:n)&&r(t)}function r(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var i=0,o=/^ui-id-\d+$/;e.ui=e.ui||{};e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});e.fn.extend({focus:function(t){return function(n,r){return"number"==typeof n?this.each(function(){var t=this;setTimeout(function(){e(t).focus();r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0);return/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length)for(var r,i,o=e(this[0]);o.length&&o[0]!==document;){r=o.css("position");if("absolute"===r||"relative"===r||"fixed"===r){i=parseInt(o.css("zIndex"),10);if(!isNaN(i)&&0!==i)return i}o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&e(this).removeAttr("id")})}});e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return n(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var r=e.attr(t,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(t,!i)}});e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function i(t,n,r,i){e.each(o,function(){n-=parseFloat(e.css(t,"padding"+this))||0;r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0);i&&(n-=parseFloat(e.css(t,"margin"+this))||0)});return n}var o="Width"===r?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),a={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?a["inner"+r].call(this):this.each(function(){e(this).css(s,i(this,n)+"px")})};e.fn["outer"+r]=function(t,n){return"number"!=typeof t?a["outer"+r].call(this,t):this.each(function(){e(this).css(s,i(this,t,!0,n)+"px")})}});e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))});e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData));e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());e.support.selectstart="onselectstart"in document.createElement("div");e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});e.extend(e.ui,{plugin:{add:function(t,n,r){var i,o=e.ui[t].prototype;for(i in r){o.plugins[i]=o.plugins[i]||[];o.plugins[i].push([n,r[i]])}},call:function(e,t,n){var r,i=e.plugins[t];if(i&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},hasScroll:function(t,n){if("hidden"===e(t).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;if(t[r]>0)return!0;t[r]=1;i=t[r]>0;t[r]=0;return i}})})(t)},{jquery:63}],60:[function(e){var t=e("jquery");e("./widget");(function(e){var t=!1;e(document).mouseup(function(){t=!1});e.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent")){e.removeData(n.target,t.widgetName+".preventClickEvent");n.stopImmediatePropagation();return!1}});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(!t){this._mouseStarted&&this._mouseUp(n);this._mouseDownEvent=n;var r=this,i=1===n.which,o="string"==typeof this.options.cancel&&n.target.nodeName?e(n.target).closest(this.options.cancel).length:!1;if(!i||o||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay;this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted){n.preventDefault();return!0}}!0===e.data(n.target,this.widgetName+".preventClickEvent")&&e.removeData(n.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(e){return r._mouseMove(e)};this._mouseUpDelegate=function(e){return r._mouseUp(e)};e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);n.preventDefault();t=!0;return!0}},_mouseMove:function(t){if(e.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(this._mouseStarted){this._mouseDrag(t);return t.preventDefault()}if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1;this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)}return!this._mouseStarted},_mouseUp:function(t){e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=!1;t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0);this._mouseStop(t)}return!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(t)},{"./widget":62,jquery:63}],61:[function(e){var t=e("jquery");e("./core");e("./mouse");e("./widget");(function(e){function t(e,t,n){return e>t&&t+n>e}function n(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?"x"===e.axis||n(this.items[0].item):!1;this.offset=this.element.offset();this._mouseInit();this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){if("disabled"===t){this.options[t]=n;this.widget().toggleClass("ui-sortable-disabled",!!n)}else e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=null,i=!1,o=this;if(this.reverting)return!1;if(this.options.disabled||"static"===this.options.type)return!1;this._refreshItems(t);e(t.target).parents().each(function(){if(e.data(this,o.widgetName+"-item")===o){r=e(this);return!1}});e.data(t.target,o.widgetName+"-item")===o&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}this.currentItem=r;this._removeCurrentsFromItems();return!0},_mouseStart:function(t,n,r){var i,o,s=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(t);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(t);this.originalPageX=t.pageX;this.originalPageY=t.pageY;s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!==this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();s.containment&&this._setContainment();if(s.cursor&&"auto"!==s.cursor){o=this.document.find("body");this.storedCursor=o.css("cursor");o.css("cursor",s.cursor);this.storedStylesheet=e("<style>*{ cursor: "+s.cursor+" !important; }</style>").appendTo(o)}if(s.opacity){this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity"));this.helper.css("opacity",s.opacity)}if(s.zIndex){this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex"));this.helper.css("zIndex",s.zIndex)}this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset());this._trigger("start",t,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));e.ui.ddmanager&&(e.ui.ddmanager.current=this);e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(t);return!0},_mouseDrag:function(t){var n,r,i,o,s=this.options,a=!1;this.position=this._generatePosition(t);this.positionAbs=this._convertPositionTo("absolute");this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){if(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName){this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<s.scrollSensitivity?this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop+s.scrollSpeed:t.pageY-this.overflowOffset.top<s.scrollSensitivity&&(this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop-s.scrollSpeed);this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<s.scrollSensitivity?this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft+s.scrollSpeed:t.pageX-this.overflowOffset.left<s.scrollSensitivity&&(this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft-s.scrollSpeed)}else{t.pageY-e(document).scrollTop()<s.scrollSensitivity?a=e(document).scrollTop(e(document).scrollTop()-s.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<s.scrollSensitivity&&(a=e(document).scrollTop(e(document).scrollTop()+s.scrollSpeed));t.pageX-e(document).scrollLeft()<s.scrollSensitivity?a=e(document).scrollLeft(e(document).scrollLeft()-s.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<s.scrollSensitivity&&(a=e(document).scrollLeft(e(document).scrollLeft()+s.scrollSpeed))}a!==!1&&e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(n=this.items.length-1;n>=0;n--){r=this.items[n];i=r.item[0];o=this._intersectsWithPointer(r);if(o&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],i):!0)){this.direction=1===o?"down":"up";if("pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(t,r);this._trigger("change",t,this._uiHash());break}}this._contactContainers(t);e.ui.ddmanager&&e.ui.ddmanager.drag(this,t);this._trigger("sort",t,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(t,n){if(t){e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset(),o=this.options.axis,s={};o&&"x"!==o||(s.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft));
o&&"y"!==o||(s.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop));this.reverting=!0;e(this.helper).animate(s,parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--){this.containers[t]._trigger("deactivate",null,this._uiHash(this));if(this.containers[t].containerCache.over){this.containers[t]._trigger("out",null,this._uiHash(this));this.containers[t].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove();e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null});this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))});!r.length&&t.key&&r.push(t.key+"=");return r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")});return r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,o=e.left,s=o+e.width,a=e.top,l=a+e.height,u=this.offset.click.top,c=this.offset.click.left,p="x"===this.options.axis||r+u>a&&l>r+u,d="y"===this.options.axis||t+c>o&&s>t+c,f=p&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?f:o<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<s&&a<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<l},_intersectsWithPointer:function(e){var n="x"===this.options.axis||t(this.positionAbs.top+this.offset.click.top,e.top,e.height),r="y"===this.options.axis||t(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=n&&r,o=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return i?this.floating?s&&"right"===s||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(e){var n=t(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=t(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&r||"left"===o&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){this._refreshItems(e);this.refreshPositions();return this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function n(){a.push(this)}var r,i,o,s,a=[],l=[],u=this._connectWith();if(u&&t)for(r=u.length-1;r>=0;r--){o=e(u[r]);for(i=o.length-1;i>=0;i--){s=e.data(o[i],this.widgetFullName);s&&s!==this&&!s.options.disabled&&l.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}}l.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(r=l.length-1;r>=0;r--)l[r][0].each(n);return e(a)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[];this.containers=[this];var n,r,i,o,s,a,l,u,c=this.items,p=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(n=d.length-1;n>=0;n--){i=e(d[n]);for(r=i.length-1;r>=0;r--){o=e.data(i[r],this.widgetFullName);if(o&&o!==this&&!o.options.disabled){p.push([e.isFunction(o.options.items)?o.options.items.call(o.element[0],t,{item:this.currentItem}):e(o.options.items,o.element),o]);this.containers.push(o)}}}for(n=p.length-1;n>=0;n--){s=p[n][1];a=p[n][0];for(r=0,u=a.length;u>r;r++){l=e(a[r]);l.data(this.widgetName+"-item",s);c.push({item:l,instance:s,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,o;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance===this.currentContainer||!this.currentContainer||r.item[0]===this.currentItem[0]){i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;if(!t){r.width=i.outerWidth();r.height=i.outerHeight()}o=i.offset();r.left=o.left;r.top=o.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--){o=this.containers[n].element.offset();this.containers[n].containerCache.left=o.left;this.containers[n].containerCache.top=o.top;this.containers[n].containerCache.width=this.containers[n].element.outerWidth();this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n,r=t.options;if(!r.placeholder||r.placeholder.constructor===String){n=r.placeholder;r.placeholder={element:function(){var r=t.currentItem[0].nodeName.toLowerCase(),i=e("<"+r+">",t.document[0]).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");"tr"===r?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(i)}):"img"===r&&i.attr("src",t.currentItem.attr("src"));n||i.css("visibility","hidden");return i},update:function(e,i){if(!n||r.forcePlaceholderSize){i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10));i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}}t.placeholder=e(r.placeholder.element.call(t.element,t.currentItem));t.currentItem.after(t.placeholder);r.placeholder.update(t,t.placeholder)},_contactContainers:function(r){var i,o,s,a,l,u,c,p,d,f,h=null,g=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(h&&e.contains(this.containers[i].element[0],h.element[0]))continue;h=this.containers[i];g=i}else if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",r,this._uiHash(this));this.containers[i].containerCache.over=0}if(h)if(1===this.containers.length){if(!this.containers[g].containerCache.over){this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}}else{s=1e4;a=null;f=h.floating||n(this.currentItem);l=f?"left":"top";u=f?"width":"height";c=this.positionAbs[l]+this.offset.click[l];for(o=this.items.length-1;o>=0;o--)if(e.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!f||t(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))){p=this.items[o].item.offset()[l];d=!1;if(Math.abs(p-c)>Math.abs(p+this.items[o][u]-c)){d=!0;p+=this.items[o][u]}if(Math.abs(p-c)<s){s=Math.abs(p-c);a=this.items[o];this.direction=d?"up":"down"}}if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;a?this._rearrange(r,a,null,!0):this._rearrange(r,null,this.containers[g].element,!0);this._trigger("change",r,this._uiHash());this.containers[g]._trigger("change",r,this._uiHash(this));this.currentContainer=this.containers[g];this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;r.parents("body").length||e("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]);r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")});(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width());(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height());return r},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" "));e.isArray(t)&&(t={left:+t[0],top:+t[1]||0});"left"in t&&(this.offset.click.left=t.left+this.margins.left);"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left);"top"in t&&(this.offset.click.top=t.top+this.margins.top);"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();if("absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])){t.left+=this.scrollParent.scrollLeft();t.top+=this.scrollParent.scrollTop()}(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0});return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode);("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]);if(!/^(document|window|parent)$/.test(i.containment)){t=e(i.containment)[0];n=e(i.containment).offset();r="hidden"!==e(t).css("overflow");this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r="absolute"===t?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,o=t.pageX,s=t.pageY,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(a[0].tagName);"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());if(this.originalPosition){if(this.containment){t.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left);t.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top);t.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left);t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)}if(i.grid){n=this.originalPageY+Math.round((s-this.originalPageY)/i.grid[1])*i.grid[1];s=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n;r=this.originalPageX+Math.round((o-this.originalPageX)/i.grid[0])*i.grid[0];o=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r}}return{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:a.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:a.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(e,t){function n(e,t,n){return function(r){n._trigger(e,r,t._uiHash(t))}}this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)("auto"===this._storedCSS[r]||"static"===this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!t&&i.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))});!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||i.push(function(e){this._trigger("update",e,this._uiHash())});if(this!==this.currentContainer&&!t){i.push(function(e){this._trigger("remove",e,this._uiHash())});i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer));i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))}for(r=this.containers.length-1;r>=0;r--){t||i.push(n("deactivate",this,this.containers[r]));if(this.containers[r].containerCache.over){i.push(n("out",this,this.containers[r]));this.containers[r].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!t){this._trigger("beforeStop",e,this._uiHash());for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!1}t||this._trigger("beforeStop",e,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!==this.currentItem[0]&&this.helper.remove();this.helper=null;if(!t){for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(t)},{"./core":59,"./mouse":60,"./widget":62,jquery:63}],62:[function(e){var t=e("jquery");(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n,r=0;null!=(n=t[r]);r++)try{e(n).triggerHandler("remove")}catch(o){}i(t)};e.widget=function(t,n,r){var i,o,s,a,l={},u=t.split(".")[0];t=t.split(".")[1];i=u+"-"+t;if(!r){r=n;n=e.Widget}e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)};e[u]=e[u]||{};o=e[u][t];s=e[u][t]=function(e,t){if(!this._createWidget)return new s(e,t);arguments.length&&this._createWidget(e,t);return void 0};e.extend(s,o,{version:r.version,_proto:e.extend({},r),_childConstructors:[]});a=new n;a.options=e.widget.extend({},a.options);e.each(r,function(t,r){l[t]=e.isFunction(r)?function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=function(e){return n.prototype[t].apply(this,e)};return function(){var t,n=this._super,o=this._superApply;this._super=e;this._superApply=i;t=r.apply(this,arguments);this._super=n;this._superApply=o;return t}}():r});s.prototype=e.widget.extend(a,{widgetEventPrefix:o?a.widgetEventPrefix||t:t},l,{constructor:s,namespace:u,widgetName:t,widgetFullName:i});if(o){e.each(o._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,s,n._proto)});delete o._childConstructors}else n._childConstructors.push(s);e.widget.bridge(t,s)};e.widget.extend=function(n){for(var i,o,s=r.call(arguments,1),a=0,l=s.length;l>a;a++)for(i in s[a]){o=s[a][i];s[a].hasOwnProperty(i)&&o!==t&&(n[i]=e.isPlainObject(o)?e.isPlainObject(n[i])?e.widget.extend({},n[i],o):e.widget.extend({},o):o)}return n};e.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;e.fn[n]=function(s){var a="string"==typeof s,l=r.call(arguments,1),u=this;s=!a&&l.length?e.widget.extend.apply(null,[s].concat(l)):s;this.each(a?function(){var r,i=e.data(this,o);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; attempted to call method '"+s+"'");if(!e.isFunction(i[s])||"_"===s.charAt(0))return e.error("no such method '"+s+"' for "+n+" widget instance");r=i[s].apply(i,l);if(r!==i&&r!==t){u=r&&r.jquery?u.pushStack(r.get()):r;return!1}}:function(){var t=e.data(this,o);t?t.option(s||{})._init():e.data(this,o,new i(s,this))});return u}};e.Widget=function(){};e.Widget._childConstructors=[];e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0];this.element=e(r);this.uuid=n++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=e.widget.extend({},this.options,this._getCreateOptions(),t);this.bindings=e();this.hoverable=e();this.focusable=e();if(r!==this){e.data(r,this.widgetFullName,this);this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}});this.document=e(r.style?r.ownerDocument:r.document||r);this.window=e(this.document[0].defaultView||this.document[0].parentWindow)}this._create();this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i,o,s,a=n;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof n){a={};i=n.split(".");n=i.shift();if(i.length){o=a[n]=e.widget.extend({},this.options[n]);for(s=0;s<i.length-1;s++){o[i[s]]=o[i[s]]||{};o=o[i[s]]}n=i.pop();if(1===arguments.length)return o[n]===t?null:o[n];o[n]=r}else{if(1===arguments.length)return this.options[n]===t?null:this.options[n];a[n]=r}}this._setOptions(a);return this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){this.options[e]=t;if("disabled"===e){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,o=this;if("boolean"!=typeof t){r=n;n=t;t=!1}if(r){n=i=e(n);this.bindings=this.bindings.add(n)}else{r=n;n=this.element;i=this.widget()}e.each(r,function(r,s){function a(){return t||o.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof s?o[s]:s).apply(o,arguments):void 0}"string"!=typeof s&&(a.guid=s.guid=s.guid||a.guid||e.guid++);var l=r.match(/^(\w+)\s*(.*)$/),u=l[1]+o.eventNamespace,c=l[2];c?i.delegate(c,u,a):n.bind(u,a)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return("string"==typeof e?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t);this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t);this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,o,s=this.options[t];r=r||{};n=e.Event(n);n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase();n.target=this.element[0];o=n.originalEvent;if(o)for(i in o)i in n||(n[i]=o[i]);this.element.trigger(n,r);return!(e.isFunction(s)&&s.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}};e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,o){"string"==typeof i&&(i={effect:i});var s,a=i?i===!0||"number"==typeof i?n:i.effect||n:t;i=i||{};"number"==typeof i&&(i={duration:i});s=!e.isEmptyObject(i);i.complete=o;i.delay&&r.delay(i.delay);s&&e.effects&&e.effects.effect[a]?r[t](i):a!==t&&r[a]?r[a](i.duration,i.easing,o):r.queue(function(n){e(this)[t]();o&&o.call(r[0]);n()})}})})(t)},{jquery:63}],63:[function(e,t){t.exports=e(4)},{"/home/lrd900/yasgui/yasgui/node_modules/jquery/dist/jquery.js":4}],64:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(t("jquery")):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){return e.pivotUtilities.d3_renderers={Treemap:function(t,n){var r,i,o,s,a,l,u,c,p,d,f,h,g,m;o={localeStrings:{}};n=e.extend(o,n);l=e("<div style='width: 100%; height: 100%;'>");c={name:"All",children:[]};r=function(e,t,n){var i,o,s,a,l,u;if(0!==t.length){null==e.children&&(e.children=[]);s=t.shift();u=e.children;for(a=0,l=u.length;l>a;a++){i=u[a];if(i.name===s){r(i,t,n);return}}o={name:s};r(o,t,n);return e.children.push(o)}e.value=n};m=t.getRowKeys();for(h=0,g=m.length;g>h;h++){u=m[h];d=t.getAggregator(u,[]).value();null!=d&&r(c,u,d)}i=d3.scale.category10();f=e(window).width()/1.4;s=e(window).height()/1.4;a=10;p=d3.layout.treemap().size([f,s]).sticky(!0).value(function(e){return e.size});d3.select(l[0]).append("div").style("position","relative").style("width",f+2*a+"px").style("height",s+2*a+"px").style("left",a+"px").style("top",a+"px").datum(c).selectAll(".node").data(p.padding([15,0,0,0]).value(function(e){return e.value}).nodes).enter().append("div").attr("class","node").style("background",function(e){return null!=e.children?"lightgrey":i(e.name)}).text(function(e){return e.name}).call(function(){this.style("left",function(e){return e.x+"px"}).style("top",function(e){return e.y+"px"}).style("width",function(e){return Math.max(0,e.dx-1)+"px"}).style("height",function(e){return Math.max(0,e.dy-1)+"px"})});return l}}})}).call(this)},{jquery:63}],65:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(t("jquery")):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t;t=function(t,n){return function(r,i){var o,s,a,l,u,c,p,d,f,h,g,m,v,E,y,x,b,T,S,N,C,L,A,I,w;c={localeStrings:{vs:"vs",by:"by"}};i=e.extend(c,i);b=r.getRowKeys();0===b.length&&b.push([]);a=r.getColKeys();0===a.length&&a.push([]);h=function(){var e,t,n;n=[];for(e=0,t=b.length;t>e;e++){d=b[e];n.push(d.join("-"))}return n}();h.unshift("");m=0;l=[h];for(L=0,I=a.length;I>L;L++){s=a[L];y=[s.join("-")];m+=y[0].length;for(A=0,w=b.length;w>A;A++){x=b[A];o=r.getAggregator(x,s);y.push(null!=o.value()?o.value():null)}l.push(y)}T=N=r.aggregatorName+(r.valAttrs.length?"("+r.valAttrs.join(", ")+")":"");f=r.colAttrs.join("-");""!==f&&(T+=" "+i.localeStrings.vs+" "+f);p=r.rowAttrs.join("-");""!==p&&(T+=" "+i.localeStrings.by+" "+p);v={width:e(window).width()/1.4,height:e(window).height()/1.4,title:T,hAxis:{title:f,slantedText:m>50},vAxis:{title:N}};2===l[0].length&&""===l[0][1]&&(v.legend={position:"none"});for(g in n){S=n[g];v[g]=S}u=google.visualization.arrayToDataTable(l);E=e("<div style='width: 100%; height: 100%;'>");C=new google.visualization.ChartWrapper({dataTable:u,chartType:t,options:v});C.draw(E[0]);E.bind("dblclick",function(){var e;e=new google.visualization.ChartEditor;google.visualization.events.addListener(e,"ok",function(){return e.getChartWrapper().draw(E[0])});return e.openDialog(C)});return E}};return e.pivotUtilities.gchart_renderers={"Line Chart":t("LineChart"),"Bar Chart":t("ColumnChart"),"Stacked Bar Chart":t("ColumnChart",{isStacked:!0}),"Area Chart":t("AreaChart",{isStacked:!0})}})}).call(this)},{jquery:63}],66:[function(t,n,r){(function(){var i,o=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1},s=[].slice,a=function(e,t){return function(){return e.apply(t,arguments)}},l={}.hasOwnProperty;i=function(i){return"object"==typeof r&&"object"==typeof n?i(t("jquery")):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t,n,r,i,u,c,p,d,f,h,g,m,v,E,y,x;n=function(e,t,n){var r,i,o,s;e+="";i=e.split(".");o=i[0];s=i.length>1?n+i[1]:"";r=/(\d+)(\d{3})/;for(;r.test(o);)o=o.replace(r,"$1"+t+"$2");return o+s};h=function(t){var r;r={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:"",showZero:!1};t=e.extend(r,t);return function(e){var r;if(isNaN(e)||!isFinite(e))return"";if(0===e&&!t.showZero)return"";r=n((t.scaler*e).toFixed(t.digitsAfterDecimal),t.thousandsSep,t.decimalSep);return""+t.prefix+r+t.suffix}};v=h();E=h({digitsAfterDecimal:0});y=h({digitsAfterDecimal:1,scaler:100,suffix:"%"});r={count:function(e){null==e&&(e=E);return function(){return function(){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:e}}}},countUnique:function(e){null==e&&(e=E);return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.length},format:e,numInputs:null!=n?0:1}}}},listUnique:function(e){return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.join(e)},format:function(e){return e},numInputs:null!=n?0:1}}}},sum:function(e){null==e&&(e=v);return function(t){var n;n=t[0];return function(){return{sum:0,push:function(e){return isNaN(parseFloat(e[n]))?void 0:this.sum+=parseFloat(e[n])},value:function(){return this.sum},format:e,numInputs:null!=n?0:1}}}},average:function(e){null==e&&(e=v);return function(t){var n;n=t[0];return function(){return{sum:0,len:0,push:function(e){if(!isNaN(parseFloat(e[n]))){this.sum+=parseFloat(e[n]);return this.len++}},value:function(){return this.sum/this.len},format:e,numInputs:null!=n?0:1}}}},sumOverSum:function(e){null==e&&(e=v);return function(t){var n,r;r=t[0],n=t[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[r]))||(this.sumNum+=parseFloat(e[r]));return isNaN(parseFloat(e[n]))?void 0:this.sumDenom+=parseFloat(e[n])},value:function(){return this.sumNum/this.sumDenom},format:e,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(e,t){null==e&&(e=!0);null==t&&(t=v);return function(n){var r,i;i=n[0],r=n[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[i]))||(this.sumNum+=parseFloat(e[i]));return isNaN(parseFloat(e[r]))?void 0:this.sumDenom+=parseFloat(e[r])},value:function(){var t;t=e?1:-1;return(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*t*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:t,numInputs:null!=i&&null!=r?0:2}}}},fractionOf:function(e,t,n){null==t&&(t="total");null==n&&(n=y);return function(){var r;r=1<=arguments.length?s.call(arguments,0):[];return function(i,o,s){return{selector:{total:[[],[]],row:[o,[]],col:[[],s]}[t],inner:e.apply(null,r)(i,o,s),push:function(e){return this.inner.push(e)},format:n,value:function(){return this.inner.value()/i.getAggregator.apply(i,this.selector).inner.value()},numInputs:e.apply(null,r)().numInputs}}}}};i=function(e){return{Count:e.count(E),"Count Unique Values":e.countUnique(E),"List Unique Values":e.listUnique(", "),Sum:e.sum(v),"Integer Sum":e.sum(E),Average:e.average(v),"Sum over Sum":e.sumOverSum(v),"80% Upper Bound":e.sumOverSumBound80(!0,v),"80% Lower Bound":e.sumOverSumBound80(!1,v),"Sum as Fraction of Total":e.fractionOf(e.sum(),"total",y),"Sum as Fraction of Rows":e.fractionOf(e.sum(),"row",y),"Sum as Fraction of Columns":e.fractionOf(e.sum(),"col",y),"Count as Fraction of Total":e.fractionOf(e.count(),"total",y),"Count as Fraction of Rows":e.fractionOf(e.count(),"row",y),"Count as Fraction of Columns":e.fractionOf(e.count(),"col",y)}}(r);m={Table:function(e,t){return g(e,t)},"Table Barchart":function(t,n){return e(g(t,n)).barchart()},Heatmap:function(t,n){return e(g(t,n)).heatmap()},"Row Heatmap":function(t,n){return e(g(t,n)).heatmap("rowheatmap")},"Col Heatmap":function(t,n){return e(g(t,n)).heatmap("colheatmap")}};p={en:{aggregators:i,renderers:m,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter results",totals:"Totals",vs:"vs",by:"by"}}};
d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];x=function(e){return("0"+e).substr(-2,2)};c={bin:function(e,t){return function(n){return n[e]-n[e]%t}},dateFormat:function(e,t,n,r){null==n&&(n=d);null==r&&(r=u);return function(i){var o;o=new Date(Date.parse(i[e]));return isNaN(o)?"":t.replace(/%(.)/g,function(e,t){switch(t){case"y":return o.getFullYear();case"m":return x(o.getMonth()+1);case"n":return n[o.getMonth()];case"d":return x(o.getDate());case"w":return r[o.getDay()];case"x":return o.getDay();case"H":return x(o.getHours());case"M":return x(o.getMinutes());case"S":return x(o.getSeconds());default:return"%"+t}})}}};f=function(){return function(e,t){var n,r,i,o,s,a,l;a=/(\d+)|(\D+)/g;s=/\d/;l=/^0/;if("number"==typeof e||"number"==typeof t)return isNaN(e)?1:isNaN(t)?-1:e-t;n=String(e).toLowerCase();i=String(t).toLowerCase();if(n===i)return 0;if(!s.test(n)||!s.test(i))return n>i?1:-1;n=n.match(a);i=i.match(a);for(;n.length&&i.length;){r=n.shift();o=i.shift();if(r!==o)return s.test(r)&&s.test(o)?r.replace(l,".0")-o.replace(l,".0"):r>o?1:-1}return n.length-i.length}}(this);e.pivotUtilities={aggregatorTemplates:r,aggregators:i,renderers:m,derivers:c,locales:p,naturalSort:f,numberFormat:h};t=function(){function t(e,n){this.getAggregator=a(this.getAggregator,this);this.getRowKeys=a(this.getRowKeys,this);this.getColKeys=a(this.getColKeys,this);this.sortKeys=a(this.sortKeys,this);this.arrSort=a(this.arrSort,this);this.natSort=a(this.natSort,this);this.aggregator=n.aggregator;this.aggregatorName=n.aggregatorName;this.colAttrs=n.cols;this.rowAttrs=n.rows;this.valAttrs=n.vals;this.tree={};this.rowKeys=[];this.colKeys=[];this.rowTotals={};this.colTotals={};this.allTotal=this.aggregator(this,[],[]);this.sorted=!1;t.forEachRecord(e,n.derivedAttributes,function(e){return function(t){return n.filter(t)?e.processRecord(t):void 0}}(this))}t.forEachRecord=function(t,n,r){var i,o,s,a,u,c,p,d,f,h,g,m;i=e.isEmptyObject(n)?r:function(e){var t,i,o;for(t in n){i=n[t];e[t]=null!=(o=i(e))?o:e[t]}return r(e)};if(e.isFunction(t))return t(i);if(e.isArray(t)){if(e.isArray(t[0])){g=[];for(s in t)if(l.call(t,s)){o=t[s];if(s>0){c={};h=t[0];for(a in h)if(l.call(h,a)){u=h[a];c[u]=o[a]}g.push(i(c))}}return g}m=[];for(d=0,f=t.length;f>d;d++){c=t[d];m.push(i(c))}return m}if(t instanceof jQuery){p=[];e("thead > tr > th",t).each(function(){return p.push(e(this).text())});return e("tbody > tr",t).each(function(){c={};e("td",this).each(function(t){return c[p[t]]=e(this).text()});return i(c)})}throw new Error("unknown input format")};t.convertToArray=function(e){var n;n=[];t.forEachRecord(e,{},function(e){return n.push(e)});return n};t.prototype.natSort=function(e,t){return f(e,t)};t.prototype.arrSort=function(e,t){return this.natSort(e.join(),t.join())};t.prototype.sortKeys=function(){if(!this.sorted){this.rowKeys.sort(this.arrSort);this.colKeys.sort(this.arrSort)}return this.sorted=!0};t.prototype.getColKeys=function(){this.sortKeys();return this.colKeys};t.prototype.getRowKeys=function(){this.sortKeys();return this.rowKeys};t.prototype.processRecord=function(e){var t,n,r,i,o,s,a,l,u,c,p,d,f;t=[];i=[];c=this.colAttrs;for(s=0,l=c.length;l>s;s++){o=c[s];t.push(null!=(p=e[o])?p:"null")}d=this.rowAttrs;for(a=0,u=d.length;u>a;a++){o=d[a];i.push(null!=(f=e[o])?f:"null")}r=i.join(String.fromCharCode(0));n=t.join(String.fromCharCode(0));this.allTotal.push(e);if(0!==i.length){if(!this.rowTotals[r]){this.rowKeys.push(i);this.rowTotals[r]=this.aggregator(this,i,[])}this.rowTotals[r].push(e)}if(0!==t.length){if(!this.colTotals[n]){this.colKeys.push(t);this.colTotals[n]=this.aggregator(this,[],t)}this.colTotals[n].push(e)}if(0!==t.length&&0!==i.length){this.tree[r]||(this.tree[r]={});this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,i,t));return this.tree[r][n].push(e)}};t.prototype.getAggregator=function(e,t){var n,r,i;i=e.join(String.fromCharCode(0));r=t.join(String.fromCharCode(0));n=0===e.length&&0===t.length?this.allTotal:0===e.length?this.colTotals[r]:0===t.length?this.rowTotals[i]:this.tree[i][r];return null!=n?n:{value:function(){return null},format:function(){return""}}};return t}();g=function(t,n){var r,i,o,s,a,u,c,p,d,f,h,g,m,v,E,y,x,b,T,S,N;u={localeStrings:{totals:"Totals"}};n=e.extend(u,n);o=t.colAttrs;h=t.rowAttrs;m=t.getRowKeys();a=t.getColKeys();f=document.createElement("table");f.className="pvtTable";v=function(e,t,n){var r,i,o,s,a,l;if(0!==t){i=!0;for(s=a=0;n>=0?n>=a:a>=n;s=n>=0?++a:--a)e[t-1][s]!==e[t][s]&&(i=!1);if(i)return-1}r=0;for(;t+r<e.length;){o=!1;for(s=l=0;n>=0?n>=l:l>=n;s=n>=0?++l:--l)e[t][s]!==e[t+r][s]&&(o=!0);if(o)break;r++}return r};for(p in o)if(l.call(o,p)){i=o[p];b=document.createElement("tr");if(0===parseInt(p)&&0!==h.length){y=document.createElement("th");y.setAttribute("colspan",h.length);y.setAttribute("rowspan",o.length);b.appendChild(y)}y=document.createElement("th");y.className="pvtAxisLabel";y.textContent=i;b.appendChild(y);for(c in a)if(l.call(a,c)){s=a[c];N=v(a,parseInt(c),parseInt(p));if(-1!==N){y=document.createElement("th");y.className="pvtColLabel";y.textContent=s[p];y.setAttribute("colspan",N);parseInt(p)===o.length-1&&0!==h.length&&y.setAttribute("rowspan",2);b.appendChild(y)}}if(0===parseInt(p)){y=document.createElement("th");y.className="pvtTotalLabel";y.innerHTML=n.localeStrings.totals;y.setAttribute("rowspan",o.length+(0===h.length?0:1));b.appendChild(y)}f.appendChild(b)}if(0!==h.length){b=document.createElement("tr");for(c in h)if(l.call(h,c)){d=h[c];y=document.createElement("th");y.className="pvtAxisLabel";y.textContent=d;b.appendChild(y)}y=document.createElement("th");if(0===o.length){y.className="pvtTotalLabel";y.innerHTML=n.localeStrings.totals}b.appendChild(y);f.appendChild(b)}for(c in m)if(l.call(m,c)){g=m[c];b=document.createElement("tr");for(p in g)if(l.call(g,p)){T=g[p];N=v(m,parseInt(c),parseInt(p));if(-1!==N){y=document.createElement("th");y.className="pvtRowLabel";y.textContent=T;y.setAttribute("rowspan",N);parseInt(p)===h.length-1&&0!==o.length&&y.setAttribute("colspan",2);b.appendChild(y)}}for(p in a)if(l.call(a,p)){s=a[p];r=t.getAggregator(g,s);S=r.value();E=document.createElement("td");E.className="pvtVal row"+c+" col"+p;E.innerHTML=r.format(S);E.setAttribute("data-value",S);b.appendChild(E)}x=t.getAggregator(g,[]);S=x.value();E=document.createElement("td");E.className="pvtTotal rowTotal";E.innerHTML=x.format(S);E.setAttribute("data-value",S);E.setAttribute("data-for","row"+c);b.appendChild(E);f.appendChild(b)}b=document.createElement("tr");y=document.createElement("th");y.className="pvtTotalLabel";y.innerHTML=n.localeStrings.totals;y.setAttribute("colspan",h.length+(0===o.length?0:1));b.appendChild(y);for(p in a)if(l.call(a,p)){s=a[p];x=t.getAggregator([],s);S=x.value();E=document.createElement("td");E.className="pvtTotal colTotal";E.innerHTML=x.format(S);E.setAttribute("data-value",S);E.setAttribute("data-for","col"+p);b.appendChild(E)}x=t.getAggregator([],[]);S=x.value();E=document.createElement("td");E.className="pvtGrandTotal";E.innerHTML=x.format(S);E.setAttribute("data-value",S);b.appendChild(E);f.appendChild(b);f.setAttribute("data-numrows",m.length);f.setAttribute("data-numcols",a.length);return f};e.fn.pivot=function(n,i){var o,s,a,l,u;o={cols:[],rows:[],filter:function(){return!0},aggregator:r.count()(),aggregatorName:"Count",derivedAttributes:{},renderer:g,rendererOptions:null,localeStrings:p.en.localeStrings};i=e.extend(o,i);l=null;try{a=new t(n,i);try{l=i.renderer(a,i.rendererOptions)}catch(c){s=c;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.renderError)}}catch(c){s=c;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.computeError)}u=this[0];for(;u.hasChildNodes();)u.removeChild(u.lastChild);return this.append(l)};e.fn.pivotUI=function(n,r,i,s){var a,u,c,d,h,g,m,v,E,y,x,b,T,S,N,C,L,A,I,w,R,O,_,D,F,k,P,M,j,G,U,B,q,H,V,W,z,$,X;null==i&&(i=!1);null==s&&(s="en");m={derivedAttributes:{},aggregators:p[s].aggregators,renderers:p[s].renderers,hiddenAttributes:[],menuLimit:200,cols:[],rows:[],vals:[],exclusions:{},unusedAttrsVertical:"auto",autoSortUnusedAttrs:!1,rendererOptions:{localeStrings:p[s].localeStrings},onRefresh:null,filter:function(){return!0},localeStrings:p[s].localeStrings};E=this.data("pivotUIOptions");T=null==E||i?e.extend(m,r):E;try{n=t.convertToArray(n);w=function(){var e,t;e=n[0];t=[];for(b in e)l.call(e,b)&&t.push(b);return t}();V=T.derivedAttributes;for(h in V)l.call(V,h)&&o.call(w,h)<0&&w.push(h);d={};for(P=0,U=w.length;U>P;P++){F=w[P];d[F]={}}t.forEachRecord(n,T.derivedAttributes,function(e){var t,n,r;r=[];for(b in e)if(l.call(e,b)){t=e[b];if(T.filter(e)){null==t&&(t="null");null==(n=d[b])[t]&&(n[t]=0);r.push(d[b][t]++)}}return r});_=e("<table cellpadding='5'>");A=e("<td>");L=e("<select class='pvtRenderer'>").appendTo(A).bind("change",function(){return N()});W=T.renderers;for(F in W)l.call(W,F)&&e("<option>").val(F).html(F).appendTo(L);g=e("<td class='pvtAxisContainer pvtUnused'>");I=function(){var e,t,n;n=[];for(e=0,t=w.length;t>e;e++){h=w[e];o.call(T.hiddenAttributes,h)<0&&n.push(h)}return n}();D=!1;if("auto"===T.unusedAttrsVertical){c=0;for(M=0,B=I.length;B>M;M++){a=I[M];c+=a.length}D=c>120}g.addClass(T.unusedAttrsVertical===!0||D?"pvtVertList":"pvtHorizList");k=function(t){var n,r,i,s,a,l,u,c,p,h,m,v,E,x,S;u=function(){var e;e=[];for(b in d[t])e.push(b);return e}();l=!1;v=e("<div>").addClass("pvtFilterBox").hide();v.append(e("<h4>").text(""+t+" ("+u.length+")"));if(u.length>T.menuLimit)v.append(e("<p>").html(T.localeStrings.tooMany));else{r=e("<p>").appendTo(v);r.append(e("<button>").html(T.localeStrings.selectAll).bind("click",function(){return v.find("input:visible").prop("checked",!0)}));r.append(e("<button>").html(T.localeStrings.selectNone).bind("click",function(){return v.find("input:visible").prop("checked",!1)}));r.append(e("<input>").addClass("pvtSearch").attr("placeholder",T.localeStrings.filterResults).bind("keyup",function(){var t;t=e(this).val().toLowerCase();return e(this).parents(".pvtFilterBox").find("label span").each(function(){var n;n=e(this).text().toLowerCase().indexOf(t);return-1!==n?e(this).parent().show():e(this).parent().hide()})}));i=e("<div>").addClass("pvtCheckContainer").appendTo(v);S=u.sort(f);for(E=0,x=S.length;x>E;E++){b=S[E];m=d[t][b];s=e("<label>");a=T.exclusions[t]?o.call(T.exclusions[t],b)>=0:!1;l||(l=a);e("<input type='checkbox' class='pvtFilter'>").attr("checked",!a).data("filter",[t,b]).appendTo(s);s.append(e("<span>").text(""+b+" ("+m+")"));i.append(e("<p>").append(s))}}h=function(){var t;t=e(v).find("[type='checkbox']").length-e(v).find("[type='checkbox']:checked").length;t>0?n.addClass("pvtFilteredAttribute"):n.removeClass("pvtFilteredAttribute");return u.length>T.menuLimit?v.toggle():v.toggle(0,N)};e("<p>").appendTo(v).append(e("<button>").text("OK").bind("click",h));c=function(t){v.css({left:t.pageX,top:t.pageY}).toggle();e(".pvtSearch").val("");return e("label").show()};p=e("<span class='pvtTriangle'>").html(" ▾").bind("click",c);n=e("<li class='axis_"+y+"'>").append(e("<span class='pvtAttr'>").text(t).data("attrName",t).append(p));l&&n.addClass("pvtFilteredAttribute");g.append(n).append(v);return n.bind("dblclick",c)};for(y in I){h=I[y];k(h)}R=e("<tr>").appendTo(_);u=e("<select class='pvtAggregator'>").bind("change",function(){return N()});z=T.aggregators;for(F in z)l.call(z,F)&&u.append(e("<option>").val(F).html(F));e("<td class='pvtVals'>").appendTo(R).append(u).append(e("<br>"));e("<td class='pvtAxisContainer pvtHorizList pvtCols'>").appendTo(R);O=e("<tr>").appendTo(_);O.append(e("<td valign='top' class='pvtAxisContainer pvtRows'>"));S=e("<td valign='top' class='pvtRendererArea'>").appendTo(O);if(T.unusedAttrsVertical===!0||D){_.find("tr:nth-child(1)").prepend(A);_.find("tr:nth-child(2)").prepend(g)}else _.prepend(e("<tr>").append(A).append(g));this.html(_);$=T.cols;for(j=0,q=$.length;q>j;j++){F=$[j];this.find(".pvtCols").append(this.find(".axis_"+I.indexOf(F)))}X=T.rows;for(G=0,H=X.length;H>G;G++){F=X[G];this.find(".pvtRows").append(this.find(".axis_"+I.indexOf(F)))}null!=T.aggregatorName&&this.find(".pvtAggregator").val(T.aggregatorName);null!=T.rendererName&&this.find(".pvtRenderer").val(T.rendererName);x=!0;C=function(t){return function(){var r,i,s,a,l,c,p,d,f,h,g,m,v,E;d={derivedAttributes:T.derivedAttributes,localeStrings:T.localeStrings,rendererOptions:T.rendererOptions,cols:[],rows:[]};l=null!=(E=T.aggregators[u.val()]([])().numInputs)?E:0;h=[];t.find(".pvtRows li span.pvtAttr").each(function(){return d.rows.push(e(this).data("attrName"))});t.find(".pvtCols li span.pvtAttr").each(function(){return d.cols.push(e(this).data("attrName"))});t.find(".pvtVals select.pvtAttrDropdown").each(function(){if(0===l)return e(this).remove();l--;return""!==e(this).val()?h.push(e(this).val()):void 0});if(0!==l){p=t.find(".pvtVals");for(F=m=0;l>=0?l>m:m>l;F=l>=0?++m:--m){a=e("<select class='pvtAttrDropdown'>").append(e("<option>")).bind("change",function(){return N()});for(v=0,g=I.length;g>v;v++){r=I[v];a.append(e("<option>").val(r).text(r))}p.append(a)}}if(x){h=T.vals;y=0;t.find(".pvtVals select.pvtAttrDropdown").each(function(){e(this).val(h[y]);return y++});x=!1}d.aggregatorName=u.val();d.vals=h;d.aggregator=T.aggregators[u.val()](h);d.renderer=T.renderers[L.val()];i={};t.find("input.pvtFilter").not(":checked").each(function(){var t;t=e(this).data("filter");return null!=i[t[0]]?i[t[0]].push(t[1]):i[t[0]]=[t[1]]});d.filter=function(e){var t,n;if(!T.filter(e))return!1;for(b in i){t=i[b];if(n=""+e[b],o.call(t,n)>=0)return!1}return!0};S.pivot(n,d);c=e.extend(T,{cols:d.cols,rows:d.rows,vals:h,exclusions:i,aggregatorName:u.val(),rendererName:L.val()});t.data("pivotUIOptions",c);if(T.autoSortUnusedAttrs){s=e.pivotUtilities.naturalSort;f=t.find("td.pvtUnused.pvtAxisContainer");e(f).children("li").sort(function(t,n){return s(e(t).text(),e(n).text())}).appendTo(f)}S.css("opacity",1);return null!=T.onRefresh?T.onRefresh(c):void 0}}(this);N=function(){return function(){S.css("opacity",.5);return setTimeout(C,10)}}(this);N();this.find(".pvtAxisContainer").sortable({update:function(e,t){return null==t.sender?N():void 0},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(Y){v=Y;"undefined"!=typeof console&&null!==console&&console.error(v.stack);this.html(T.localeStrings.uiRenderError)}return this};e.fn.heatmap=function(t){var n,r,i,o,s,a,l,u;null==t&&(t="heatmap");a=this.data("numrows");s=this.data("numcols");n=function(e,t,n){var r;r=function(){switch(e){case"red":return function(e){return"ff"+e+e};case"green":return function(e){return""+e+"ff"+e};case"blue":return function(e){return""+e+e+"ff"}}}();return function(e){var i,o;o=255-Math.round(255*(e-t)/(n-t));i=o.toString(16).split(".")[0];1===i.length&&(i=0+i);return r(i)}};r=function(t){return function(r,i){var o,s,a;s=function(n){return t.find(r).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};a=[];s(function(e){return a.push(e)});o=n(i,Math.min.apply(Math,a),Math.max.apply(Math,a));return s(function(e,t){return t.css("background-color","#"+o(e))})}}(this);switch(t){case"heatmap":r(".pvtVal","red");break;case"rowheatmap":for(i=l=0;a>=0?a>l:l>a;i=a>=0?++l:--l)r(".pvtVal.row"+i,"red");break;case"colheatmap":for(o=u=0;s>=0?s>u:u>s;o=s>=0?++u:--u)r(".pvtVal.col"+o,"red")}r(".pvtTotal.rowTotal","red");r(".pvtTotal.colTotal","red");return this};return e.fn.barchart=function(){var t,n,r,i,o;i=this.data("numrows");r=this.data("numcols");t=function(t){return function(n){var r,i,o,s;r=function(r){return t.find(n).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?r(t,e(this)):void 0})};s=[];r(function(e){return s.push(e)});i=Math.max.apply(Math,s);o=function(e){return 100*e/(1.4*i)};return r(function(t,n){var r,i;r=n.text();i=e("<div>").css({position:"relative",height:"55px"});i.append(e("<div>").css({position:"absolute",bottom:0,left:0,right:0,height:o(t)+"%","background-color":"gray"}));i.append(e("<div>").text(r).css({position:"relative","padding-left":"5px","padding-right":"5px"}));return n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(i)})}}(this);for(n=o=0;i>=0?i>o:o>i;n=i>=0?++o:--o)t(".pvtVal.row"+n);t(".pvtTotal.colTotal");return this}})}).call(this)},{jquery:63}],67:[function(e,t){t.exports=e(8)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":8}],68:[function(e,t){t.exports=e(28)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/yasgui-utils/package.json":28}],69:[function(e,t,n){arguments[4][10][0].apply(n,arguments)},{"../package.json":68,"./storage.js":70,"./svg.js":71,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":10}],70:[function(e,t){t.exports=e(30)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/yasgui-utils/src/storage.js":30,store:67}],71:[function(e,t){t.exports=e(12)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":12}],72:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.4.2",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1","gulp-html-replace":"^1.4.1","browserify-shim":"^3.8.1"},bugs:"https://github.com/YASGUI/YASR/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/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1",pivottable:"^1.2.2","jquery-ui":"^1.10.5",d3:"^3.4.13"},"browserify-shim":{google:"global:google"},browserify:{transform:["browserify-shim"]},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"datatables",global:"jQuery"},datatables:{require:"datatables",global:"jQuery"},d3:{require:"d3",global:"d3"},"jquery-ui/sortable":{require:"jquery-ui/sortable",global:"jQuery"},pivottable:{require:"pivottable",global:"jQuery"}}}},{}],73:[function(e,t){"use strict";t.exports=function(e){var t='"',n=",",r="\n",i=e.head.vars,o=e.results.bindings,s=function(){for(var e=0;e<i.length;e++)u(i[e]);p+=r},a=function(){for(var e=0;e<o.length;e++){l(o[e]);p+=r}},l=function(e){for(var t=0;t<i.length;t++){var n=i[t];u(e.hasOwnProperty(n)?e[n].value:"")}},u=function(e){e.replace(t,t+t);c(e)&&(e=t+e+t);p+=" "+e+" "+n},c=function(e){var r=!1;e.match("[\\w|"+n+"|"+t+"]")&&(r=!0);return r},p="";s();a();return p}},{}],74:[function(e,t){"use strict";var n=e("jquery"),r=t.exports=function(t){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(t.resultsContainer);var i=t.results.getBoolean(),o=null,s=null;if(i===!0){o="check";s="True"}else if(i===!1){o="cross";s="False"}else{r.width("140");s="Could not find boolean value in response"}o&&e("yasgui-utils").svg.draw(r,e("./imgs.js")[o]);n("<span></span>").text(s).appendTo(r)},o=function(){return t.results.getBoolean&&(t.results.getBoolean()===!0||0==t.results.getBoolean())};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":e("../package.json").version,jquery:n.fn.jquery}},{"../package.json":72,"./imgs.js":79,jquery:63,"yasgui-utils":69}],75:[function(e,t){"use strict";var n=e("jquery");t.exports={output:"table",useGoogleCharts:!0,outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{prefix:function(e){return"yasr_"+n(e.container).closest("[id]").attr("id")+"_"},outputSelector:function(){return"selector"},results:{id:function(e){return"results_"+n(e.container).closest("[id]").attr("id")},key:"results",maxSize:1e5}}}},{jquery:63}],76:[function(e,t){"use strict";var n=e("jquery"),r=t.exports=function(e){var t=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){var r=e.results.getException();t.empty().appendTo(e.resultsContainer);var i="Error";r.statusText&&r.statusText.length<100&&(i=r.statusText);void 0!=r.status&&(i+=" (#"+r.status+")");t.append(n("<span>",{"class":"exception"}).text(i));var o=null;r.responseText?o=r.responseText:"string"==typeof r&&(o=r);o&&t.append(n("<pre>").text(o))}),o=function(e){return e.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:63}],77:[function(e,t){(function(n){var r=e("events").EventEmitter,i=(e("jquery"),!1),o=!1,s=function(){r.call(this);var e=this;this.init=function(){if(o||("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)||i)("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)?e.emit("initDone"):o&&e.emit("initError");else{i=!0;a("//google.com/jsapi",function(){i=!1;e.emit("initDone")});var t=100,r=6e3,s=+new Date,l=function(){if(!("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null))if(+new Date-s>r){o=!0;i=!1;e.emit("initError")}else setTimeout(l,t)};l()}};this.googleLoad=function(){var t=function(){("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).load("visualization","1",{packages:["corechart","charteditor"],callback:function(){e.emit("done")}})};if(i){e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}else if("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)t();else if(o)e.emit("error","Could not load google loader");else{e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}}},a=function(e,t){var n=document.createElement("script");n.type="text/javascript";n.readyState?n.onreadystatechange=function(){if("loaded"==n.readyState||"complete"==n.readyState){n.onreadystatechange=null;t()}}:n.onload=function(){t()};n.src=e;document.body.appendChild(n)};s.prototype=new r;t.exports=new s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{events:2,jquery:63}],78:[function(e,t){(function(n){"use strict";function r(e,t,n){function r(e,t,o){var l,u,c,p,d,f,h,g;if(null==e||null==t)return e===t;if(e.__placeholder__||t.__placeholder__)return!0;if(e===t)return 0!==e||1/e==1/t;l=i.call(e);if(i.call(t)!=l)return!1;switch(l){case"[object String]":return e==String(t);case"[object Number]":return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object RegExp]":return e.source==t.source&&e.global==t.global&&e.multiline==t.multiline&&e.ignoreCase==t.ignoreCase}if("object"!=typeof e||"object"!=typeof t)return!1;u=o.length;for(;u--;)if(o[u]==e)return!0;o.push(e);c=0;p=!0;if("[object Array]"==l){d=e.length;f=t.length;if(a){switch(n){case"===":p=d===f;break;case"<==":p=f>=d;break;case"<<=":p=f>d}c=d;a=!1}else{p=d===f;c=d}if(p)for(;c--&&(p=c in e==c in t&&r(e[c],t[c],o)););}else{if("constructor"in e!="constructor"in t||e.constructor!=t.constructor)return!1;for(h in e)if(s(e,h)){c++;if(!(p=s(t,h)&&r(e[h],t[h],o)))break}if(p){g=0;for(h in t)s(t,h)&&++g;if(a)p="<<="===n?g>c:"<=="===n?g>=c:c===g;else{a=!1;p=c===g}}}o.pop();return p}var i={}.toString,o={}.hasOwnProperty,s=function(e,t){return o.call(e,t)},a=!0;return r(e,t,[])}var i=e("jquery"),o=e("./utils.js"),s=e("yasgui-utils"),a=t.exports=function(t){var l=i.extend(!0,{},a.defaults),u=t.container.closest("[id]").attr("id");null==t.options.gchart&&(t.options.gchart={});var c=t.getPersistencyId("motionchart"),p=t.getPersistencyId("chartConfig");null==t.options.gchart.motionChartState&&(t.options.gchart.motionChartState=s.storage.get(c));null==t.options.gchart.chartConfig&&(t.options.gchart.chartConfig=s.storage.get(p));var d=null,f=function(e){var i="undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null;d=new i.visualization.ChartEditor;i.visualization.events.addListener(d,"ok",function(){var e,n;e=d.getChartWrapper();if(!r(e.getChartType,"MotionChart","===")){t.options.gchart.motionChartState=e.n;s.storage.set(c,t.options.gchart.motionChartState);e.setOption("state",t.options.gchart.motionChartState);i.visualization.events.addListener(e,"ready",function(){var n;n=e.getChart();i.visualization.events.addListener(n,"statechange",function(){t.options.gchart.motionChartState=n.getState();s.storage.set(c,t.options.gchart.motionChartState)})})}n=e.getDataTable();e.setDataTable(null);t.options.gchart.chartConfig=e.toJSON();s.storage.set(p,t.options.gchart.chartConfig);e.setDataTable(n);e.draw()});e&&e()};return{name:"Google Chart",hideFromSelection:!1,priority:7,canHandleResults:function(e){var t,n;return null!=(t=e.results)&&(n=t.getVariables())&&n.length>0},getDownloadInfo:function(){if(!t.results)return null;var e=t.resultsContainer.find("svg");return 0==e.length?null:{getContent:function(){return e[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}},draw:function(){var r=function(){t.resultsContainer.empty();var e=u+"_gchartWrapper",n=null;t.resultsContainer.append(i("<button>",{"class":"openGchartBtn yasr_btn"}).text("Chart Config").click(function(){d.openDialog(n)})).append(i("<div>",{id:e,"class":"gchartWrapper"}));var r=new google.visualization.DataTable,a=t.results.getAsJson();a.head.vars.forEach(function(e){var t=o.getGoogleType(a.results.bindings[0][e]);r.addColumn(t,e)});var p=null;t.options.getUsedPrefixes&&(p="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);a.results.bindings.forEach(function(e){var t=[];a.head.vars.forEach(function(n){t.push(o.castGoogleType(e[n],p))});r.addRow(t)});if(t.options.gchart.chartConfig){n=new google.visualization.ChartWrapper(t.options.gchart.chartConfig);if("MotionChart"===n.getChartType()&&null!=t.options.gchart.motionChartState){n.setOption("state",t.options.gchart.motionChartState);google.visualization.events.addListener(n,"ready",function(){var e;e=n.getChart();google.visualization.events.addListener(e,"statechange",function(){t.options.gchart.motionChartState=e.getState();s.storage.set(c,t.options.gchart.motionChartState)})})}n.setDataTable(r)}else n=new google.visualization.ChartWrapper({chartType:"Table",dataTable:r,containerId:e});n.setOption("width",l.width);n.setOption("height",l.height);n.draw();t.updateHeader()};("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)&&("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).visualization&&d?r():e("./gChartLoader.js").on("done",function(){f();r()}).on("error",function(){console.log("errorrr")}).googleLoad()}}};a.defaults={height:"600px",width:"100%",persistencyId:"gchart"}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./gChartLoader.js":77,"./utils.js":90,jquery:63,"yasgui-utils":69}],79:[function(e,t){"use strict";t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<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" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<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" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<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" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></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>',move:'<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" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_11656_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="753" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="287" inkscape:window-y="249" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><polygon points="33,83 50,100 67,83 54,83 54,17 67,17 50,0 33,17 46,17 46,83 " transform="translate(-7.962963,-10)" /><polygon points="83,67 100,50 83,33 83,46 17,46 17,33 0,50 17,67 17,54 83,54 " transform="translate(-7.962963,-10)" /></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],80:[function(e,t){"use strict";var n=e("jquery"),r=e("yasgui-utils");console=console||{log:function(){}};var i=t.exports=function(t,s,a){var l={};l.options=n.extend(!0,{},i.defaults,s);l.container=n("<div class='yasr'></div>").appendTo(t);l.header=n("<div class='yasr_header'></div>").appendTo(l.container);l.resultsContainer=n("<div class='yasr_results'></div>").appendTo(l.container);l.storage=r.storage;var u=null;l.getPersistencyId=function(e){null===u&&(u=l.options.persistency&&l.options.persistency.prefix?"string"==typeof l.options.persistency.prefix?l.options.persistency.prefix:l.options.persistency.prefix(l):!1);return u&&e?u+("string"==typeof e?e:e(l)):null};l.options.useGoogleCharts&&e("./gChartLoader.js").once("initError",function(){l.options.useGoogleCharts=!1}).init();l.plugins={};for(var c in i.plugins)(l.options.useGoogleCharts||"gchart"!=c)&&(l.plugins[c]=new i.plugins[c](l));l.updateHeader=function(){var e=l.header.find(".yasr_downloadIcon").removeAttr("title"),t=l.plugins[l.options.output];if(t){var n=t.getDownloadInfo?t.getDownloadInfo():null;if(n){n.buttonTitle&&e.attr("title",n.buttonTitle);e.prop("disabled",!1);e.find("path").each(function(){this.style.fill="black"})}else{e.prop("disabled",!0).prop("title","Download not supported for this result representation");e.find("path").each(function(){this.style.fill="gray"})}}};l.draw=function(e){if(!l.results)return!1;e||(e=l.options.output);var t=null,r=-1,i=[];for(var o in l.plugins)if(l.plugins[o].canHandleResults(l)){var s=l.plugins[o].getPriority;"function"==typeof s&&(s=s(l));if(null!=s&&void 0!=s&&s>r){r=s;t=o}}else i.push(o);p(i);if(e in l.plugins&&l.plugins[e].canHandleResults(l)){n(l.resultsContainer).empty();l.plugins[e].draw();return!0}if(t){n(l.resultsContainer).empty();l.plugins[t].draw();return!0}return!1};var p=function(e){l.header.find(".yasr_btnGroup .yasr_btn").removeClass("disabled");e.forEach(function(e){l.header.find(".yasr_btnGroup .select_"+e).addClass("disabled")})};l.somethingDrawn=function(){return!l.resultsContainer.is(":empty")};l.setResponse=function(t,n,i){try{l.results=e("./parsers/wrapper.js")(t,n,i)}catch(o){l.results={getException:function(){return o}}}l.draw();var s=l.getPersistencyId(l.options.persistency.results.key);s&&(l.results.getOriginalResponseAsString&&l.results.getOriginalResponseAsString().length<l.options.persistency.results.maxSize?r.storage.set(s,l.results.getAsStoreObject(),"month"):r.storage.remove(s))};var d=l.getPersistencyId(l.options.persistency.outputSelector);if(d){var f=r.storage.get(d);f&&(l.options.output=f)}o(l);if(!a&&l.options.persistency&&l.options.persistency.results){var h,g=l.getPersistencyId(l.options.persistency.results.key);g&&(h=r.storage.get(g));if(!h&&l.options.persistency.results.id){var m="string"==typeof l.options.persistency.results.id?l.options.persistency.results.id:l.options.persistency.results.id(l);if(m){h=r.storage.get(m);h&&r.storage.remove(m)}}h&&(n.isArray(h)?l.setResponse.apply(this,h):l.setResponse(h))}a&&l.setResponse(a);l.updateHeader();return l},o=function(t){var i=function(){var e=n('<div class="yasr_btnGroup"></div>');n.each(t.plugins,function(i,o){if(!o.hideFromSelection){var s=o.name||i,a=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){e.find("button.selected").removeClass("selected");n(this).addClass("selected");t.options.output=i;var o=t.getPersistencyId(t.options.persistency.outputSelector);o&&r.storage.set(o,t.options.output,"month");t.draw();t.updateHeader()}).appendTo(e);t.options.output==i&&a.addClass("selected")}});e.children().length>1&&t.header.append(e)},o=function(){var r=function(e,t){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([e],{type:t});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download)).click(function(){var i=t.plugins[t.options.output];if(i&&i.getDownloadInfo){var o=i.getDownloadInfo(),s=r(o.getContent(),o.contentType?o.contentType:"text/plain"),a=n("<a></a>",{href:s,download:o.filename});e("./utils.js").fireClick(a)}});t.header.append(i)},s=function(){var r=n("<button class='yasr_btn btn_fullscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").fullscreen)).click(function(){t.container.addClass("yasr_fullscreen")});t.header.append(r)},a=function(){var r=n("<button class='yasr_btn btn_smallscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").smallscreen)).click(function(){t.container.removeClass("yasr_fullscreen")});t.header.append(r)};s();a();t.options.drawOutputSelector&&i();t.options.drawDownloadIcon&&o()};i.plugins={};i.registerOutput=function(e,t){i.plugins[e]=t};i.defaults=e("./defaults.js");i.version={YASR:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":e("yasgui-utils").version};i.$=n;try{i.registerOutput("boolean",e("./boolean.js"))}catch(s){}try{i.registerOutput("rawResponse",e("./rawResponse.js"))}catch(s){}try{i.registerOutput("table",e("./table.js"))}catch(s){}try{i.registerOutput("error",e("./error.js"))}catch(s){}try{i.registerOutput("pivot",e("./pivot.js"))}catch(s){}try{i.registerOutput("gchart",e("./gchart.js"))}catch(s){}},{"../package.json":72,"./boolean.js":74,"./defaults.js":75,"./error.js":76,"./gChartLoader.js":77,"./gchart.js":78,"./imgs.js":79,"./parsers/wrapper.js":85,"./pivot.js":87,"./rawResponse.js":88,"./table.js":89,"./utils.js":90,jquery:63,"yasgui-utils":69}],81:[function(e,t){"use strict";e("jquery"),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":82,jquery:63}],82:[function(e,t){"use strict";var n=jQuery=e("jquery");e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var r={},i=n.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},s=function(){if(2==i.length&&1==i[0].length&&1==i[1].length&&"boolean"==i[0][0]&&("1"==i[1][0]||"0"==i[1][0])){r["boolean"]="1"==i[1][0]?!0:!1;return!0}return!1},a=function(){if(i.length>0&&i[0].length>0){r.head={vars:i[0]};return!0}return!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var e=1;e<i.length;e++){for(var t={},n=0;n<i[e].length;n++){var s=r.head.vars[n];if(s){var a=i[e][n],l=o(a);t[s]={value:a};l&&(t[s].type=l)}}r.results.bindings.push(t)}r.head={vars:i[0]};return!0}return!1},u=s();if(!u){var c=a();c&&l()}return r}},{"../../lib/jquery.csv-0.71.js":49,jquery:63}],83:[function(e,t){"use strict";e("jquery"),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:63}],84:[function(e,t){"use strict";e("jquery"),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":82,jquery:63}],85:[function(e,t){"use strict";e("jquery"),t.exports=function(t,n,r){var i={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,s=null,a=null,l=null,u=null,c=function(){if("object"==typeof t){if(t.exception)u=t.exception;else if(void 0!=t.status&&(t.status>=300||0===t.status)){u={status:t.status};"string"==typeof r&&(u.errorString=r);t.responseText&&(u.responseText=t.responseText);t.statusText&&(u.statusText=t.statusText)}if(t.contentType)o=t.contentType.toLowerCase();else if(t.getResponseHeader&&t.getResponseHeader("content-type")){var e=t.getResponseHeader("content-type").trim().toLowerCase();e.length>0&&(o=e)}t.response?s=t.response:n||r||(s=t)}u||s||(s=t.responseText?t.responseText:t)},p=function(){if(a)return a;if(a===!1||u)return!1;var e=function(){if(o)if(o.indexOf("json")>-1){try{a=i.json(s)}catch(e){u=e}l="json"}else if(o.indexOf("xml")>-1){try{a=i.xml(s)}catch(e){u=e}l="xml"}else if(o.indexOf("csv")>-1){try{a=i.csv(s)}catch(e){u=e}l="csv"}else if(o.indexOf("tab-separated")>-1){try{a=i.tsv(s)}catch(e){u=e}l="tsv"}},t=function(){a=i.json(s);if(a)l="json";else try{a=i.xml(s);a&&(l="xml")}catch(e){}};e();a||t();a||(a=!1);return a},d=function(){var e=p();return e&&"head"in e?e.head.vars:null},f=function(){var e=p();return e&&"results"in e?e.results.bindings:null},h=function(){var e=p();return e&&"boolean"in e?e["boolean"]:null},g=function(){return s},m=function(){var e="";"string"==typeof s?e=s:"json"==l?e=JSON.stringify(s,void 0,2):"xml"==l&&(e=(new XMLSerializer).serializeToString(s));return e},v=function(){return u},E=function(){null==l&&p();return l},y=function(){var e={};if(t.status){e.status=t.status;e.responseText=t.responseText;e.statusText=t.statusText;e.contentType=o}else e=t;var i=n,s=void 0;"string"==typeof r&&(s=r);return[e,i,s]};c();a=p();return{getAsStoreObject:y,getAsJson:p,getOriginalResponse:g,getOriginalResponseAsString:m,getOriginalContentType:function(){return o},getVariables:d,getBindings:f,getBoolean:h,getType:E,getException:v}}},{"./csv.js":81,"./json.js":83,"./tsv.js":84,"./xml.js":86,jquery:63}],86:[function(e,t){"use strict";{var n=e("jquery");t.exports=function(e){var t=function(e){s.head={};for(var t=0;t<e.childNodes.length;t++){var n=e.childNodes[t];if("variable"==n.nodeName){s.head.vars||(s.head.vars=[]);var r=n.getAttribute("name");r&&s.head.vars.push(r)}}},r=function(e){s.results={};s.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var n=e.childNodes[t],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var a=o.getAttribute("name");if(a){r=r||{};r[a]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){r[a].type=c;r[a].value=u.innerHTML;var p=u.getAttribute("datatype");p&&(r[a].datatype=p)}}}}}r&&s.results.bindings.push(r)}},i=function(e){s["boolean"]="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=n.parseXML(e):n.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var s={},a=0;a<e.childNodes.length;a++){var l=e.childNodes[a];"head"==l.nodeName&&t(l);"results"==l.nodeName&&r(l);"boolean"==l.nodeName&&i(l)}return s}}},{jquery:63}],87:[function(e,t){"use strict";var n=e("jquery"),r=e("./utils.js"),i=e("yasgui-utils"),o=e("./imgs.js");e("jquery-ui/sortable");e("pivottable");if(!n.fn.pivotUI)throw new Error("Pivot lib not loaded");var s=t.exports=function(t){var a=n.extend(!0,{},s.defaults);if(a.useD3Chart){try{var l=e("d3");l&&e("../node_modules/pivottable/dist/d3_renderers.js")}catch(u){}n.pivotUtilities.d3_renderers&&n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.d3_renderers)}var c,p=null,d=function(){var e=t.results.getVariables();if(!a.mergeLabelsWithUris)return e;var n=[];p="string"==typeof a.mergeLabelsWithUris?a.mergeLabelsWithUris:"Label";e.forEach(function(t){-1!==t.indexOf(p,t.length-p.length)&&e.indexOf(t.substring(0,t.length-p.length))>=0||n.push(t)});return n},f=function(e){var n=d(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);t.results.getBindings().forEach(function(t){var o={};n.forEach(function(e){if(e in t){var n=t[e].value;p&&t[e+p]?n=t[e+p].value:"uri"==t[e].type&&(n=r.uriToPrefixed(i,n));o[e]=n}else o[e]=null});e(o)})},h=t.getPersistencyId(a.persistencyId),g=function(){var e=i.storage.get(h);if(e){var r=t.results.getVariables(),o=!0;e.cols.forEach(function(e){r.indexOf(e)<0&&(o=!1)});o&&e.rows.forEach(function(e){r.indexOf(e)<0&&(o=!1)});if(!o){e.cols=[];e.rows=[]}n.pivotUtilities.renderers[e.rendererName]||delete e.rendererName}else e={};return e},m=function(){var r=function(){var e=function(e){if(h){var n={cols:e.cols,rows:e.rows,rendererName:e.rendererName,aggregatorName:e.aggregatorName,vals:e.vals};i.storage.set(h,n,"month")}e.rendererName.toLowerCase().indexOf(" chart")>=0?r.show():r.hide();t.updateHeader()},r=n("<button>",{"class":"openPivotGchart yasr_btn"}).text("Chart Config").click(function(){c.find('div[dir="ltr"]').dblclick()}).appendTo(t.resultsContainer);c=n("<div>",{"class":"pivotTable"}).appendTo(n(t.resultsContainer));var a=n.extend(!0,{},g(),s.defaults.pivotTable);a.onRefresh=function(){var t=a.onRefresh;return function(n){e(n);t&&t(n)}}();window.pivot=c.pivotUI(f,a);var l=n(i.svg.getElement(o.move));c.find(".pvtTriangle").replaceWith(l);n(".pvtCols").prepend(n("<div>",{"class":"containerHeader"}).text("Columns"));n(".pvtRows").prepend(n("<div>",{"class":"containerHeader"}).text("Rows"));n(".pvtUnused").prepend(n("<div>",{"class":"containerHeader"}).text("Available Variables"));n(".pvtVals").prepend(n("<div>",{"class":"containerHeader"}).text("Cells"));setTimeout(t.updateHeader,400)};t.options.useGoogleCharts&&a.useGoogleCharts&&!n.pivotUtilities.gchart_renderers?e("./gChartLoader.js").on("done",function(){try{e("../node_modules/pivottable/dist/gchart_renderers.js");n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.gchart_renderers)}catch(t){a.useGoogleCharts=!1}r()}).on("error",function(){console.log("could not load gchart");a.useGoogleCharts=!1;r()}).googleLoad():r()},v=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0},E=function(){if(!t.results)return null;var e=t.resultsContainer.find(".pvtRendererArea svg");return 0==e.length?null:{getContent:function(){return e[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}};return{getDownloadInfo:E,options:a,draw:m,name:"Pivot Table",canHandleResults:v,getPriority:4}};s.defaults={mergeLabelsWithUris:!1,useGoogleCharts:!0,useD3Chart:!0,persistencyId:"pivot",pivotTable:{}};s.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery}},{"../node_modules/pivottable/dist/d3_renderers.js":64,"../node_modules/pivottable/dist/gchart_renderers.js":65,"../package.json":72,"./gChartLoader.js":77,"./imgs.js":79,"./utils.js":90,d3:58,jquery:63,"jquery-ui/sortable":61,pivottable:66,"yasgui-utils":69}],88:[function(e,t){"use strict";var n=e("jquery"),r=e("codemirror");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/mode/xml/xml.js");e("codemirror/mode/javascript/javascript.js");var i=t.exports=function(e){var t=n.extend(!0,{},i.defaults),o=null,s=function(){var n=t.CodeMirror;n.value=e.results.getOriginalResponseAsString();var i=e.results.getType();if(i){"json"==i&&(i={name:"javascript",json:!0});n.mode=i}o=r(e.resultsContainer.get()[0],n);o.on("fold",function(){o.refresh()});o.on("unfold",function(){o.refresh()})},a=function(){if(!e.results)return!1;if(!e.results.getOriginalResponseAsString)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},l=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),n=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:s,name:"Raw Response",canHandleResults:a,getPriority:2,getDownloadInfo:l}};i.defaults={CodeMirror:{readOnly:!0,lineNumbers:!0,lineWrapping:!0,foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"]}};i.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":72,codemirror:55,"codemirror/addon/edit/matchbrackets.js":50,"codemirror/addon/fold/brace-fold.js":51,"codemirror/addon/fold/foldcode.js":52,"codemirror/addon/fold/foldgutter.js":53,"codemirror/addon/fold/xml-fold.js":54,"codemirror/mode/javascript/javascript.js":56,"codemirror/mode/xml/xml.js":57,jquery:63}],89:[function(e,t){"use strict";var n=e("jquery"),r=e("yasgui-utils"),i=e("./imgs.js");e("../lib/DataTables/media/js/jquery.dataTables.js");e("../lib/colResizable-1.4.js");var o=t.exports=function(t){var s=null,a={name:"Table",getPriority:10},u=a.options=n.extend(!0,{},o.defaults),c=u.persistency?t.getPersistencyId(u.persistency.tableLength):null,p=function(){var e=[],n=t.results.getBindings(),r=t.results.getVariables(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var s=[];s.push("");for(var l=n[o],c=0;c<r.length;c++){var p=r[c];s.push(p in l?u.getCellContent?u.getCellContent(t,a,l,p,{rowId:o,colId:c,usedPrefixes:i}):"":"")}e.push(s)}return e},d=function(){s.on("order.dt",function(){f()});c&&s.on("length.dt",function(e,t,n){r.storage.set(c,n,"month")});n.extend(!0,u.callbacks,u.handlers);s.delegate("td","click",function(e){if(u.callbacks&&u.callbacks.onCellClick){var t=u.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){u.callbacks&&u.callbacks.onCellMouseEnter&&u.callbacks.onCellMouseEnter(this,e);var t=n(this);u.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&l(t)}).delegate("td","mouseleave",function(e){u.callbacks&&u.callbacks.onCellMouseLeave&&u.callbacks.onCellMouseLeave(this,e)})};a.draw=function(){s=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>');n(t.resultsContainer).html(s);var e=u.datatable;e.data=p();e.columns=u.getColumns(t,a);var i=r.storage.get(c);i&&(e.pageLength=i);s.DataTable(n.extend(!0,{},e));f();d();s.colResizable();s.find("thead").outerHeight();n(t.resultsContainer).find(".JCLRgrip").height(s.find("thead").outerHeight());var o=t.header.outerHeight()-5;if(o>0){t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+o+"px").css("margin-bottom","-"+o+"px");n(t.resultsContainer).find(".JCLRgrip").css("marginTop",o+"px")}};var f=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};s.find(".sortIcons").remove();for(var t in e){var o=n("<div class='sortIcons'></div>");r.svg.draw(o,i[e[t]]);s.find("th."+t).append(o)}};a.canHandleResults=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0};a.getDownloadInfo=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return a},s=function(e,t,n){var r=n.value;if(n["xml:lang"])r='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var i="http://www.w3.org/2001/XMLSchema#",o=n.datatype;o=0==o.indexOf(i)?"xsd:"+o.substring(i.length):"<"+o+">";r='"'+r+'"^^'+o}return r},a=function(e,t,n,r,i){var o=n[r],a=null;if("uri"==o.type){var l=null,u=o.value,c=u;if(i.usedPrefixes)for(var p in i.usedPrefixes)if(0==c.indexOf(i.usedPrefixes[p])){c=p+":"+u.substring(i.usedPrefixes[p].length);break}if(t.options.mergeLabelsWithUris){var d="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";if(n[r+d]){c=s(e,t,n[r+d]);l=u}}a="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+c+"</a>"}else a="<span class='nonUri'>"+s(e,t,o)+"</span>";return"<div>"+a+"</div>"},l=function(e){var t=function(){e.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?e.attr("title",n.label):"string"==typeof n&&n.length>0?e.attr("title",n):t()}).fail(t)};o.defaults={getCellContent:a,persistency:{tableLength:"tableLength"},getColumns:function(e,t){var n=function(n){if(!t.options.mergeLabelsWithUris)return!0;var r="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&e.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];r.push({title:""});e.results.getVariables().forEach(function(e){r.push({title:"<span>"+e+"</span>",visible:n(e)})});return r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!1,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{autoWidth:!1,order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)n("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var r=!1;n(e.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)});r?n(e.nTableWrapper).find(".dataTables_paginate").show():n(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"32px",orderable:!1,targets:0}]}};o.version={"YASR-table":e("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/DataTables/media/js/jquery.dataTables.js":47,"../lib/colResizable-1.4.js":48,"../package.json":72,"./bindingsToCsv.js":73,"./imgs.js":79,jquery:63,"yasgui-utils":69}],90:[function(e,t){"use strict";var n=e("jquery");t.exports={uriToPrefixed:function(e,t){if(e)for(var n in e)if(0==t.indexOf(e[n])){t=n+":"+t.substring(e[n].length);break}return t},getGoogleType:function(e){if(null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return"string";switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return"number";case"http://www.w3.org/2001/XMLSchema#date":return"date";case"http://www.w3.org/2001/XMLSchema#dateTime":return"datetime";case"http://www.w3.org/2001/XMLSchema#time":return"timeofday";default:return"string"}},castGoogleType:function(e,n){if(null==e)return null;if(null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return(e.type="uri")?t.exports.uriToPrefixed(n,e.value):e.value;switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return Number(e.value);case"http://www.w3.org/2001/XMLSchema#date":case"http://www.w3.org/2001/XMLSchema#dateTime":case"http://www.w3.org/2001/XMLSchema#time":return new Date(e.value);default:return e.value}},fireClick:function(e){e&&e.each(function(e,t){var r=n(t);if(document.dispatchEvent){var i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!0,window,1,1,1,1,1,!1,!1,!1,!1,0,r[0]);r[0].dispatchEvent(i)}else document.fireEvent&&r[0].click()})}}},{jquery:63}],91:[function(e,t){"use strict";var n=e("jquery");t.exports={persistencyPrefix:function(e){return"yasgui_"+n(e.wrapperElement).closest("[id]").attr("id")+"_"},api:{corsProxy:null}}},{jquery:4}],92:[function(e,t){"use strict";t.exports={persistent:null,consumeShareLink:null,createShareLink:null,sparql:{showQueryButton:!0,acceptHeaderGraph:"text/turtle",acceptHeaderSelect:"application/sparql-results+json"}}},{}],93:[function(e,t){"use strict";t.exports={yasgui:'<svg xmlns:osb="http://www.openswatchbook.org/uri/2009/osb" 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" viewBox="0 0 603.99 522.51" width="100%" height="100%" id="svg2" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="yasgui (copy).svg"> <defs id="defs4"> <linearGradient id="linearGradient5249" osb:paint="solid"> <stop style="stop-color:#3b3b3b;stop-opacity:1;" offset="0" id="stop5251" /> </linearGradient> <inkscape:path-effect effect="skeletal" id="path-effect2997" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" id="path-effect2995" is_visible="true" /> <inkscape:path-effect effect="skeletal" id="path-effect2991" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" id="path-effect2989" is_visible="true" /> </defs> <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.35" inkscape:cx="-469.55507" inkscape:cy="840.5292" inkscape:document-units="px" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="1855" inkscape:window-height="1056" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" /> <metadata id="metadata7"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title /> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(-50.966817,-280.33262)"> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" id="rect5293-6-8" width="40.000004" height="478.57324" x="-374.48849" y="103.99496" transform="matrix(-2.679181e-4,-0.99999996,0.99999993,-3.6684387e-4,0,0)" /> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" id="rect5293-5-7" width="40.000004" height="560" x="651.37634" y="-132.06581" transform="matrix(0.74639582,0.66550228,-0.66550228,0.74639582,0,0)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" id="path3781-9-0-7-1-9-7" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,92.132758,620.67568)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" id="path3781-9-0-7-1-3-0" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,457.84706,214.96137)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" id="path3781-9-0-7-1-1-2" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,-30.152972,219.81853)" /> <text xml:space="preserve" style="font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#3b3b3b;fill-opacity:1;stroke:none;font-family:Sans" x="-387.96655" y="630.61871" id="text5479-9-0-6-4" sodipodi:linespacing="125%" transform="matrix(0.68747304,-0.7262099,0.7262099,0.68747304,0,0)" inkscape:transform-center-x="239.86342" inkscape:transform-center-y="-26.958107"><tspan sodipodi:role="line" id="tspan5481-8-8-9-7" x="-387.96655" y="630.61871" style="font-size:200px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;fill-opacity:1;font-family:RR Beaver;-inkscape-font-specification:RR Beaver">YAS</tspan></text> <text xml:space="preserve" style="font-size:40px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Theorem NBP;-inkscape-font-specification:Theorem NBP" x="349.24683" y="750.29126" id="text5483-4-3-2" sodipodi:linespacing="125%"><tspan sodipodi:role="line" id="tspan5485-6-5-7" x="349.24683" y="750.29126" style="font-size:170px;font-style:italic;font-variant:normal;font-weight:bold;font-stretch:normal;letter-spacing:20px;fill:#c80000;fill-opacity:1;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic">GUI</tspan></text> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" id="path3781-9-7-4-1-4" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.4331683,0,0,0.38716814,381.83246,155.72497)" /> </g></svg>',cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',plus:'<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="5 -10 59.259258 79.999999" enable-background="new 0 0 100 100" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_79066_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="6.675088" inkscape:cx="46.670641" inkscape:cy="16.037704" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Your_Icon" /><g transform="translate(-23.47037,-20)"><g ><g ><g /></g><g /></g></g><path d="M 67.12963,22.5 H 42.129629 v -25 c 0,-4.142 -3.357,-7.5 -7.5,-7.5 -4.141999,0 -7.5,3.358 -7.5,7.5 v 25 H 2.1296295 c -4.142,0 -7.5,3.358 -7.5,7.5 0,4.143 3.358,7.5 7.5,7.5 H 27.129629 v 25 c 0,4.143 3.358001,7.5 7.5,7.5 4.143,0 7.5,-3.357 7.5,-7.5 v -25 H 67.12963 c 4.143,0 7.5,-3.357 7.5,-7.5 0,-4.142 -3.357,-7.5 -7.5,-7.5 z" inkscape:connector-curvature="0" style="fill:#000000" /></svg>'}
},{}],94:[function(e){"use strict";var t=e("jquery"),n=e("selectize"),r=e("yasgui-utils");n.define("allowRegularTextInput",function(){var e=this;this.onMouseDown=function(){var t=e.onMouseDown;return function(n){if(e.$dropdown.is(":visible")){n.stopPropagation();n.preventDefault()}else{t.apply(this,arguments);var r=this.getValue();this.clear(!0);this.setTextboxValue(r);this.refreshOptions(!0)}}}()});t.fn.endpointCombi=function(e,n){var o=function(n){e.corsEnabled||(e.corsEnabled={});n in e.corsEnabled||t.ajax({url:n,data:{query:"ASK {?x ?y ?z}"},complete:function(t){e.corsEnabled[n]=t.status>0}})},s=function(t){var n=null;e.persistencyPrefix&&(n=e.persistencyPrefix+"endpoint_"+t);var i=[];for(var o in l[0].selectize.options){var s=l[0].selectize.options[o];if(s.optgroup==t){var a={endpoint:s.endpoint};s.text&&(a.label=s.text);i.push(a)}}r.storage.set(n,i)},a=function(t,n){var o=null;e.persistencyPrefix&&(o=e.persistencyPrefix+"endpoint_"+n);var s=r.storage.get(o);if(!s&&"catalogue"==n){s=i();r.storage.set(o,s)}t(s,n)},l=this,u={selectize:{plugins:["allowRegularTextInput"],create:function(e,t){t({endpoint:e,optgroup:"own"})},createOnBlur:!0,onItemAdd:function(t){n.onChange&&n.onChange(t);e.options.api.corsProxy&&o(t)},onOptionRemove:function(){s("own");s("catalogue")},optgroups:[{value:"own",label:"History"},{value:"catalogue",label:"Catalogue"}],optgroupOrder:["own","catalogue"],sortField:"endpoint",valueField:"endpoint",labelField:"endpoint",searchField:["endpoint","text"],render:{option:function(e,t){var n='<a href="javascript:void(0)" class="close pull-right" tabindex="-1" title="Remove from '+("own"==e.optgroup?"history":"catalogue")+'">×</a>',r='<div class="endpointUrl">'+t(e.endpoint)+"</div>",i="";e.text&&(i='<div class="endpointTitle">'+t(e.text)+"</div>");return'<div class="endpointOptionRow">'+n+r+i+"</div>"}}}};n=n?t.extend(!0,{},u,n):u;this.addClass("endpointText form-control");this.selectize(n.selectize);l[0].selectize.$dropdown.off("mousedown","[data-selectable]");l[0].selectize.$dropdown.on("mousedown","[data-selectable]",function(e){var n,r,i=l[0].selectize;if(e.preventDefault){e.preventDefault();e.stopPropagation()}r=t(e.currentTarget);if(t(e.target).hasClass("close")){l[0].selectize.removeOption(r.attr("data-value"));l[0].selectize.refreshOptions()}else if(r.hasClass("create"))i.createItem();else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);!i.settings.hideSelected&&e.type&&/mouse/.test(e.type)&&i.setActiveOption(i.getOption(n))}}});var c=function(e,t){t.optgroup&&s(t.optgroup)},p=function(e,t){if(e){l[0].selectize.off("option_add",c);e.forEach(function(e){l[0].selectize.addOption({endpoint:e.endpoint,text:e.title,optgroup:t})});l[0].selectize.on("option_add",c)}};a(p,"catalogue");a(p,"own");if(n.value){n.value in l[0].selectize.options||l[0].selectize.addOption({endpoint:n.value,optgroup:"own"});l[0].selectize.addItem(n.value)}return this};var i=function(){var e=[{endpoint:"http%3A%2F%2Fvisualdataweb.infor.uva.es%2Fsparql"},{endpoint:"http%3A%2F%2Fbiolit.rkbexplorer.com%2Fsparql",title:"A Short Biographical Dictionary of English Literature (RKBExplorer)"},{endpoint:"http%3A%2F%2Faemet.linkeddata.es%2Fsparql",title:"AEMET metereological dataset"},{endpoint:"http%3A%2F%2Fsparql.jesandco.org%3A8890%2Fsparql",title:"ASN:US"},{endpoint:"http%3A%2F%2Fdata.allie.dbcls.jp%2Fsparql",title:"Allie Abbreviation And Long Form Database in Life Science"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FAustrianSkiTeam",title:"Alpine Ski Racers of Austria"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Feuropeana%2Fsparql%2F",title:"Amsterdam Museum as Linked Open Data in the Europeana Data Model"},{endpoint:"http%3A%2F%2Fopendata.aragon.es%2Fsparql",title:"AragoDBPedia"},{endpoint:"http%3A%2F%2Fdata.archiveshub.ac.uk%2Fsparql",title:"Archives Hub Linked Data"},{endpoint:"http%3A%2F%2Fwww.auth.gr%2Fsparql",title:"Aristotle University"},{endpoint:"http%3A%2F%2Facm.rkbexplorer.com%2Fsparql%2F",title:"Association for Computing Machinery (ACM) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fabs.270a.info%2Fsparql",title:"Australian Bureau of Statistics (ABS) Linked Data"},{endpoint:"http%3A%2F%2Flab.environment.data.gov.au%2Fsparql",title:"Australian Climate Observations Reference Network - Surface Air Temperature Dataset"},{endpoint:"http%3A%2F%2Flod.b3kat.de%2Fsparql",title:"B3Kat - Library Union Catalogues of Bavaria, Berlin and Brandenburg"},{endpoint:"http%3A%2F%2Fdati.camera.it%2Fsparql"},{endpoint:"http%3A%2F%2Fbis.270a.info%2Fsparql",title:"Bank for International Settlements (BIS) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fbdgp_20081030",title:"Bdgp"},{endpoint:"http%3A%2F%2Faffymetrix.bio2rdf.org%2Fsparql",title:"Bio2RDF::Affymetrix"},{endpoint:"http%3A%2F%2Fbiomodels.bio2rdf.org%2Fsparql",title:"Bio2RDF::Biomodels"},{endpoint:"http%3A%2F%2Fbioportal.bio2rdf.org%2Fsparql",title:"Bio2RDF::Bioportal"},{endpoint:"http%3A%2F%2Fclinicaltrials.bio2rdf.org%2Fsparql",title:"Bio2RDF::Clinicaltrials"},{endpoint:"http%3A%2F%2Fctd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ctd"},{endpoint:"http%3A%2F%2Fdbsnp.bio2rdf.org%2Fsparql",title:"Bio2RDF::Dbsnp"},{endpoint:"http%3A%2F%2Fdrugbank.bio2rdf.org%2Fsparql",title:"Bio2RDF::Drugbank"},{endpoint:"http%3A%2F%2Fgenage.bio2rdf.org%2Fsparql",title:"Bio2RDF::Genage"},{endpoint:"http%3A%2F%2Fgendr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Gendr"},{endpoint:"http%3A%2F%2Fgoa.bio2rdf.org%2Fsparql",title:"Bio2RDF::Goa"},{endpoint:"http%3A%2F%2Fhgnc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Hgnc"},{endpoint:"http%3A%2F%2Fhomologene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Homologene"},{endpoint:"http%3A%2F%2Finoh.bio2rdf.org%2Fsparql",title:"Bio2RDF::INOH"},{endpoint:"http%3A%2F%2Finterpro.bio2rdf.org%2Fsparql",title:"Bio2RDF::Interpro"},{endpoint:"http%3A%2F%2Fiproclass.bio2rdf.org%2Fsparql",title:"Bio2RDF::Iproclass"},{endpoint:"http%3A%2F%2Firefindex.bio2rdf.org%2Fsparql",title:"Bio2RDF::Irefindex"},{endpoint:"http%3A%2F%2Fbiopax.kegg.bio2rdf.org%2Fsparql",title:"Bio2RDF::KEGG::BioPAX"},{endpoint:"http%3A%2F%2Flinkedspl.bio2rdf.org%2Fsparql",title:"Bio2RDF::Linkedspl"},{endpoint:"http%3A%2F%2Flsr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Lsr"},{endpoint:"http%3A%2F%2Fmesh.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mesh"},{endpoint:"http%3A%2F%2Fmgi.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mgi"},{endpoint:"http%3A%2F%2Fncbigene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ncbigene"},{endpoint:"http%3A%2F%2Fndc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ndc"},{endpoint:"http%3A%2F%2Fnetpath.bio2rdf.org%2Fsparql",title:"Bio2RDF::NetPath"},{endpoint:"http%3A%2F%2Fomim.bio2rdf.org%2Fsparql",title:"Bio2RDF::Omim"},{endpoint:"http%3A%2F%2Forphanet.bio2rdf.org%2Fsparql",title:"Bio2RDF::Orphanet"},{endpoint:"http%3A%2F%2Fpid.bio2rdf.org%2Fsparql",title:"Bio2RDF::PID"},{endpoint:"http%3A%2F%2Fbiopax.pharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::PharmGKB::BioPAX"},{endpoint:"http%3A%2F%2Fpharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::Pharmgkb"},{endpoint:"http%3A%2F%2Fpubchem.bio2rdf.org%2Fsparql",title:"Bio2RDF::PubChem"},{endpoint:"http%3A%2F%2Frhea.bio2rdf.org%2Fsparql",title:"Bio2RDF::Rhea"},{endpoint:"http%3A%2F%2Fspike.bio2rdf.org%2Fsparql",title:"Bio2RDF::SPIKE"},{endpoint:"http%3A%2F%2Fsabiork.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sabiork"},{endpoint:"http%3A%2F%2Fsgd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sgd"},{endpoint:"http%3A%2F%2Fsider.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sider"},{endpoint:"http%3A%2F%2Ftaxonomy.bio2rdf.org%2Fsparql",title:"Bio2RDF::Taxonomy"},{endpoint:"http%3A%2F%2Fwikipathways.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wikipathways"},{endpoint:"http%3A%2F%2Fwormbase.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wormbase"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiomodels%2Fsparql",title:"BioModels RDF"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiosamples%2Fsparql",title:"BioSamples RDF"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fbizkaisense%2Fsparql",title:"BizkaiSense"},{endpoint:"http%3A%2F%2Fbnb.data.bl.uk%2Fsparql"},{endpoint:"http%3A%2F%2Fbudapest.rkbexplorer.com%2Fsparql%2F",title:"Budapest University of Technology and Economics (RKBExplorer)"},{endpoint:"http%3A%2F%2Fbfs.270a.info%2Fsparql",title:"Bundesamt für Statistik (BFS) - Swiss Federal Statistical Office (FSO) Linked Data"},{endpoint:"http%3A%2F%2Fopendata-bundestag.de%2Fsparql",title:"BundestagNebeneinkuenfte"},{endpoint:"http%3A%2F%2Fdata.colinda.org%2Fendpoint.php",title:"COLINDA - Conference Linked Data"},{endpoint:"http%3A%2F%2Fcrtm.linkeddata.es%2Fsparql",title:"CRTM"},{endpoint:"http%3A%2F%2Fdata.fundacionctic.org%2Fsparql",title:"CTIC Public Dataset Catalogs"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fchembl%2Fsparql",title:"ChEMBL RDF"},{endpoint:"http%3A%2F%2Fchebi.bio2rdf.org%2Fsparql",title:"Chemical Entities of Biological Interest (ChEBI)"},{endpoint:"http%3A%2F%2Fciteseer.rkbexplorer.com%2Fsparql%2F",title:"CiteSeer (Research Index) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcordis.rkbexplorer.com%2Fsparql%2F",title:"Community R&D Information Service (CORDIS) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsemantic.ckan.net%2Fsparql%2F",title:"Comprehensive Knowledge Archive Network"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Fcourt",title:"Courts thesaurus"},{endpoint:"http%3A%2F%2Fcultura.linkeddata.es%2Fsparql",title:"CulturaLinkedData"},{endpoint:"http%3A%2F%2Fdblp.rkbexplorer.com%2Fsparql%2F",title:"DBLP Computer Science Bibliography (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdblp.l3s.de%2Fd2r%2Fsparql",title:"DBLP in RDF (L3S)"},{endpoint:"http%3A%2F%2Fdbtune.org%2Fmusicbrainz%2Fsparql",title:"DBTune.org Musicbrainz D2R Server"},{endpoint:"http%3A%2F%2Fdbpedia.org%2Fsparql",title:"DBpedia"},{endpoint:"http%3A%2F%2Feu.dbpedia.org%2Fsparql",title:"DBpedia in Basque"},{endpoint:"http%3A%2F%2Fnl.dbpedia.org%2Fsparql",title:"DBpedia in Dutch"},{endpoint:"http%3A%2F%2Ffr.dbpedia.org%2Fsparql",title:"DBpedia in French"},{endpoint:"http%3A%2F%2Fde.dbpedia.org%2Fsparql",title:"DBpedia in German"},{endpoint:"http%3A%2F%2Fja.dbpedia.org%2Fsparql",title:"DBpedia in Japanese"},{endpoint:"http%3A%2F%2Fpt.dbpedia.org%2Fsparql",title:"DBpedia in Portuguese"},{endpoint:"http%3A%2F%2Fes.dbpedia.org%2Fsparql",title:"DBpedia in Spanish"},{endpoint:"http%3A%2F%2Flive.dbpedia.org%2Fsparql",title:"DBpedia-Live"},{endpoint:"http%3A%2F%2Fdeploy.rkbexplorer.com%2Fsparql%2F",title:"DEPLOY (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F"},{endpoint:"http%3A%2F%2Fdatos.bcn.cl%2Fsparql",title:"Datos.bcn.cl"},{endpoint:"http%3A%2F%2Fdeepblue.rkbexplorer.com%2Fsparql%2F",title:"Deep Blue (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdewey.info%2Fsparql.php",title:"Dewey Decimal Classification (DDC)"},{endpoint:"http%3A%2F%2Frdf.disgenet.org%2Fsparql%2F",title:"DisGeNET"},{endpoint:"http%3A%2F%2Fitaly.rkbexplorer.com%2Fsparql",title:"Diverse Italian ReSIST Partner Institutions (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdutchshipsandsailors.nl%2Fdata%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fdss%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fwww.eclap.eu%2Fsparql",title:"ECLAP"},{endpoint:"http%3A%2F%2Fcr.eionet.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Fera.rkbexplorer.com%2Fsparql%2F",title:"ERA - Australian Research Council publication ratings (RKBExplorer)"},{endpoint:"http%3A%2F%2Fkent.zpr.fer.hr%3A8080%2FeducationalProgram%2Fsparql",title:"Educational programs - SISVU"},{endpoint:"http%3A%2F%2Fwebenemasuno.linkeddata.es%2Fsparql",title:"El Viajero's tourism dataset"},{endpoint:"http%3A%2F%2Fwww.ida.liu.se%2Fprojects%2Fsemtech%2Fopenrdf-sesame%2Frepositories%2Fenergy",title:"Energy efficiency assessments and improvements"},{endpoint:"http%3A%2F%2Fheritagedata.org%2Flive%2Fsparql"},{endpoint:"http%3A%2F%2Fenipedia.tudelft.nl%2Fsparql",title:"Enipedia - Energy Industry Data"},{endpoint:"http%3A%2F%2Fenvironment.data.gov.uk%2Fsparql%2Fbwq%2Fquery",title:"Environment Agency Bathing Water Quality"},{endpoint:"http%3A%2F%2Fecb.270a.info%2Fsparql",title:"European Central Bank (ECB) Linked Data"},{endpoint:"http%3A%2F%2Fsemantic.eea.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Feuropeana.ontotext.com%2Fsparql"},{endpoint:"http%3A%2F%2Feventmedia.eurecom.fr%2Fsparql",title:"EventMedia"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fforge%2Fquery",title:"FORGE Course information"},{endpoint:"http%3A%2F%2Ffactforge.net%2Fsparql",title:"Fact Forge"},{endpoint:"http%3A%2F%2Flogd.tw.rpi.edu%2Fsparql"},{endpoint:"http%3A%2F%2Ffrb.270a.info%2Fsparql",title:"Federal Reserve Board (FRB) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflybase",title:"Flybase"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyted",title:"Flyted"},{endpoint:"http%3A%2F%2Ffao.270a.info%2Fsparql",title:"Food and Agriculture Organization of the United Nations (FAO) Linked Data"},{endpoint:"http%3A%2F%2Fft.rkbexplorer.com%2Fsparql%2F",title:"France Telecom Recherche et Développement (RKBExplorer)"},{endpoint:"http%3A%2F%2Flisbon.rkbexplorer.com%2Fsparql",title:"Fundação da Faculdade de Ciencas da Universidade de Lisboa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fatlas%2Fsparql",title:"Gene Expression Atlas RDF"},{endpoint:"http%3A%2F%2Fgeo.linkeddata.es%2Fsparql",title:"GeoLinkedData"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicTimeScale",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicUnit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Flithology",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Ftectonicunit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Farbeitsrecht",title:"German labor law thesaurus"},{endpoint:"http%3A%2F%2Fdata.globalchange.gov%2Fsparql",title:"Global Change Information System"},{endpoint:"http%3A%2F%2Fwordnet.okfn.gr%3A8890%2Fsparql%2F",title:"Greek Wordnet"},{endpoint:"http%3A%2F%2Flod.hebis.de%2Fsparql",title:"HeBIS - Bibliographic Resources of the Library Union Catalogues of Hessen and parts of the Rhineland Palatinate"},{endpoint:"http%3A%2F%2Fhealthdata.tw.rpi.edu%2Fsparql",title:"HealthData.gov Platform (HDP) on the Semantic Web"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fhedatuz%2Fsparql",title:"Hedatuz"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Ffire-brigade%2Fsparql",title:"Hellenic Fire Brigade"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Fpolice%2Fsparql",title:"Hellenic Police"},{endpoint:"http%3A%2F%2Fsetaria.oszk.hu%2Fsparql",title:"Hungarian National Library (NSZL) catalog"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fiati%2Fsparql%2F",title:"IATI as Linked Data"},{endpoint:"http%3A%2F%2Fibm.rkbexplorer.com%2Fsparql%2F",title:"IBM Research GmbH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.icane.es%2Fopendata%2Fsparql",title:"ICANE"},{endpoint:"http%3A%2F%2Fieee.rkbexplorer.com%2Fsparql%2F",title:"IEEE Papers (RKBExplorer)"},{endpoint:"http%3A%2F%2Fieeevis.tw.rpi.edu%2Fsparql",title:"IEEE VIS Source Data"},{endpoint:"http%3A%2F%2Fwww.imagesnippets.com%2Fsparql%2Fimages",title:"Imagesnippets Image Descriptions"},{endpoint:"http%3A%2F%2Fopendatacommunities.org%2Fsparql"},{endpoint:"http%3A%2F%2Fpurl.org%2Ftwc%2Fhub%2Fsparql",title:"Instance Hub (all)"},{endpoint:"http%3A%2F%2Feurecom.rkbexplorer.com%2Fsparql%2F",title:"Institut Eurécom (RKBExplorer)"},{endpoint:"http%3A%2F%2Fimf.270a.info%2Fsparql",title:"International Monetary Fund (IMF) Linked Data"},{endpoint:"http%3A%2F%2Fwww.rechercheisidore.fr%2Fsparql",title:"Isidore"},{endpoint:"http%3A%2F%2Fsparql.kupkb.org%2Fsparql",title:"Kidney and Urinary Pathway Knowledge Base"},{endpoint:"http%3A%2F%2Fkisti.rkbexplorer.com%2Fsparql%2F",title:"Korean Institute of Science Technology and Information (RKBExplorer)"},{endpoint:"http%3A%2F%2Flod.kaist.ac.kr%2Fsparql",title:"Korean Traditional Recipes"},{endpoint:"http%3A%2F%2Flaas.rkbexplorer.com%2Fsparql%2F",title:"LAAS-CNRS (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsmartcity.linkeddata.es%2Fsparql",title:"LCC (Leeds City Council Energy Consumption Linked Data)"},{endpoint:"http%3A%2F%2Flod.ac%2Fbdls%2Fsparql",title:"LODAC BDLS"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Flak-conference%2Fsparql",title:"Learning Analytics and Knowledge (LAK) Dataset"},{endpoint:"http%3A%2F%2Fwww.linklion.org%3A8890%2Fsparql",title:"LinkLion - A Link Repository for the Web of Data"},{endpoint:"http%3A%2F%2Fsparql.reegle.info%2F",title:"Linked Clean Energy Data (reegle.info)"},{endpoint:"http%3A%2F%2Fsparql.contextdatacloud.org",title:"Linked Crowdsourced Data"},{endpoint:"http%3A%2F%2Flinkedlifedata.com%2Fsparql",title:"Linked Life Data"},{endpoint:"http%3A%2F%2Fdata.logainm.ie%2Fsparql",title:"Linked Logainm"},{endpoint:"http%3A%2F%2Fdata.linkedmdb.org%2Fsparql",title:"Linked Movie DataBase"},{endpoint:"http%3A%2F%2Fdata.aalto.fi%2Fsparql",title:"Linked Open Aalto Data Service"},{endpoint:"http%3A%2F%2Fdbmi-icode-01.dbmi.pitt.edu%2FlinkedSPLs%2Fsparql",title:"Linked Structured Product Labels"},{endpoint:"http%3A%2F%2Flinkedgeodata.org%2Fsparql%2F",title:"LinkedGeoData"},{endpoint:"http%3A%2F%2Flinkedspending.aksw.org%2Fsparql",title:"LinkedSpending: OpenSpending becomes Linked Open Data"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Flinkedstats%2Fsparql",title:"LinkedStats"},{endpoint:"http%3A%2F%2Flinkedu.eu%2Fcatalogue%2Fsparql%2F",title:"LinkedUp Catalogue of Educational Datasets"},{endpoint:"http%3A%2F%2Fid.sgcb.mcu.es%2Fsparql",title:"Lista de Encabezamientos de Materia as Linked Open Data"},{endpoint:"http%3A%2F%2Fonto.mondis.cz%2Fopenrdf-sesame%2Frepositories%2Fmondis-record-owlim",title:"MONDIS"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Flabman%2Fsparql",title:"MORElab"},{endpoint:"http%3A%2F%2Fsparql.msc2010.org",title:"Mathematics Subject Classification"},{endpoint:"http%3A%2F%2Fdoc.metalex.eu%3A8000%2Fsparql%2F",title:"MetaLex Document Server"},{endpoint:"http%3A%2F%2Frdf.muninn-project.org%2Fsparql",title:"Muninn World War I"},{endpoint:"http%3A%2F%2Flod.sztaki.hu%2Fsparql",title:"National Digital Data Archive of Hungary (partial)"},{endpoint:"http%3A%2F%2Fnsf.rkbexplorer.com%2Fsparql%2F",title:"National Science Foundation (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.nobelprize.org%2Fsparql",title:"Nobel Prizes"},{endpoint:"http%3A%2F%2Fdata.lenka.no%2Fsparql",title:"Norwegian geo-divisions"},{endpoint:"http%3A%2F%2Fspatial.ucd.ie%2Flod%2Fsparql",title:"OSM Semantic Network"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fdon%2Fquery",title:"OUNL DSpace in RDF"},{endpoint:"http%3A%2F%2Fdata.oceandrilling.org%2Fsparql"},{endpoint:"http%3A%2F%2Fonto.beef.org.pl%2Fsparql",title:"OntoBeef"},{endpoint:"http%3A%2F%2Foai.rkbexplorer.com%2Fsparql%2F",title:"Open Archive Initiative Harvest over OAI-PMH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Focw%2Fquery",title:"Open Courseware Consortium metadata in RDF"},{endpoint:"http%3A%2F%2Fopendata.ccd.uniroma2.it%2FLMF%2Fsparql%2Fselect",title:"Open Data @ Tor Vergata"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FOpenData",title:"Open Data Thesaurus"},{endpoint:"http%3A%2F%2Fdata.cnr.it%2Fsparql-proxy%2F",title:"Open Data from the Italian National Research Council"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Fecuadorresearch%2Flod%2Fsparql",title:"Open Data of Ecuador"},{endpoint:"http%3A%2F%2Fen.openei.org%2Fsparql",title:"OpenEI - Open Energy Info"},{endpoint:"http%3A%2F%2Flod.openlinksw.com%2Fsparql",title:"OpenLink Software LOD Cache"},{endpoint:"http%3A%2F%2Fsparql.openmobilenetwork.org",title:"OpenMobileNetwork"},{endpoint:"http%3A%2F%2Fapps.ideaconsult.net%3A8080%2Fontology",title:"OpenTox"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fcoins%2Fsparql",title:"OpenUpLabs COINS"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fdclg%2Fsparql",title:"OpenUpLabs DCLG"},{endpoint:"http%3A%2F%2Fos.services.tso.co.uk%2Fgeo%2Fsparql",title:"OpenUpLabs Geographic"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Flegislation%2Fsparql",title:"OpenUpLabs Legislation"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Ftransport%2Fsparql",title:"OpenUpLabs Transport"},{endpoint:"http%3A%2F%2Fos.rkbexplorer.com%2Fsparql%2F",title:"Ordnance Survey (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.organic-edunet.eu%2Fsparql",title:"Organic Edunet Linked Open Data"},{endpoint:"http%3A%2F%2Foecd.270a.info%2Fsparql",title:"Organisation for Economic Co-operation and Development (OECD) Linked Data"},{endpoint:"https%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F",title:"OxPoints (University of Oxford)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fprod%2Fquery",title:"PROD - JISC Project Directory in RDF"},{endpoint:"http%3A%2F%2Fld.panlex.org%2Fsparql",title:"PanLex"},{endpoint:"http%3A%2F%2Flinked-data.org%2Fsparql",title:"Phonetics Information Base and Lexicon (PHOIBLE)"},{endpoint:"http%3A%2F%2Flinked.opendata.cz%2Fsparql",title:"Publications of Charles University in Prague"},{endpoint:"http%3A%2F%2Flinkeddata4.dia.fi.upm.es%3A8907%2Fsparql",title:"RDFLicense"},{endpoint:"http%3A%2F%2Frisks.rkbexplorer.com%2Fsparql%2F",title:"RISKS Digest (RKBExplorer)"},{endpoint:"http%3A%2F%2Fruian.linked.opendata.cz%2Fsparql",title:"RUIAN - Register of territorial identification, addresses and real estates of the Czech Republic"},{endpoint:"http%3A%2F%2Fcurriculum.rkbexplorer.com%2Fsparql%2F",title:"ReSIST MSc in Resilient Computing Curriculum (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwiki.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Project Wiki (RKBExplorer)"},{endpoint:"http%3A%2F%2Fresex.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Resilience Mechanisms (RKBExplorer.com)"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Freactome%2Fsparql",title:"Reactome RDF"},{endpoint:"http%3A%2F%2Flod.xdams.org%2Fsparql"},{endpoint:"http%3A%2F%2Frae2001.rkbexplorer.com%2Fsparql%2F",title:"Research Assessment Exercise 2001 (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcourseware.rkbexplorer.com%2Fsparql%2F",title:"Resilient Computing Courseware (RKBExplorer)"},{endpoint:"http%3A%2F%2Flink.informatics.stonybrook.edu%2Fsparql%2F",title:"RxNorm"},{endpoint:"http%3A%2F%2Fdata.rism.info%2Fsparql"},{endpoint:"http%3A%2F%2Fbiordf.net%2Fsparql",title:"SADI Semantic Web Services framework registry"},{endpoint:"http%3A%2F%2Fseek.rkbexplorer.com%2Fsparql%2F",title:"SEEK-AT-WD ICT tools for education - Web-Share"},{endpoint:"http%3A%2F%2Fzbw.eu%2Fbeta%2Fsparql%2Fstw%2Fquery",title:"STW Thesaurus for Economics"},{endpoint:"http%3A%2F%2Fsouthampton.rkbexplorer.com%2Fsparql%2F",title:"School of Electronics and Computer Science, University of Southampton (RKBExplorer)"},{endpoint:"http%3A%2F%2Fserendipity.utpl.edu.ec%2Flod%2Fsparql",title:"Serendipity"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fslidewiki%2Fquery",title:"Slidewiki (RDF/SPARQL)"},{endpoint:"http%3A%2F%2Fsmartlink.open.ac.uk%2Fsmartlink%2Fsparql",title:"SmartLink: Linked Services Non-Functional Properties"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Feac",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Fsnac-viaf",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2Fsemweb",title:"Social Semantic Web Thesaurus"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fsparql",title:"Spanish Linguistic Datasets"},{endpoint:"http%3A%2F%2Fcrashmap.okfn.gr%3A8890%2Fsparql",title:"Statistics on Fatal Traffic Accidents in greek roads"},{endpoint:"http%3A%2F%2Fcrime.rkbexplorer.com%2Fsparql%2F",title:"Street level crime reports for England and Wales"},{endpoint:"http%3A%2F%2Fsymbolicdata.org%3A8890%2Fsparql",title:"SymbolicData"},{endpoint:"http%3A%2F%2Fagalpha.mathbiol.org%2Frepositories%2Ftcga",title:"TCGA Roadmap"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Ftcm",title:"TCMGeneDIT Dataset"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Fted%2Fsparql",title:"TED Talks"},{endpoint:"http%3A%2F%2Fdarmstadt.rkbexplorer.com%2Fsparql%2F",title:"Technische Universität Darmstadt (RKBExplorer)"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fterminesp%2Fsparql-editor",title:"Terminesp Linked Data"},{endpoint:"http%3A%2F%2Facademia6.poolparty.biz%2FPoolParty%2Fsparql%2FTesauro-Materias-BUPM",title:"Tesauro materias BUPM"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Fteseo%2Fsparql",title:"Teseo"},{endpoint:"http%3A%2F%2Flinkeddata.ge.imati.cnr.it%3A8890%2Fsparql",title:"ThIST"},{endpoint:"http%3A%2F%2Fring.ciard.net%2Fsparql1",title:"The CIARD RING"},{endpoint:"http%3A%2F%2Fvocab.getty.edu%2Fsparql"},{endpoint:"http%3A%2F%2Flod.gesis.org%2Fthesoz%2Fsparql",title:"TheSoz Thesaurus for the Social Sciences (GESIS)"},{endpoint:"http%3A%2F%2Fdigitale.bncf.firenze.sbn.it%2Fopenrdf-workbench%2Frepositories%2FNS%2Fquery",title:"Thesaurus BNCF"},{endpoint:"http%3A%2F%2Ftour-pedia.org%2Fsparql",title:"Tourpedia"},{endpoint:"http%3A%2F%2Ftkm.kiom.re.kr%2Fontology%2Fsparql",title:"Traditional Korean Medicine Ontology"},{endpoint:"http%3A%2F%2Ftransparency.270a.info%2Fsparql",title:"Transparency International Linked Data"},{endpoint:"http%3A%2F%2Fjisc.rkbexplorer.com%2Fsparql%2F",title:"UK JISC (RKBExplorer)"},{endpoint:"http%3A%2F%2Funlocode.rkbexplorer.com%2Fsparql%2F",title:"UN/LOCODE (RKBExplorer)"},{endpoint:"http%3A%2F%2Fuis.270a.info%2Fsparql",title:"UNESCO Institute for Statistics (UIS) Linked Data"},{endpoint:"http%3A%2F%2Fskos.um.es%2Fsparql%2F",title:"UNESCO Thesaurus"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis1112%2Fquery",title:"UNISTAT-KIS 2011/2012 in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis%2Fquery",title:"UNISTAT-KIS in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Flinkeddata.uriburner.com%2Fsparql",title:"URIBurner"},{endpoint:"http%3A%2F%2Fbeta.sparql.uniprot.org"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Futpl%2Flod%2Fsparql",title:"Universidad Técnica Particular de Loja - Linked Open Data"},{endpoint:"http%3A%2F%2Fresrev.ilrt.bris.ac.uk%2Fdata-server-workshop%2Fsparql",title:"University of Bristol"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fhud%2Fquery",title:"University of Huddersfield -- Circulation and Recommendation Data"},{endpoint:"http%3A%2F%2Fnewcastle.rkbexplorer.com%2Fsparql%2F",title:"University of Newcastle upon Tyne (RKBExplorer)"},{endpoint:"http%3A%2F%2Froma.rkbexplorer.com%2Fsparql%2F",title:'Università degli studi di Roma "La Sapienza" (RKBExplorer)'},{endpoint:"http%3A%2F%2Fpisa.rkbexplorer.com%2Fsparql%2F",title:"Università di Pisa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fulm.rkbexplorer.com%2Fsparql%2F",title:"Universität Ulm (RKBExplorer)"},{endpoint:"http%3A%2F%2Firit.rkbexplorer.com%2Fsparql%2F",title:"Université Paul Sabatier - Toulouse 3 (RKB Explorer)"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fverrijktkoninkrijk%2Fsparql%2F",title:"Verrijkt Koninkrijk"},{endpoint:"http%3A%2F%2Fkaunas.rkbexplorer.com%2Fsparql",title:"Vytautas Magnus University, Kaunas (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwebscience.rkbexplorer.com%2Fsparql",title:"Web Science Conference (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsparql.wikipathways.org%2F",title:"WikiPathways"},{endpoint:"http%3A%2F%2Fwww.opmw.org%2Fsparql",title:"Wings workflow provenance dataset"},{endpoint:"http%3A%2F%2Fwordnet.rkbexplorer.com%2Fsparql%2F",title:"WordNet (RKBExplorer)"},{endpoint:"http%3A%2F%2Fworldbank.270a.info%2Fsparql",title:"World Bank Linked Data"},{endpoint:"http%3A%2F%2Fmlode.nlp2rdf.org%2Fsparql"},{endpoint:"http%3A%2F%2Fldf.fi%2Fww1lod%2Fsparql",title:"World War 1 as Linked Open Data"},{endpoint:"http%3A%2F%2Faksw.org%2Fsparql",title:"aksw.org Research Group dataset"},{endpoint:"http%3A%2F%2Fcrm.rkbexplorer.com%2Fsparql",title:"crm"},{endpoint:"http%3A%2F%2Fdata.open.ac.uk%2Fquery",title:"data.open.ac.uk, Linked Data from the Open University"},{endpoint:"http%3A%2F%2Fsparql.data.southampton.ac.uk%2F"},{endpoint:"http%3A%2F%2Fdatos.bne.es%2Fsparql",title:"datos.bne.es"},{endpoint:"http%3A%2F%2Fkaiko.getalp.org%2Fsparql",title:"dbnary"},{endpoint:"http%3A%2F%2Fdigitaleconomy.rkbexplorer.com%2Fsparql",title:"digitaleconomy"},{endpoint:"http%3A%2F%2Fdotac.rkbexplorer.com%2Fsparql%2F",title:"dotAC (RKBExplorer)"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql%2F",title:"ePrints Harvest (RKBExplorer)"},{endpoint:"http%3A%2F%2Feprints.rkbexplorer.com%2Fsparql%2F",title:"ePrints3 Institutional Archive Collection (RKBExplorer)"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Feducation%2Fsparql",title:"education.data.gov.uk"},{endpoint:"http%3A%2F%2Fepsrc.rkbexplorer.com%2Fsparql",title:"epsrc"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyatlas",title:"flyatlas"},{endpoint:"http%3A%2F%2Fiserve.kmi.open.ac.uk%2Fiserve%2Fsparql",title:"iServe: Linked Services Registry"},{endpoint:"http%3A%2F%2Fichoose.tw.rpi.edu%2Fsparql",title:"ichoose"},{endpoint:"http%3A%2F%2Fkdata.kr%2Fsparql%2Fendpoint.jsp",title:"kdata"},{endpoint:"http%3A%2F%2Flofd.tw.rpi.edu%2Fsparql",title:"lofd"},{endpoint:"http%3A%2F%2Fprovenanceweb.org%2Fsparql",title:"provenanceweb"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Freference%2Fsparql",title:"reference.data.gov.uk"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql",title:"rkb-explorer-foreign"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Fstatistics%2Fsparql",title:"statistics.data.gov.uk"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Ftransport%2Fsparql",title:"transport.data.gov.uk"},{endpoint:"http%3A%2F%2Fopendap.tw.rpi.edu%2Fsparql",title:"twc-opendap"},{endpoint:"http%3A%2F%2Fwebconf.rkbexplorer.com%2Fsparql",title:"webconf"},{endpoint:"http%3A%2F%2Fwiktionary.dbpedia.org%2Fsparql",title:"wiktionary.dbpedia.org"},{endpoint:"http%3A%2F%2Fdiwis.imis.athena-innovation.gr%3A8181%2Fsparql",title:"xxxxx"}];e.forEach(function(t,n){e[n].endpoint=decodeURIComponent(t.endpoint)});e.sort(function(e,t){var n=e.title||e.endpoint,r=t.title||t.endpoint;return n.toUpperCase().localeCompare(r.toUpperCase())});return e}},{jquery:4,selectize:6,"yasgui-utils":10}],95:[function(e){e("./outsideclick.js");e("./tab.js");e("./endpointCombi.js")},{"./endpointCombi.js":94,"./outsideclick.js":96,"./tab.js":97}],96:[function(e){"use strict";var t=e("jquery");t.fn.onOutsideClick=function(e,n){n=t.extend({skipFirst:!1,allowedElements:t()},n);var r=t(this),i=function(o){var s=function(e){return!e.is(o.target)&&0===e.has(o.target).length};if(s(r)&&s(n.allowedElements))if(n.skipFirst)n.skipFirst=!1;else{e();t(document).off("mouseup",i)}};t(document).mouseup(i);return this}},{jquery:4}],97:[function(e){function t(e){return this.each(function(){var t=n(this),i=t.data("bs.tab");i||t.data("bs.tab",i=new r(this));"string"==typeof e&&i[e]()})}var n=e("jquery"),r=function(e){this.element=n(e)};r.VERSION="3.3.1";r.TRANSITION_DURATION=150;r.prototype.show=function(){var e=this.element,t=e.closest("ul:not(.dropdown-menu)"),r=e.data("target");if(!r){r=e.attr("href");r=r&&r.replace(/.*(?=#[^\s]*$)/,"")}if(!e.parent("li").hasClass("active")){var i=t.find(".active:last a"),o=n.Event("hide.bs.tab",{relatedTarget:e[0]}),s=n.Event("show.bs.tab",{relatedTarget:i[0]});i.trigger(o);e.trigger(s);if(!s.isDefaultPrevented()&&!o.isDefaultPrevented()){var a=n(r);this.activate(e.closest("li"),t);this.activate(a,a.parent(),function(){i.trigger({type:"hidden.bs.tab",relatedTarget:e[0]});e.trigger({type:"shown.bs.tab",relatedTarget:i[0]})})}}};r.prototype.activate=function(e,t,i){function o(){s.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1);
e.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0);if(a){e[0].offsetWidth;e.addClass("in")}else e.removeClass("fade");e.parent(".dropdown-menu")&&e.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0);i&&i()}var s=t.find("> .active"),a=i&&n.support.transition&&(s.length&&s.hasClass("fade")||!!t.find("> .fade").length);s.length&&a?s.one("bsTransitionEnd",o).emulateTransitionEnd(r.TRANSITION_DURATION):o();s.removeClass("in")};var i=n.fn.tab;n.fn.tab=t;n.fn.tab.Constructor=r;n.fn.tab.noConflict=function(){n.fn.tab=i;return this};var o=function(e){e.preventDefault();t.call(n(this),"show")};n(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',o).on("click.bs.tab.data-api",'[data-toggle="pill"]',o)},{jquery:4}],98:[function(e,t){"use strict";var n=e("jquery"),r=e("yasgui-utils");e("./jquery/extendJquery.js");var i=t.exports=function(t,o){var s={};s.wrapperElement=n('<div class="yasgui"></div>').appendTo(n(t));s.options=n.extend(!0,{},i.defaults,o);s.history=[];s.persistencyPrefix=null;s.options.persistencyPrefix&&(s.persistencyPrefix="function"==typeof s.options.persistencyPrefix?s.options.persistencyPrefix(s):s.options.persistencyPrefix);s.store=function(){s.persistentOptions&&r.storage.set(s.persistencyPrefix,s.persistentOptions)};var a=function(){var e=r.storage.get(s.persistencyPrefix);e||(e={});return e};s.persistentOptions=a();s.tabManager=e("./tabManager.js")(s);s.tabManager.init();return s};i.YASQE=e("yasgui-yasqe");i.YASQE.defaults=n.extend(!0,i.YASQE.defaults,e("./defaultsYasqe.js"));i.YASR=e("yasgui-yasr");i.$=n;i.defaults=e("./defaults.js")},{"./defaults.js":91,"./defaultsYasqe.js":92,"./jquery/extendJquery.js":95,"./tabManager.js":101,jquery:4,"yasgui-utils":10,"yasgui-yasqe":41,"yasgui-yasr":80}],99:[function(e,t){var n=function(e){var t=[];e||(e=window.location.search.substring(1));if(e.length>0)for(var n=e.split("&"),r=0;r<n.length;r++){var i=n[r].split("="),o=i[0],s=i[1];if(o.length>0&&s&&s.length>0){s=s.replace(/\+/g," ");s=decodeURIComponent(s);t.push({name:i[0],value:s})}}return t};t.exports={getCreateLinkHandler:function(e){return function(){var t=[{name:"outputFormat",value:e.yasr.options.output},{name:"query",value:e.yasqe.getValue()},{name:"contentTypeConstruct",value:e.persistentOptions.yasqe.sparql.acceptHeaderGraph},{name:"contentTypeSelect",value:e.persistentOptions.yasqe.sparql.acceptHeaderSelect},{name:"endpoint",value:e.persistentOptions.yasqe.sparql.endpoint},{name:"requestMethod",value:e.persistentOptions.yasqe.sparql.requestMethod},{name:"tabTitle",value:e.persistentOptions.name}];e.persistentOptions.yasqe.sparql.args.forEach(function(e){t.push(e)});e.persistentOptions.yasqe.sparql.namedGraphs.forEach(function(e){t.push({name:"namedGraph",value:e})});e.persistentOptions.yasqe.sparql.defaultGraphs.forEach(function(e){t.push({name:"defaultGraph",value:e})});var r=[];t.forEach(function(e){r.push(e.name)});var i=n();i.forEach(function(e){-1==r.indexOf(e.name)&&t.push(e)});return t}},getOptionsFromUrl:function(){var e={yasqe:{sparql:{}},yasr:{}},t=n(),r=!1;t.forEach(function(t){if("query"==t.name){r=!0;e.yasqe.value=t.value}else if("outputFormat"==t.name){var n=t.value;"simpleTable"==n&&(n="table");e.yasr.output=n}else if("contentTypeConstruct"==t.name)e.yasqe.sparql.acceptHeaderGraph=t.value;else if("contentTypeSelect"==t.name)e.yasqe.sparql.acceptHeaderSelect=t.value;else if("endpoint"==t.name)e.yasqe.sparql.endpoint=t.value;else if("requestMethod"==t.name)e.yasqe.sparql.requestMethod=t.value;else if("tabTitle"==t.name)e.name=t.value;else if("namedGraph"==t.name){e.yasqe.namedGraphs||(e.yasqe.namedGraphs=[]);e.yasqe.sparql.namedGraphs.push(t)}else if("defaultGraph"==t.name){e.yasqe.defaultGraphs||(e.yasqe.defaultGraphs=[]);e.yasqe.sparql.defaultGraphs.push(t)}else{e.yasqe.args||(e.yasqe.args=[]);e.yasqe.sparql.args.push(t)}});return r?e:null}}},{}],100:[function(e,t){"use strict";var n=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),i=e("./main.js"),o={yasqe:{sparql:{endpoint:i.YASQE.defaults.sparql.endpoint,acceptHeaderGraph:i.YASQE.defaults.sparql.acceptHeaderGraph,acceptHeaderSelect:i.YASQE.defaults.sparql.acceptHeaderSelect,args:i.YASQE.defaults.sparql.args,defaultGraphs:i.YASQE.defaults.sparql.defaultGraphs,namedGraphs:i.YASQE.defaults.sparql.namedGraphs,requestMethod:i.YASQE.defaults.sparql.requestMethod}}};t.exports=function(t,s,a){t.persistentOptions.tabManager.tabs[s]=t.persistentOptions.tabManager.tabs[s]?n.extend(!0,{},o,t.persistentOptions.tabManager.tabs[s]):n.extend(!0,{id:s,name:a},o);var l,u=t.persistentOptions.tabManager.tabs[s],c={persistentOptions:u},p=e("./tabPaneMenu.js")(t,c),d=n("<div>",{id:u.id,style:"position:relative","class":"tab-pane",role:"tabpanel"}).appendTo(t.tabManager.$tabPanesParent),f=n("<div>",{"class":"wrapper"}).appendTo(d),h=n("<div>",{"class":"controlbar"}).appendTo(f),g=(p.initWrapper().appendTo(d),function(){n("<button>",{type:"button","class":"menuButton btn btn-default"}).on("click",function(){if(d.hasClass("menu-open")){d.removeClass("menu-open");p.store()}else{p.updateWrapper();d.addClass("menu-open");n(".menu-slide,.menuButton").onOutsideClick(function(){d.removeClass("menu-open");p.store()})}}).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).appendTo(h);l=n("<select>").appendTo(h).endpointCombi(t,{value:u.yasqe.sparql.endpoint,onChange:function(e){u.yasqe.sparql.endpoint=e;c.refreshYasqe();t.store()}})}),m=n("<div>",{id:"yasqe_"+u.id}).appendTo(f),v=n("<div>",{id:"yasq_"+u.id}).appendTo(f),E={createShareLink:e("./shareLink").getCreateLinkHandler(c)};c.setPersistentInYasqe=function(){if(c.yasqe){n.extend(!0,c.yasqe.options,u.yasqe);c.yasqe.setValue(u.yasqe.value)}};n.extend(E,u.yasqe);c.onShow=function(){if(!c.yasqe||!c.yasr){c.yasqe=i.YASQE(m[0],E);c.yasqe.on("blur",function(e){u.yasqe.value=e.getValue();t.store()});c.yasr=i.YASR(v[0],n.extend({getUsedPrefixes:c.yasqe.getPrefixesFromQuery},u.yasr));c.yasqe.options.sparql.callbacks.complete=function(){c.yasr.setResponse.apply(this,arguments);u.yasqe.value=c.yasqe.getValue();var e=null;c.yasr.results.getBindings()&&(e=c.yasr.results.getBindings().length);var r={options:n.extend(!0,{},u),resultSize:e};delete r.options.name;t.history.unshift(r)};c.yasqe.query=function(){if(t.options.api.corsProxy&&t.corsEnabled)if(t.corsEnabled[u.yasqe.sparql.endpoint])i.YASQE.executeQuery(c.yasqe);else{var e=n.extend(!0,{},c.yasqe.options.sparql);e.args.push({name:"endpoint",value:e.endpoint});e.args.push({name:"requestMethod",value:e.requestMethod});e.requestMethod="POST";e.endpoint=t.options.api.corsProxy;i.YASQE.executeQuery(c.yasqe,e)}else i.YASQE.executeQuery(c.yasqe)};g()}};c.refreshYasqe=function(){n.extend(!0,c.yasqe.options,c.persistentOptions.yasqe);c.persistentOptions.yasqe.value&&c.yasqe.setValue(c.persistentOptions.yasqe.value)};c.destroy=function(){c.yasr&&r.storage.remove(c.yasr.getPersistencyId(c.yasr.options.persistency.results.key))};return c}},{"./main.js":98,"./shareLink":99,"./tabPaneMenu.js":102,"./utils.js":103,jquery:4,"yasgui-utils":10}],101:[function(e,t){"use strict";{var n=e("jquery");e("yasgui-utils"),e("./imgs.js")}e("jquery-ui/position");t.exports=function(t){t.persistentOptions.tabManager||(t.persistentOptions.tabManager={});var r=t.persistentOptions.tabManager,i={};i.tabs={};var o,s=null,a=null,l=function(e,t){e||(e="Query");t||(t=0);var n=e+(t>0?" "+t:"");u(n)&&(n=l(e,t+1));return n},u=function(e){for(var t in i.tabs)if(i.tabs[t].persistentOptions.name==e)return!0;return!1},c=function(){return Math.random().toString(36).substring(7)};i.init=function(){s=n("<div>",{role:"tabpanel"}).appendTo(t.wrapperElement);o=n("<ul>",{"class":"nav nav-tabs mainTabs",role:"tablist"}).appendTo(s);var l=n("<a>",{role:"addTab"}).click(function(){f()}).text("+");o.append(n("<li>",{role:"presentation"}).append(l));i.$tabPanesParent=n("<div>",{"class":"tab-content"}).appendTo(s);if(!r||n.isEmptyObject(r)){r.tabOrder=[];r.tabs={};r.selected=null}var u=e("./shareLink.js").getOptionsFromUrl();if(u){var p=c();u.id=p;r.tabs[p]=u;r.tabOrder.push(p);r.selected=p}r.tabOrder.length>0?r.tabOrder.forEach(f):f();o.sortable({placeholder:"tab-sortable-highlight",items:'li:has([data-toggle="tab"])',forcePlaceholderSize:!0,update:function(){var e=[];o.find('a[data-toggle="tab"]').each(function(){e.push(n(this).attr("aria-controls"))});r.tabOrder=e;t.store()}});a=n("<div>",{"class":"tabDropDown"}).appendTo(t.wrapperElement);var h=n("<ul>",{"class":"dropdown-menu",role:"menu"}).appendTo(a),g=function(e,t){var r=n("<li>",{role:"presentation"}).appendTo(h);e?r.append(n("<a>",{role:"menuitem",href:"#"}).text(e)).click(function(){a.hide();event.preventDefault();t&&t(a.attr("target-tab"))}):r.addClass("divider")};g("Rename",function(e){o.find('a[href="#'+e+'"]').dblclick()});g("Copy",function(){console.log("todo")});g();g("Close",d);g("Close others",function(e){o.find('a[role="tab"]').each(function(){var t=n(this).attr("aria-controls");t!=e&&d(t)})});g("Close all",function(){o.find('a[role="tab"]').each(function(){d(n(this).attr("aria-controls"))})})};var p=function(e){o.find('a[aria-controls="'+e+'"]').tab("show")},d=function(e){i.tabs[e].destroy();delete i.tabs[e];delete r.tabs[e];var s=r.tabOrder.indexOf(e);s>-1&&r.tabOrder.splice(s,1);var a=null;r.tabOrder[s]?a=s:r.tabOrder[s-1]&&(a=s-1);null!==a&&p(r.tabOrder[a]);o.find('a[href="#'+e+'"]').closest("li").remove();n("#"+e).remove();t.store()},f=function(s){var u=!s;s||(s=c());"tabs"in r||(r.tabs={});var p=r.tabs[s]?r.tabs[s].name:l(),f=n("<a>",{href:"#"+s,"aria-controls":s,role:"tab","data-toggle":"tab"}).click(function(e){e.preventDefault();n(this).tab("show");i.tabs[s].yasqe.refresh()}).on("shown.bs.tab",function(){r.selected=n(this).attr("aria-controls");i.tabs[s].onShow();t.store()}).append(n("<span>").text(p)).append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){d(s)})),h=n('<div><input type="text"></div>').keydown(function(){27==event.which||27==event.keyCode?n(this).closest("li").removeClass("rename"):(13==event.which||13==event.keyCode)&&g(n(this).closest("li"))}),g=function(e){var n=e.find('a[role="tab"]').attr("aria-controls"),i=e.find("input").val();f.find("span").text(e.find("input").val());r.tabs[n].name=i;t.store();e.removeClass("rename")},m=n("<li>",{role:"presentation"}).append(f).append(h).dblclick(function(){var e=n(this),t=e.find("span").text();e.addClass("rename");e.find("input").val(t);e.onOutsideClick(function(){g(e)})}).bind("contextmenu",function(e){e.preventDefault();a.show().onOutsideClick(function(){a.hide()},{allowedElements:n(this).closest("li")}).addClass("open").position({my:"left top-3",at:"left bottom",of:n(this),collision:"fit"}).attr("target-tab",m.find('a[role="tab"]').attr("aria-controls"))});o.find('li:has(a[role="addTab"])').before(m);u&&r.tabOrder.push(s);i.tabs[s]=e("./tab.js")(t,s,p);(u||r.selected==s)&&f.tab("show")};i.current=function(){return i.tabs[r.selected]};return i}},{"./imgs.js":93,"./shareLink.js":99,"./tab.js":100,jquery:4,"jquery-ui/position":3,"yasgui-utils":10}],102:[function(e,t){"use strict";var n=e("jquery"),r=e("./imgs.js"),i=e("yasgui-utils");t.exports=function(e,t){var o,s,a,l,u,c,p,d=null,f=null,h=null,g=null,m=null,v=function(){d=n("<nav>",{"class":"menu-slide",id:"navmenu"});d.append(n(i.svg.getElement(r.yasgui)).addClass("yasguiLogo").attr("title","About YASGUI").click(function(){window.open("http://about.yasgui.org","_blank")}));f=n("<div>",{role:"tabpanel"}).appendTo(d);h=n("<ul>",{"class":"nav nav-pills tabPaneMenuTabs",role:"tablist"}).appendTo(f);g=n("<div>",{"class":"tab-content"}).appendTo(f);var e=n("<li>",{role:"presentation"}).appendTo(h),v="yasgui_reqConfig_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+v,"aria-controls":v,role:"tab","data-toggle":"tab"}).text("Configure Request").click(function(e){e.preventDefault();n(this).tab("show")}));var E=n("<div>",{id:v,role:"tabpanel","class":"tab-pane requestConfig container-fluid"}).appendTo(g),y=n("<div>",{"class":"row"}).appendTo(E);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(y).append(n("<span>").text("Request Method"));o=n("<button>",{"class":"btn btn-default ","data-toggle":"button"}).text("POST").click(function(){o.addClass("active");s.removeClass("active")});s=n("<button>",{"class":"btn btn-default","data-toggle":"button"}).text("GET").click(function(){s.addClass("active");o.removeClass("active")});n("<div>",{"class":"btn-group col-md-8",role:"group"}).append(s).append(o).appendTo(y);var x=n("<div>",{"class":"row"}).appendTo(E);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(x).text("Accept Headers");a=n("<select>",{"class":"form-control"}).append(n("<option>",{value:"application/sparql-results+json"}).text("JSON")).append(n("<option>",{value:"application/sparql-results+xml"}).text("XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));l=n("<select>",{"class":"form-control"}).append(n("<option>",{value:"text/turtle"}).text("Turtle")).append(n("<option>",{value:"application/rdf+xml"}).text("RDF-XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("SELECT").append(a)).appendTo(x);n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("Graph").append(l)).appendTo(x);var b=n("<div>",{"class":"row"}).appendTo(E);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(b).text("URL Arguments");u=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(b);var T=n("<div>",{"class":"row"}).appendTo(E);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(T).text("Default graphs");c=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(T);var S=n("<div>",{"class":"row"}).appendTo(E);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(S).text("Named graphs");p=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(S);var e=n("<li>",{role:"presentation"}).appendTo(h),N="yasgui_history_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+N,"aria-controls":N,role:"tab","data-toggle":"tab"}).text("History").click(function(e){e.preventDefault();n(this).tab("show")}));var C=n("<div>",{id:N,role:"tabpanel","class":"tab-pane history container-fluid"}).appendTo(g);m=n("<ul>",{"class":"list-group"}).appendTo(C);var e=n("<li>",{role:"presentation"}).appendTo(h),L="yasgui_collections_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+L,"aria-controls":L,role:"tab","data-toggle":"tab"}).text("Collections").click(function(e){e.preventDefault();n(this).tab("show")}));var E=n("<div>",{id:L,role:"tabpanel","class":"tab-pane collections container-fluid"}).appendTo(g);return d},E=function(e,t,r,i){for(var o=n("<div>",{"class":"textInputsRow"}),s=0;t>s;s++){var a=i&&i[s]?i[s]:"";n("<input>",{type:"text"}).val(a).keyup(function(){var r=!1;e.find(".textInputsRow:last input").each(function(e,t){n(t).val().trim().length>0&&(r=!0)});r&&E(e,t,!0)}).css("width",92/t+"%").appendTo(o)}o.append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){n(this).closest(".textInputsRow").remove()}));r?o.hide().appendTo(e).show("fast"):o.appendTo(e)},y=function(){0==d.find(".tabPaneMenuTabs li.active").length&&d.find(".tabPaneMenuTabs a:first").tab("show");var r=t.persistentOptions.yasqe;"POST"==r.sparql.requestMethod.toUpperCase()?o.addClass("active"):s.addClass("active");l.val(r.sparql.acceptHeaderGraph);a.val(r.sparql.acceptHeaderSelect);u.empty();r.sparql.args&&r.sparql.args.length>0&&r.sparql.args.forEach(function(e){var t=[e.name,e.value];E(u,2,!1,t)});E(u,2,!1);c.empty();r.sparql.defaultGraphs&&r.sparql.defaultGraphs.length>0&&E(c,1,!1,r.sparql.defaultGraphs);E(c,1,!1);p.empty();r.sparql.namedGraphs&&r.sparql.namedGraphs.length>0&&E(p,1,!1,r.sparql.namedGraphs);E(p,1,!1);m.empty();0==e.history.length?m.append(n("<a>",{"class":"list-group-item disabled",href:"#"}).text("No items in history yet").click(function(e){e.preventDefault()})):e.history.forEach(function(t){var r=t.options.yasqe.sparql.endpoint;t.resultSize&&(r+=" ("+t.resultSize+" results)");m.append(n("<a>",{"class":"list-group-item",href:"#",title:t.options.yasqe.value}).text(r).click(function(r){var i=e.tabManager.tabs[t.options.id];n.extend(!0,i.persistentOptions,t.options);i.refreshYasqe();e.store();d.closest(".tab-pane").removeClass("menu-open");r.preventDefault()}))})},x=function(){var r=t.persistentOptions.yasqe.sparql;o.hasClass("active")?r.requestMethod="POST":s.hasClass("active")&&(r.requestMethod="GET");r.acceptHeaderGraph=l.val();r.acceptHeaderSelect=a.val();var i=[];u.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&i.push({name:r[0],value:r[1]?r[1]:""})});r.args=i;var d=[];c.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&d.push(r[0])});r.defaultGraphs=d;var f=[];p.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&f.push(r[0])});r.namedGraphs=f;e.store();t.setPersistentInYasqe()};return{initWrapper:v,updateWrapper:y,store:x}}},{"./imgs.js":93,jquery:4,"yasgui-utils":10}],103:[function(e,t){e("jquery");t.exports={escapeHtmlEntities:function(e){var t={"&":"&","<":"<",">":">"},n=function(e){return t[e]||e};return e.replace(/[&<>]/g,n)}}},{jquery:4}]},{},[1])(1)});
//# sourceMappingURL=yasgui.bundled.min.js.map |
ajax/libs/angular-google-maps/2.0.15/angular-google-maps.js | tholu/cdnjs | /*! angular-google-maps 2.0.15 2015-03-10
* AngularJS directives for Google Maps
* git: https://github.com/angular-ui/angular-google-maps.git
*/
;
(function( window, angular, undefined ){
'use strict';
/*
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
angular-google-maps
https://github.com/angular-ui/angular-google-maps
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps.providers', []);
angular.module('uiGmapgoogle-maps.wrapped', []);
angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']);
angular.module('uiGmapgoogle-maps.directives.api.managers', []);
angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']);
angular.module('uiGmapgoogle-maps.directives.api.options.builders', []);
angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']);
angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']);
angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [
'$q', 'uiGmapuuid', function($q, uuid) {
var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId;
scriptId = void 0;
getScriptUrl = function(options) {
if (options.china) {
return 'http://maps.google.cn/maps/api/js?';
} else {
return 'https://maps.googleapis.com/maps/api/js?';
}
};
includeScript = function(options) {
var query, script;
query = _.map(options, function(v, k) {
return k + '=' + v;
});
if (scriptId) {
document.getElementById(scriptId).remove();
}
query = query.join('&');
script = document.createElement('script');
script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate());
script.type = 'text/javascript';
script.src = getScriptUrl(options) + query;
return document.body.appendChild(script);
};
isGoogleMapsLoaded = function() {
return angular.isDefined(window.google) && angular.isDefined(window.google.maps);
};
return {
load: function(options) {
var deferred, randomizedFunctionName;
deferred = $q.defer();
if (isGoogleMapsLoaded()) {
deferred.resolve(window.google.maps);
return deferred.promise;
}
randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000);
window[randomizedFunctionName] = function() {
window[randomizedFunctionName] = null;
deferred.resolve(window.google.maps);
};
if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) {
document.addEventListener('online', function() {
if (!isGoogleMapsLoaded()) {
return includeScript(options);
}
});
} else {
includeScript(options);
}
return deferred.promise;
}
};
}
]).provider('uiGmapGoogleMapApi', function() {
this.options = {
china: false,
v: '3.17',
libraries: '',
language: 'en',
sensor: 'false'
};
this.configure = function(options) {
angular.extend(this.options, options);
};
this.$get = [
'uiGmapMapScriptLoader', (function(_this) {
return function(loader) {
return loader.load(_this.options);
};
})(this)
];
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() {
return {
init: _.once(function() {
if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) {
return;
}
google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open;
google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close;
google.maps.InfoWindow.prototype._isOpen = false;
google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) {
if (recurse != null) {
return;
}
this._isOpen = true;
this._open(map, anchor, true);
};
google.maps.InfoWindow.prototype.close = function(recurse) {
if (recurse != null) {
return;
}
this._isOpen = false;
this._close(true);
};
google.maps.InfoWindow.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
/*
Do the same for InfoBox
TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier
*/
if (window.InfoBox) {
window.InfoBox.prototype._open = window.InfoBox.prototype.open;
window.InfoBox.prototype._close = window.InfoBox.prototype.close;
window.InfoBox.prototype._isOpen = false;
window.InfoBox.prototype.open = function(map, anchor) {
this._isOpen = true;
this._open(map, anchor);
};
window.InfoBox.prototype.close = function() {
this._isOpen = false;
this._close();
};
window.InfoBox.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
}
if (window.MarkerLabel_) {
return window.MarkerLabel_.prototype.setContent = function() {
var content;
content = this.marker_.get('labelContent');
if (!content || _.isEqual(this.oldContent, content)) {
return;
}
if (typeof (content != null ? content.nodeType : void 0) === 'undefined') {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
this.oldContent = content;
} else {
this.labelDiv_.innerHTML = '';
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.labelDiv_.innerHTML = '';
this.eventDiv_.appendChild(content);
this.oldContent = content;
}
};
}
})
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() {
/*
Author Nick McCready
Intersection of Objects if the arrays have something in common each intersecting object will be returned
in an new array.
*/
this.intersectionObjects = function(array1, array2, comparison) {
var res;
if (comparison == null) {
comparison = void 0;
}
res = _.map(array1, (function(_this) {
return function(obj1) {
return _.find(array2, function(obj2) {
if (comparison != null) {
return comparison(obj1, obj2);
} else {
return _.isEqual(obj1, obj2);
}
});
};
})(this));
return _.filter(res, function(o) {
return o != null;
});
};
this.containsObject = _.includeObject = function(obj, target, comparison) {
if (comparison == null) {
comparison = void 0;
}
if (obj === null) {
return false;
}
return _.any(obj, (function(_this) {
return function(value) {
if (comparison != null) {
return comparison(value, target);
} else {
return _.isEqual(value, target);
}
};
})(this));
};
this.differenceObjects = function(array1, array2, comparison) {
if (comparison == null) {
comparison = void 0;
}
return _.filter(array1, (function(_this) {
return function(value) {
return !_this.containsObject(array2, value, comparison);
};
})(this));
};
this.withoutObjects = this.differenceObjects;
this.indexOfObject = function(array, item, comparison, isSorted) {
var i, length;
if (array == null) {
return -1;
}
i = 0;
length = array.length;
if (isSorted) {
if (typeof isSorted === "number") {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return (array[i] === item ? i : -1);
}
}
while (i < length) {
if (comparison != null) {
if (comparison(array[i], item)) {
return i;
}
} else {
if (_.isEqual(array[i], item)) {
return i;
}
}
i++;
}
return -1;
};
this["extends"] = function(arrayOfObjectsToCombine) {
return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) {
return _.extend(combined, toAdd);
}, {});
};
this.isNullOrUndefined = function(thing) {
return _.isNull(thing || _.isUndefined(thing));
};
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() {
return function(str) {
this.contains = function(value, fromIndex) {
return str.indexOf(value, fromIndex) !== -1;
};
return this;
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [
function() {
return {
fakePromise: function() {
var _cb;
_cb = void 0;
return {
then: function(cb) {
return _cb = cb;
},
resolve: function() {
return _cb.apply(void 0, arguments);
}
};
}
};
}
]).service('uiGmap_async', [
'$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) {
var ExposedPromise, PromiseQueueManager, SniffedPromise, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch, _getArrayAndKeys, _getIterateeValue;
promiseTypes = uiGmapPromise.promiseTypes;
isInProgress = uiGmapPromise.isInProgress;
promiseStatus = uiGmapPromise.promiseStatus;
ExposedPromise = uiGmapPromise.ExposedPromise;
SniffedPromise = uiGmapPromise.SniffedPromise;
kickPromise = function(sniffedPromise, cancelCb) {
var promise;
promise = sniffedPromise.promise();
promise.promiseType = sniffedPromise.promiseType;
if (promise.$$state) {
$log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status)));
}
promise.cancelCb = cancelCb;
return promise;
};
doSkippPromise = function(sniffedPromise, lastPromise) {
if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) {
$log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY");
return true;
}
return false;
};
maybeCancelPromises = function(queue, sniffedPromise, lastPromise) {
var first;
if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) {
if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) {
$log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType);
lastPromise.cancelCb('cancel safe');
first = queue.peek();
if ((first != null) && isInProgress(first)) {
if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) {
$log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType);
return first.cancelCb('cancel safe');
} else {
return $log.warn('first promise was not cancelable');
}
}
}
}
};
/*
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
*/
PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) {
var lastPromise, newPromise;
if (!existingPiecesObj.existingPieces) {
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue();
return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb));
} else {
lastPromise = _.last(existingPiecesObj.existingPieces._content);
if (doSkippPromise(sniffedPromise, lastPromise)) {
return;
}
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise);
newPromise = ExposedPromise(lastPromise["finally"](function() {
return kickPromise(sniffedPromise, cancelCb);
}));
newPromise.cancelCb = cancelCb;
newPromise.promiseType = sniffedPromise.promiseType;
existingPiecesObj.existingPieces.enqueue(newPromise);
return lastPromise["finally"](function() {
return existingPiecesObj.existingPieces.dequeue();
});
}
};
managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) {
var cancelLogger;
if (msg == null) {
msg = '';
}
cancelLogger = function(msg) {
$log.debug("" + msg + ": " + msg);
return cancelCb(msg);
};
return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger);
};
defaultChunkSize = 80;
errorObject = {
value: null
};
tryCatch = function(fn, ctx, args) {
var e;
try {
return fn.apply(ctx, args);
} catch (_error) {
e = _error;
errorObject.value = e;
return errorObject;
}
};
logTryCatch = function(fn, ctx, deferred, args) {
var msg, result;
result = tryCatch(fn, ctx, args);
if (result === errorObject) {
msg = "error within chunking iterator: " + errorObject.value;
$log.error(msg);
deferred.reject(msg);
}
if (result === 'cancel safe') {
return false;
}
return true;
};
_getIterateeValue = function(collection, array, index) {
var valOrKey, _isArray;
_isArray = collection === array;
valOrKey = array[index];
if (_isArray) {
return valOrKey;
}
return collection[valOrKey];
};
_getArrayAndKeys = function(collection, keys, bailOutCb, cb) {
var array;
if (angular.isArray(collection)) {
array = collection;
} else {
array = keys ? keys : Object.keys(_.omit(collection, ['length', 'forEach', 'map']));
keys = array;
}
if (cb == null) {
cb = bailOutCb;
}
if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) {
if (cb !== bailOutCb) {
return bailOutCb();
}
}
return cb(array, keys);
};
/*
Author: Nicholas McCready & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
*/
doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) {
return _getArrayAndKeys(collection, _keys, function(array, keys) {
var cnt, i, keepGoing, val;
if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) {
cnt = chunkSizeOrDontChunk;
} else {
cnt = array.length;
}
i = index;
keepGoing = true;
while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) {
val = _getIterateeValue(collection, array, i);
keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]);
++i;
}
if (array) {
if (keepGoing && i < array.length) {
index = i;
if (chunkSizeOrDontChunk) {
if ((pauseCb != null) && _.isFunction(pauseCb)) {
logTryCatch(pauseCb, void 0, overallD, []);
}
return $timeout(function() {
return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys);
}, pauseMilli, false);
}
} else {
return overallD.resolve();
}
}
});
};
each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var error, overallD, ret;
if (chunkSizeOrDontChunk == null) {
chunkSizeOrDontChunk = defaultChunkSize;
}
if (index == null) {
index = 0;
}
if (pauseMilli == null) {
pauseMilli = 1;
}
ret = void 0;
overallD = uiGmapPromise.defer();
ret = overallD.promise;
if (!pauseMilli) {
error = 'pause (delay) must be set from _async!';
$log.error(error);
overallD.reject(error);
return ret;
}
return _getArrayAndKeys(collection, _keys, function() {
overallD.resolve();
return ret;
}, function(array, keys) {
doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys);
return ret;
});
};
map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var results;
results = [];
return _getArrayAndKeys(collection, _keys, function() {
return uiGmapPromise.resolve(results);
}, function(array, keys) {
return each(collection, function(o) {
return results.push(iterator(o));
}, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() {
return results;
});
});
};
return {
each: each,
map: map,
managePromiseQueue: managePromiseQueue,
promiseLock: managePromiseQueue,
defaultChunkSize: defaultChunkSize,
chunkSizeFrom: function(fromSize, ret) {
if (ret == null) {
ret = void 0;
}
if (_.isNumber(fromSize)) {
ret = fromSize;
}
if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) {
ret = false;
}
return ret;
}
};
}
]);
}).call(this);
;(function() {
var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() {
var BaseObject, baseObjectKeywords;
baseObjectKeywords = ['extended', 'included'];
BaseObject = (function() {
function BaseObject() {}
BaseObject.extend = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(baseObjectKeywords, key) < 0) {
this[key] = value;
}
}
if ((_ref = obj.extended) != null) {
_ref.apply(this);
}
return this;
};
BaseObject.include = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(baseObjectKeywords, key) < 0) {
this.prototype[key] = value;
}
}
if ((_ref = obj.included) != null) {
_ref.apply(this);
}
return this;
};
return BaseObject;
})();
return BaseObject;
});
}).call(this);
;
/*
Useful function callbacks that should be defined at later time.
Mainly to be used for specs to verify creation / linking.
This is to lead a common design in notifying child stuff.
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() {
return {
onChildCreation: function(child) {}
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [
'$q', function($q) {
var CtrlHandle;
return CtrlHandle = {
handle: function($scope, $element) {
$scope.$on('$destroy', function() {
return CtrlHandle.handle($scope);
});
$scope.deferred = $q.defer();
return {
getScope: function() {
return $scope;
}
};
},
mapPromise: function(scope, ctrl) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.deferred.promise.then(function(map) {
return scope.map = map;
});
return mapScope.deferred.promise;
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [
"uiGmapLogger", function($log) {
return {
setEvents: function(gObject, scope, model, ignores) {
if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) {
return _.compact(_.map(scope.events, function(eventHandler, eventName) {
var doIgnore;
if (ignores) {
doIgnore = _(ignores).contains(eventName);
}
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName]) && !doIgnore) {
return google.maps.event.addListener(gObject, eventName, function() {
if (!scope.$evalAsync) {
scope.$evalAsync = function() {};
}
return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments]));
});
}
}));
}
},
removeEvents: function(listeners) {
if (!listeners) {
return;
}
return listeners.forEach(function(l) {
if (l) {
return google.maps.event.removeListener(l);
}
});
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [
'uiGmapLogger', 'uiGmap_async', function($log, _async) {
return {
fit: function(gMarkers, gMap) {
var bounds, everSet;
if (gMap && gMarkers && gMarkers.length > 0) {
bounds = new google.maps.LatLngBounds();
everSet = false;
gMarkers.forEach((function(_this) {
return function(gMarker) {
if (gMarker) {
if (!everSet) {
everSet = true;
}
return bounds.extend(gMarker.getPosition());
}
};
})(this));
if (everSet) {
return gMap.fitBounds(bounds);
}
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [
'uiGmapLogger', '$compile', function(Logger, $compile) {
var getCoords, getLatitude, getLongitude, validateCoords, _isFalse, _isTruthy;
_isTruthy = function(value, bool, optionsArray) {
return value === bool || optionsArray.indexOf(value) !== -1;
};
_isFalse = function(value) {
return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']);
};
getLatitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[1];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[1];
} else {
return value.latitude;
}
};
getLongitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[0];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[0];
} else {
return value.longitude;
}
};
getCoords = function(value) {
if (!value) {
return;
}
if (Array.isArray(value) && value.length === 2) {
return new google.maps.LatLng(value[1], value[0]);
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]);
} else {
return new google.maps.LatLng(value.latitude, value.longitude);
}
};
validateCoords = function(coords) {
if (angular.isUndefined(coords)) {
return false;
}
if (_.isArray(coords)) {
if (coords.length === 2) {
return true;
}
} else if ((coords != null) && (coords != null ? coords.type : void 0)) {
if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) {
return true;
}
}
if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) {
return true;
}
return false;
};
return {
setCoordsFromEvent: function(prevValue, newLatLon) {
if (!prevValue) {
return;
}
if (Array.isArray(prevValue) && prevValue.length === 2) {
prevValue[1] = newLatLon.lat();
prevValue[0] = newLatLon.lng();
} else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') {
prevValue.coordinates[1] = newLatLon.lat();
prevValue.coordinates[0] = newLatLon.lng();
} else {
prevValue.latitude = newLatLon.lat();
prevValue.longitude = newLatLon.lng();
}
return prevValue;
},
getLabelPositionPoint: function(anchor) {
var xPos, yPos;
if (anchor === void 0) {
return void 0;
}
anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor);
xPos = parseFloat(anchor[1]);
yPos = parseFloat(anchor[2]);
if ((xPos != null) && (yPos != null)) {
return new google.maps.Point(xPos, yPos);
}
},
createWindowOptions: function(gMarker, scope, content, defaults) {
var options;
if ((content != null) && (defaults != null) && ($compile != null)) {
options = angular.extend({}, defaults, {
content: this.buildContent(scope, defaults, content),
position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords)
});
if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) {
if (options.boxClass == null) {
} else {
options.pixelOffset = {
height: 0,
width: -2
};
}
}
return options;
} else {
if (!defaults) {
Logger.error('infoWindow defaults not defined');
if (!content) {
return Logger.error('infoWindow content not defined');
}
} else {
return defaults;
}
}
},
buildContent: function(scope, defaults, content) {
var parsed, ret;
if (defaults.content != null) {
ret = defaults.content;
} else {
if ($compile != null) {
content = content.replace(/^\s+|\s+$/g, '');
parsed = content === '' ? '' : $compile(content)(scope);
if (parsed.length > 0) {
ret = parsed[0];
}
} else {
ret = content;
}
}
return ret;
},
defaultDelay: 50,
isTrue: function(value) {
return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']);
},
isFalse: _isFalse,
isFalsy: function(value) {
return _isTruthy(value, false, [void 0, null]) || _isFalse(value);
},
getCoords: getCoords,
validateCoords: validateCoords,
equalCoords: function(coord1, coord2) {
return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2);
},
validatePath: function(path) {
var array, i, polygon, trackMaxVertices;
i = 0;
if (angular.isUndefined(path.type)) {
if (!Array.isArray(path) || path.length < 2) {
return false;
}
while (i < path.length) {
if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) {
return false;
}
i++;
}
return true;
} else {
if (angular.isUndefined(path.coordinates)) {
return false;
}
if (path.type === 'Polygon') {
if (path.coordinates[0].length < 4) {
return false;
}
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
polygon = path.coordinates[trackMaxVertices.index];
array = polygon[0];
if (array.length < 4) {
return false;
}
} else if (path.type === 'LineString') {
if (path.coordinates.length < 2) {
return false;
}
array = path.coordinates;
} else {
return false;
}
while (i < array.length) {
if (array[i].length !== 2) {
return false;
}
i++;
}
return true;
}
},
convertPathPoints: function(path) {
var array, i, latlng, result, trackMaxVertices;
i = 0;
result = new google.maps.MVCArray();
if (angular.isUndefined(path.type)) {
while (i < path.length) {
latlng;
if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) {
latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude);
} else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') {
latlng = path[i];
}
result.push(latlng);
i++;
}
} else {
array;
if (path.type === 'Polygon') {
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
array = path.coordinates[trackMaxVertices.index][0];
} else if (path.type === 'LineString') {
array = path.coordinates;
}
while (i < array.length) {
result.push(new google.maps.LatLng(array[i][1], array[i][0]));
i++;
}
}
return result;
},
extendMapBounds: function(map, points) {
var bounds, i;
bounds = new google.maps.LatLngBounds();
i = 0;
while (i < points.length) {
bounds.extend(points.getAt(i));
i++;
}
return map.fitBounds(bounds);
},
getPath: function(object, key) {
var obj;
if ((key == null) || !_.isString(key)) {
return key;
}
obj = object;
_.each(key.split('.'), function(value) {
if (obj) {
return obj = obj[value];
}
});
return obj;
},
validateBoundPoints: function(bounds) {
if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) {
return false;
}
return true;
},
convertBoundPoints: function(bounds) {
var result;
result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude));
return result;
},
fitMapBounds: function(map, bounds) {
return map.fitBounds(bounds);
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [
'$q', '$timeout', function($q, $timeout) {
var ctr, promises, proms;
ctr = 0;
proms = [];
promises = function() {
return $q.all(proms);
};
return {
spawn: function() {
var d;
d = $q.defer();
proms.push(d.promise);
ctr += 1;
return {
instance: ctr,
deferred: d
};
},
promises: promises,
instances: function() {
return ctr;
},
promise: function(expect) {
var d, ohCrap;
if (expect == null) {
expect = 1;
}
d = $q.defer();
ohCrap = function() {
return $timeout(function() {
if (ctr !== expect) {
return ohCrap();
} else {
return d.resolve(promises());
}
});
};
ohCrap();
return d.promise;
},
reset: function() {
ctr = 0;
return proms.length = 0;
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [
"uiGmapBaseObject", function(BaseObject) {
var Linked;
Linked = (function(_super) {
__extends(Linked, _super);
function Linked(scope, element, attrs, ctrls) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.ctrls = ctrls;
}
return Linked;
})(BaseObject);
return Linked;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [
'$log', function($log) {
var LEVELS, Logger, log, maybeExecLevel;
LEVELS = {
log: 1,
info: 2,
debug: 3,
warn: 4,
error: 5,
none: 6
};
maybeExecLevel = function(level, current, fn) {
if (level >= current) {
return fn();
}
};
log = function(logLevelFnName, msg) {
if ($log != null) {
return $log[logLevelFnName](msg);
} else {
return console[logLevelFnName](msg);
}
};
Logger = (function() {
function Logger() {
var logFns;
this.doLog = true;
logFns = {};
['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) {
return function(level) {
return logFns[level] = function(msg) {
if (_this.doLog) {
return maybeExecLevel(LEVELS[level], _this.currentLevel, function() {
return log(level, msg);
});
}
};
};
})(this));
this.LEVELS = LEVELS;
this.currentLevel = LEVELS.error;
this.log = logFns['log'];
this.info = logFns['info'];
this.debug = logFns['debug'];
this.warn = logFns['warn'];
this.error = logFns['error'];
}
Logger.prototype.spawn = function() {
return new Logger();
};
Logger.prototype.setLog = function(someLogger) {
return $log = someLogger;
};
return Logger;
})();
return new Logger();
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) {
var ModelKey;
return ModelKey = (function(_super) {
__extends(ModelKey, _super);
function ModelKey(scope) {
this.scope = scope;
this.modelsLength = __bind(this.modelsLength, this);
this.updateChild = __bind(this.updateChild, this);
this.destroy = __bind(this.destroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.setChildScope = __bind(this.setChildScope, this);
this.getChanges = __bind(this.getChanges, this);
this.getProp = __bind(this.getProp, this);
this.setIdKey = __bind(this.setIdKey, this);
this.modelKeyComparison = __bind(this.modelKeyComparison, this);
ModelKey.__super__.constructor.call(this);
this["interface"] = {};
this["interface"].scopeKeys = [];
this.defaultIdKey = 'id';
this.idKey = void 0;
}
ModelKey.prototype.evalModelHandle = function(model, modelKey) {
if ((model == null) || (modelKey == null)) {
return;
}
if (modelKey === 'self') {
return model;
} else {
if (_.isFunction(modelKey)) {
modelKey = modelKey();
}
return GmapUtil.getPath(model, modelKey);
}
};
ModelKey.prototype.modelKeyComparison = function(model1, model2) {
var hasCoords, isEqual, scope;
hasCoords = _.contains(this["interface"].scopeKeys, 'coords');
if (hasCoords && (this.scope.coords != null) || !hasCoords) {
scope = this.scope;
}
if (scope == null) {
throw 'No scope set!';
}
if (hasCoords) {
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
ModelKey.prototype.setIdKey = function(scope) {
return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey;
};
ModelKey.prototype.setVal = function(model, key, newValue) {
var thingToSet;
thingToSet = this.modelOrKey(model, key);
thingToSet = newValue;
return model;
};
ModelKey.prototype.modelOrKey = function(model, key) {
if (key == null) {
return;
}
if (key !== 'self') {
return model[key];
}
return model;
};
ModelKey.prototype.getProp = function(propName, model) {
return this.modelOrKey(model, propName);
};
/*
For the cases were watching a large object we only want to know the list of props
that actually changed.
Also we want to limit the amount of props we analyze to whitelisted props that are
actually tracked by scope. (should make things faster with whitelisted)
*/
ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) {
var c, changes, prop;
if (whitelistedProps) {
prev = _.pick(prev, whitelistedProps);
now = _.pick(now, whitelistedProps);
}
changes = {};
prop = {};
c = {};
for (prop in now) {
if (!prev || prev[prop] !== now[prop]) {
if (_.isArray(now[prop])) {
changes[prop] = now[prop];
} else if (_.isObject(now[prop])) {
c = this.getChanges(now[prop], (prev ? prev[prop] : null));
if (!_.isEmpty(c)) {
changes[prop] = c;
}
} else {
changes[prop] = now[prop];
}
}
}
return changes;
};
ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) {
var maybeWrap, modelKey, modelProp, scopeProp;
if (doWrap == null) {
doWrap = false;
}
maybeWrap = function(isScope, ret, doWrap) {
if (doWrap == null) {
doWrap = false;
}
if (doWrap) {
return {
isScope: isScope,
value: ret
};
}
return ret;
};
scopeProp = scope[key];
if (_.isFunction(scopeProp)) {
return maybeWrap(true, scopeProp(model), doWrap);
}
if (_.isObject(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
if (!_.isString(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
modelKey = scopeProp;
if (!modelKey) {
modelProp = model[key];
} else {
modelProp = modelKey === 'self' ? model : model[modelKey];
}
if (_.isFunction(modelProp)) {
return maybeWrap(false, modelProp(), doWrap);
}
return maybeWrap(false, modelProp, doWrap);
};
ModelKey.prototype.setChildScope = function(keys, childScope, model) {
_.each(keys, (function(_this) {
return function(name) {
var isScopeObj, newValue;
isScopeObj = _this.scopeOrModelVal(name, childScope, model, true);
if ((isScopeObj != null ? isScopeObj.value : void 0) != null) {
newValue = isScopeObj.value;
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
}
};
})(this));
return childScope.model = model;
};
ModelKey.prototype.onDestroy = function(scope) {};
ModelKey.prototype.destroy = function(manualOverride) {
var _ref;
if (manualOverride == null) {
manualOverride = false;
}
if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
} else {
return this.clean();
}
};
ModelKey.prototype.updateChild = function(child, model) {
if (model[this.idKey] == null) {
this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
return child.updateModel(model);
};
ModelKey.prototype.modelsLength = function() {
var len;
len = 0;
if (this.scope.models == null) {
return len;
}
if (angular.isArray(this.scope.models) || (this.scope.models.length != null)) {
len = this.scope.models.length;
} else {
len = Object.keys(this.scope.models).length;
}
return len;
};
return ModelKey;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [
'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) {
return {
didQueueInitPromise: function(existingPiecesObj, scope) {
if (scope.models.length === 0) {
_async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) {
return function() {
return uiGmapPromise.resolve();
};
})(this)));
return true;
}
return false;
},
figureOutState: function(idKey, scope, childObjects, comparison, callBack) {
var adds, children, mappedScopeModelIds, removals, updates;
adds = [];
mappedScopeModelIds = {};
removals = [];
updates = [];
scope.models.forEach(function(m) {
var child;
if (m[idKey] != null) {
mappedScopeModelIds[m[idKey]] = {};
if (childObjects.get(m[idKey]) == null) {
return adds.push(m);
} else {
child = childObjects.get(m[idKey]);
if (!comparison(m, child.clonedModel)) {
return updates.push({
model: m,
child: child
});
}
}
} else {
return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion');
}
});
children = childObjects.values();
children.forEach(function(c) {
var id;
if (c == null) {
Logger.error('child undefined in ModelsWatcher.');
return;
}
if (c.model == null) {
Logger.error('child.model undefined in ModelsWatcher.');
return;
}
id = c.model[idKey];
if (mappedScopeModelIds[id] == null) {
return removals.push(c);
}
});
return {
adds: adds,
removals: removals,
updates: updates
};
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [
'$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) {
var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses;
promiseTypes = {
create: 'create',
update: 'update',
"delete": 'delete',
init: 'init'
};
promiseStatuses = {
IN_PROGRESS: 0,
RESOLVED: 1,
REJECTED: 2
};
strPromiseStatuses = (function() {
var obj;
obj = {};
obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress';
obj["" + promiseStatuses.RESOLVED] = 'resolved';
obj["" + promiseStatuses.REJECTED] = 'rejected';
return obj;
})();
isInProgress = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.IN_PROGRESS;
}
if (!promise.hasOwnProperty("$$v")) {
return true;
}
};
isResolved = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.RESOLVED;
}
if (promise.hasOwnProperty("$$v")) {
return true;
}
};
promiseStatus = function(status) {
return strPromiseStatuses[status] || 'done w error';
};
ExposedPromise = function(promise) {
var cancelDeferred, combined, wrapped;
cancelDeferred = $q.defer();
combined = $q.all([promise, cancelDeferred.promise]);
wrapped = $q.defer();
promise.then(cancelDeferred.resolve, (function() {}), function(notify) {
cancelDeferred.notify(notify);
return wrapped.notify(notify);
});
combined.then(function(successes) {
return wrapped.resolve(successes[0] || successes[1]);
}, function(error) {
return wrapped.reject(error);
});
wrapped.promise.cancel = function(reason) {
if (reason == null) {
reason = 'canceled';
}
return cancelDeferred.reject(reason);
};
wrapped.promise.notify = function(msg) {
if (msg == null) {
msg = 'cancel safe';
}
wrapped.notify(msg);
if (promise.hasOwnProperty('notify')) {
return promise.notify(msg);
}
};
if (promise.promiseType != null) {
wrapped.promise.promiseType = promise.promiseType;
}
return wrapped.promise;
};
SniffedPromise = function(fnPromise, promiseType) {
return {
promise: fnPromise,
promiseType: promiseType
};
};
defer = function() {
return $q.defer();
};
resolve = function() {
var d;
d = $q.defer();
d.resolve.apply(void 0, arguments);
return d.promise;
};
promise = function(fnToWrap) {
var d;
if (!_.isFunction(fnToWrap)) {
$log.error("uiGmapPromise.promise() only accepts functions");
return;
}
d = $q.defer();
$timeout(function() {
var result;
result = fnToWrap();
return d.resolve(result);
});
return d.promise;
};
return {
defer: defer,
promise: promise,
resolve: resolve,
promiseTypes: promiseTypes,
isInProgress: isInProgress,
isResolved: isResolved,
promiseStatus: promiseStatus,
ExposedPromise: ExposedPromise,
SniffedPromise: SniffedPromise
};
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() {
/*
Simple Object Map with a length property to make it easy to track length/size
*/
var PropMap;
return PropMap = (function() {
function PropMap() {
this.removeAll = __bind(this.removeAll, this);
this.slice = __bind(this.slice, this);
this.push = __bind(this.push, this);
this.keys = __bind(this.keys, this);
this.values = __bind(this.values, this);
this.remove = __bind(this.remove, this);
this.put = __bind(this.put, this);
this.stateChanged = __bind(this.stateChanged, this);
this.get = __bind(this.get, this);
this.length = 0;
this.dict = {};
this.didValsStateChange = false;
this.didKeysStateChange = false;
this.allVals = [];
this.allKeys = [];
}
PropMap.prototype.get = function(key) {
return this.dict[key];
};
PropMap.prototype.stateChanged = function() {
this.didValsStateChange = true;
return this.didKeysStateChange = true;
};
PropMap.prototype.put = function(key, value) {
if (this.get(key) == null) {
this.length++;
}
this.stateChanged();
return this.dict[key] = value;
};
PropMap.prototype.remove = function(key, isSafe) {
var value;
if (isSafe == null) {
isSafe = false;
}
if (isSafe && !this.get(key)) {
return void 0;
}
value = this.dict[key];
delete this.dict[key];
this.length--;
this.stateChanged();
return value;
};
PropMap.prototype.valuesOrKeys = function(str) {
var keys, vals;
if (str == null) {
str = 'Keys';
}
if (!this["did" + str + "StateChange"]) {
return this['all' + str];
}
vals = [];
keys = [];
_.each(this.dict, function(v, k) {
vals.push(v);
return keys.push(k);
});
this.didKeysStateChange = false;
this.didValsStateChange = false;
this.allVals = vals;
this.allKeys = keys;
return this['all' + str];
};
PropMap.prototype.values = function() {
return this.valuesOrKeys('Vals');
};
PropMap.prototype.keys = function() {
return this.valuesOrKeys();
};
PropMap.prototype.push = function(obj, key) {
if (key == null) {
key = "key";
}
return this.put(obj[key], obj);
};
PropMap.prototype.slice = function() {
return this.keys().map((function(_this) {
return function(k) {
return _this.remove(k);
};
})(this));
};
PropMap.prototype.removeAll = function() {
return this.slice();
};
PropMap.prototype.each = function(cb) {
return _.each(this.dict, function(v, k) {
return cb(v);
});
};
PropMap.prototype.map = function(cb) {
return _.map(this.dict, function(v, k) {
return cb(v);
});
};
return PropMap;
})();
});
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [
"uiGmapLogger", function(Logger) {
var PropertyAction;
PropertyAction = function(setterFn) {
this.setIfChange = function(newVal, oldVal) {
var callingKey;
callingKey = this.exp;
if (!_.isEqual(oldVal, newVal)) {
return setterFn(callingKey, newVal);
}
};
this.sic = this.setIfChange;
return this;
};
return PropertyAction;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [
'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) {
var ClustererMarkerManager;
ClustererMarkerManager = (function() {
ClustererMarkerManager.type = 'ClustererMarkerManager';
function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) {
if (opt_markers == null) {
opt_markers = {};
}
this.opt_options = opt_options != null ? opt_options : {};
this.opt_events = opt_events;
this.checkSync = __bind(this.checkSync, this);
this.getGMarkers = __bind(this.getGMarkers, this);
this.fit = __bind(this.fit, this);
this.destroy = __bind(this.destroy, this);
this.clear = __bind(this.clear, this);
this.draw = __bind(this.draw, this);
this.removeMany = __bind(this.removeMany, this);
this.remove = __bind(this.remove, this);
this.addMany = __bind(this.addMany, this);
this.update = __bind(this.update, this);
this.add = __bind(this.add, this);
this.type = ClustererMarkerManager.type;
this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options);
this.propMapGMarkers = new PropMap();
this.attachEvents(this.opt_events, 'opt_events');
this.clusterer.setIgnoreHidden(true);
this.noDrawOnSingleAddRemoves = true;
$log.info(this);
}
ClustererMarkerManager.prototype.checkKey = function(gMarker) {
var msg;
if (gMarker.key == null) {
msg = 'gMarker.key undefined and it is REQUIRED!!';
return $log.error(msg);
}
};
ClustererMarkerManager.prototype.add = function(gMarker) {
this.checkKey(gMarker);
this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.put(gMarker.key, gMarker);
return this.checkSync();
};
ClustererMarkerManager.prototype.update = function(gMarker) {
this.remove(gMarker);
return this.add(gMarker);
};
ClustererMarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.remove = function(gMarker) {
var exists;
this.checkKey(gMarker);
exists = this.propMapGMarkers.get(gMarker.key);
if (exists) {
this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.remove(gMarker.key);
}
return this.checkSync();
};
ClustererMarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.remove(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.draw = function() {
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.clear = function() {
this.removeMany(this.getGMarkers());
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) {
var eventHandler, eventName, _results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
_results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer");
_results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName]));
} else {
_results.push(void 0);
}
}
return _results;
}
};
ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) {
var eventHandler, eventName, _results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
_results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info("" + optionsName + ": Clearing event: " + eventName + " to clusterer");
_results.push(google.maps.event.clearListeners(this.clusterer, eventName));
} else {
_results.push(void 0);
}
}
return _results;
}
};
ClustererMarkerManager.prototype.destroy = function() {
this.clearEvents(this.opt_events, 'opt_events');
return this.clear();
};
ClustererMarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap());
};
ClustererMarkerManager.prototype.getGMarkers = function() {
return this.clusterer.getMarkers().values();
};
ClustererMarkerManager.prototype.checkSync = function() {};
return ClustererMarkerManager;
})();
return ClustererMarkerManager;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [
"uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) {
var MarkerManager;
MarkerManager = (function() {
MarkerManager.type = 'MarkerManager';
function MarkerManager(gMap, opt_markers, opt_options) {
this.getGMarkers = __bind(this.getGMarkers, this);
this.fit = __bind(this.fit, this);
this.handleOptDraw = __bind(this.handleOptDraw, this);
this.clear = __bind(this.clear, this);
this.draw = __bind(this.draw, this);
this.removeMany = __bind(this.removeMany, this);
this.remove = __bind(this.remove, this);
this.addMany = __bind(this.addMany, this);
this.update = __bind(this.update, this);
this.add = __bind(this.add, this);
this.type = MarkerManager.type;
this.gMap = gMap;
this.gMarkers = new PropMap();
this.$log = Logger;
this.$log.info(this);
}
MarkerManager.prototype.add = function(gMarker, optDraw) {
var exists, msg;
if (optDraw == null) {
optDraw = true;
}
if (gMarker.key == null) {
msg = "gMarker.key undefined and it is REQUIRED!!";
Logger.error(msg);
throw msg;
}
exists = this.gMarkers.get(gMarker.key);
if (!exists) {
this.handleOptDraw(gMarker, optDraw, true);
return this.gMarkers.put(gMarker.key, gMarker);
}
};
MarkerManager.prototype.update = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.remove(gMarker, optDraw);
return this.add(gMarker, optDraw);
};
MarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
MarkerManager.prototype.remove = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.handleOptDraw(gMarker, optDraw, false);
if (this.gMarkers.get(gMarker.key)) {
return this.gMarkers.remove(gMarker.key);
}
};
MarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(marker) {
return _this.remove(marker);
};
})(this));
};
MarkerManager.prototype.draw = function() {
var deletes;
deletes = [];
this.gMarkers.each((function(_this) {
return function(gMarker) {
if (!gMarker.isDrawn) {
if (gMarker.doAdd) {
gMarker.setMap(_this.gMap);
return gMarker.isDrawn = true;
} else {
return deletes.push(gMarker);
}
}
};
})(this));
return deletes.forEach((function(_this) {
return function(gMarker) {
gMarker.isDrawn = false;
return _this.remove(gMarker, true);
};
})(this));
};
MarkerManager.prototype.clear = function() {
this.gMarkers.each(function(gMarker) {
return gMarker.setMap(null);
});
delete this.gMarkers;
return this.gMarkers = new PropMap();
};
MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) {
if (optDraw === true) {
if (doAdd) {
gMarker.setMap(this.gMap);
} else {
gMarker.setMap(null);
}
return gMarker.isDrawn = true;
} else {
gMarker.isDrawn = false;
return gMarker.doAdd = doAdd;
}
};
MarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.gMap);
};
MarkerManager.prototype.getGMarkers = function() {
return this.gMarkers.values();
};
return MarkerManager;
})();
return MarkerManager;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [
'$timeout', function($timeout) {
var addEvent, addEvents;
addEvent = function(target, eventName, handler) {
return google.maps.event.addListener(target, eventName, function() {
handler.apply(this, arguments);
return $timeout((function() {}), true);
});
};
addEvents = function(target, eventName, handler) {
var remove;
if (handler) {
return addEvent(target, eventName, handler);
}
remove = [];
angular.forEach(eventName, function(_handler, key) {
return remove.push(addEvent(target, key, _handler));
});
return function() {
angular.forEach(remove, function(listener) {
return google.maps.event.removeListener(listener);
});
return remove = null;
};
};
return addEvents;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [
'uiGmapadd-events', function(mapEvents) {
return function(mapArray, scope, pathEval, pathChangedFn) {
var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener;
isSetFromScope = false;
scopePath = scope.$eval(pathEval);
if (!scope["static"]) {
legacyHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath[index] = value;
} else {
scopePath[index].latitude = value.lat();
return scopePath[index].longitude = value.lng();
}
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath.splice(index, 0, value);
} else {
return scopePath.splice(index, 0, {
latitude: value.lat(),
longitude: value.lng()
});
}
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return scopePath.splice(index, 1);
}
};
geojsonArray;
if (scopePath.type === 'Polygon') {
geojsonArray = scopePath.coordinates[0];
} else if (scopePath.type === 'LineString') {
geojsonArray = scopePath.coordinates;
}
geojsonHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
geojsonArray[index][1] = value.lat();
return geojsonArray[index][0] = value.lng();
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
return geojsonArray.splice(index, 0, [value.lng(), value.lat()]);
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return geojsonArray.splice(index, 1);
}
};
mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers);
}
legacyWatcher = function(newPath) {
var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
i = 0;
oldLength = oldArray.getLength();
newLength = newPath.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = newPath[i];
if (typeof newValue.equals === 'function') {
if (!newValue.equals(oldValue)) {
oldArray.setAt(i, newValue);
changed = true;
}
} else {
if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) {
oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude));
changed = true;
}
}
i++;
}
while (i < newLength) {
newValue = newPath[i];
if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') {
oldArray.push(newValue);
} else {
oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude));
}
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
geojsonWatcher = function(newPath) {
var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
array;
if (scopePath.type === 'Polygon') {
array = newPath.coordinates[0];
} else if (scopePath.type === 'LineString') {
array = newPath.coordinates;
}
i = 0;
oldLength = oldArray.getLength();
newLength = array.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = array[i];
if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) {
oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
}
i++;
}
while (i < newLength) {
newValue = array[i];
oldArray.push(new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
watchListener;
if (!scope["static"]) {
if (angular.isUndefined(scopePath.type)) {
watchListener = scope.$watchCollection(pathEval, legacyWatcher);
} else {
watchListener = scope.$watch(pathEval, geojsonWatcher, true);
}
}
return function() {
if (mapArrayListener) {
mapArrayListener();
mapArrayListener = null;
}
if (watchListener) {
watchListener();
return watchListener = null;
}
};
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [
'$timeout', function($timeout) {
return {
maybeRepaint: function(el) {
if (el) {
el.style.opacity = 0.9;
return $timeout(function() {
return el.style.opacity = 1;
});
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() {
var _ignores, _iterators, _slapForEach, _slapMap;
_ignores = ['length', 'forEach', 'map'];
_iterators = [];
_slapForEach = function(object) {
object.forEach = function(cb) {
return _.each(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapForEach);
_slapMap = function(object) {
object.map = function(cb) {
return _.map(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapMap);
return {
slapMap: _slapMap,
slapForEach: _slapForEach,
slapAll: function(object) {
_iterators.forEach(function(it) {
return it(object);
});
return object;
}
};
});
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) {
var CommonOptionsBuilder;
return CommonOptionsBuilder = (function(_super) {
__extends(CommonOptionsBuilder, _super);
function CommonOptionsBuilder() {
this.watchProps = __bind(this.watchProps, this);
this.buildOpts = __bind(this.buildOpts, this);
return CommonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CommonOptionsBuilder.prototype.props = [
'clickable', 'draggable', 'editable', 'visible', {
prop: 'stroke',
isColl: true
}
];
CommonOptionsBuilder.prototype.getCorrectModel = function(scope) {
if (angular.isDefined(scope != null ? scope.model : void 0)) {
return scope.model;
} else {
return scope;
}
};
CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var model, opts, stroke;
if (customOpts == null) {
customOpts = {};
}
if (forEachOpts == null) {
forEachOpts = {};
}
if (!this.scope) {
$log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts');
return;
}
if (!this.map) {
$log.error('this.map not defined in CommonOptionsBuilder can not buildOpts');
return;
}
model = this.getCorrectModel(this.scope);
stroke = this.scopeOrModelVal('stroke', this.scope, model);
opts = angular.extend(customOpts, this.DEFAULTS, {
map: this.map,
strokeColor: stroke != null ? stroke.color : void 0,
strokeOpacity: stroke != null ? stroke.opacity : void 0,
strokeWeight: stroke != null ? stroke.weight : void 0
});
angular.forEach(angular.extend(forEachOpts, {
clickable: true,
draggable: false,
editable: false,
"static": false,
fit: false,
visible: true,
zIndex: 0,
icons: []
}), (function(_this) {
return function(defaultValue, key) {
var val;
val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model);
if (angular.isUndefined(val)) {
return opts[key] = defaultValue;
} else {
return opts[key] = model[key];
}
};
})(this));
if (opts["static"]) {
opts.editable = false;
}
return opts;
};
CommonOptionsBuilder.prototype.watchProps = function(props) {
if (props == null) {
props = this.props;
}
return props.forEach((function(_this) {
return function(prop) {
if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) {
if (prop != null ? prop.isColl : void 0) {
return _this.scope.$watchCollection(prop.prop, _this.setMyOptions);
} else {
return _this.scope.$watch(prop, _this.setMyOptions);
}
}
};
})(this));
};
return CommonOptionsBuilder;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var PolylineOptionsBuilder;
return PolylineOptionsBuilder = (function(_super) {
__extends(PolylineOptionsBuilder, _super);
function PolylineOptionsBuilder() {
return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolylineOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolylineOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapShapeOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var ShapeOptionsBuilder;
return ShapeOptionsBuilder = (function(_super) {
__extends(ShapeOptionsBuilder, _super);
function ShapeOptionsBuilder() {
return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments);
}
ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var fill, model;
model = this.getCorrectModel(this.scope);
fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model);
customOpts = angular.extend(customOpts, {
fillColor: fill != null ? fill.color : void 0,
fillOpacity: fill != null ? fill.opacity : void 0
});
return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts);
};
return ShapeOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapPolygonOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var PolygonOptionsBuilder;
return PolygonOptionsBuilder = (function(_super) {
__extends(PolygonOptionsBuilder, _super);
function PolygonOptionsBuilder() {
return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolygonOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolygonOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapRectangleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var RectangleOptionsBuilder;
return RectangleOptionsBuilder = (function(_super) {
__extends(RectangleOptionsBuilder, _super);
function RectangleOptionsBuilder() {
return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) {
return RectangleOptionsBuilder.__super__.buildOpts.call(this, {
bounds: bounds
}, cachedEval);
};
return RectangleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapCircleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var CircleOptionsBuilder;
return CircleOptionsBuilder = (function(_super) {
__extends(CircleOptionsBuilder, _super);
function CircleOptionsBuilder() {
return CircleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) {
return CircleOptionsBuilder.__super__.buildOpts.call(this, {
center: center,
radius: radius
}, cachedEval);
};
return CircleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [
'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) {
return _.extend(GmapUtil, {
createOptions: function(coords, icon, defaults, map) {
var opts;
if (defaults == null) {
defaults = {};
}
opts = angular.extend({}, defaults, {
position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords),
visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords)
});
if ((defaults.icon != null) || (icon != null)) {
opts = angular.extend(opts, {
icon: defaults.icon != null ? defaults.icon : icon
});
}
if (map != null) {
opts.map = map;
}
return opts;
},
isLabel: function(options) {
if (options == null) {
return false;
}
return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null);
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [
'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) {
return function(Builder, gFactory) {
var BasePolyChildModel;
return BasePolyChildModel = (function(_super) {
__extends(BasePolyChildModel, _super);
BasePolyChildModel.include(GmapUtil);
function BasePolyChildModel(scope, attrs, map, defaults, model) {
var create;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.defaults = defaults;
this.model = model;
this.clean = __bind(this.clean, this);
this.clonedModel = _.clone(this.model, true);
this.isDragging = false;
this.internalEvents = {
dragend: (function(_this) {
return function() {
return _.defer(function() {
return _this.isDragging = false;
});
};
})(this),
dragstart: (function(_this) {
return function() {
return _this.isDragging = true;
};
})(this)
};
create = (function(_this) {
return function() {
var maybeCachedEval, pathPoints;
if (_this.isDragging) {
return;
}
pathPoints = _this.convertPathPoints(_this.scope.path);
if (_this.gObject != null) {
_this.clean();
}
if (scope.model != null) {
maybeCachedEval = scope;
}
if (pathPoints.length > 0) {
_this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval));
}
if (_this.gObject) {
if (_this.scope.fit) {
_this.extendMapBounds(map, pathPoints);
}
arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) {
if (_this.scope.fit) {
return _this.extendMapBounds(map, pathPoints);
}
});
if (angular.isDefined(scope.events) && angular.isObject(scope.events)) {
_this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope);
}
return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.model) : EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.scope);
}
};
})(this);
create();
scope.$watch('path', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.gObject) {
return create();
}
};
})(this), true);
if (!scope["static"] && angular.isDefined(scope.editable)) {
scope.$watch('editable', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setEditable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.draggable)) {
scope.$watch('draggable', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setDraggable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.visible)) {
scope.$watch('visible', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
}
return (_ref = _this.gObject) != null ? _ref.setVisible(newValue) : void 0;
};
})(this), true);
}
if (angular.isDefined(scope.geodesic)) {
scope.$watch('geodesic', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) {
scope.$watch('stroke.weight', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) {
scope.$watch('stroke.color', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) {
scope.$watch('stroke.opacity', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.icons)) {
scope.$watch('icons', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
scope.$on('$destroy', (function(_this) {
return function() {
_this.clean();
return _this.scope = null;
};
})(this));
if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) {
scope.$watch('fill.color', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) {
scope.$watch('fill.opacity', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(scope.zIndex)) {
scope.$watch('zIndex', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
}
BasePolyChildModel.prototype.clean = function() {
var _ref;
EventsHelper.removeEvents(this.listeners);
EventsHelper.removeEvents(this.internalListeners);
if ((_ref = this.gObject) != null) {
_ref.setMap(null);
}
return this.gObject = null;
};
return BasePolyChildModel;
})(Builder);
};
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , &
http://jsfiddle.net/YsQdh/88/
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [
'uiGmapLogger', '$q', function($log, $q) {
var drawFreeHand, freeHandMgr;
drawFreeHand = function(map, polys, enable) {
var move, poly;
poly = new google.maps.Polyline({
map: map,
clickable: false
});
move = google.maps.event.addListener(map, 'mousemove', function(e) {
return poly.getPath().push(e.latLng);
});
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
var path;
google.maps.event.removeListener(move);
path = poly.getPath();
poly.setMap(null);
polys.push(new google.maps.Polygon({
map: map,
path: path
}));
poly = null;
google.maps.event.clearListeners(map.getDiv(), 'mousedown');
return enable();
});
return void 0;
};
freeHandMgr = function(map, defaultOptions) {
var disableMap, enable;
this.map = map;
if (!defaultOptions) {
defaultOptions = {
draggable: true,
zoomControl: true,
scrollwheel: true,
disableDoubleClickZoom: true
};
}
enable = (function(_this) {
return function() {
var _ref;
if ((_ref = _this.deferred) != null) {
_ref.resolve();
}
return _.defer(function() {
return _this.map.setOptions(_.extend(_this.oldOptions, defaultOptions));
});
};
})(this);
disableMap = (function(_this) {
return function() {
$log.info('disabling map move');
_this.oldOptions = map.getOptions();
_this.oldOptions.center = map.getCenter();
return _this.map.setOptions({
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false
});
};
})(this);
this.engage = (function(_this) {
return function(polys) {
_this.polys = polys;
_this.deferred = $q.defer();
disableMap();
$log.info('DrawFreeHandChildModel is engaged (drawing).');
google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) {
return drawFreeHand(_this.map, _this.polys, enable);
});
return _this.deferred.promise;
};
})(this);
return this;
};
return freeHandMgr;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) {
var MarkerChildModel;
MarkerChildModel = (function(_super) {
var destroy;
__extends(MarkerChildModel, _super);
MarkerChildModel.include(GmapUtil);
MarkerChildModel.include(EventsHelper);
MarkerChildModel.include(MarkerOptions);
destroy = function(child) {
if ((child != null ? child.gObject : void 0) != null) {
child.removeEvents(child.externalListeners);
child.removeEvents(child.internalListeners);
if (child != null ? child.gObject : void 0) {
if (child.removeFromManager) {
child.gManager.remove(child.gObject);
}
child.gObject.setMap(null);
return child.gObject = null;
}
}
};
function MarkerChildModel(scope, model, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) {
var action;
this.model = model;
this.keys = keys;
this.gMap = gMap;
this.defaults = defaults;
this.doClick = doClick;
this.gManager = gManager;
this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true;
this.trackModel = trackModel != null ? trackModel : true;
this.needRedraw = needRedraw != null ? needRedraw : false;
this.internalEvents = __bind(this.internalEvents, this);
this.setLabelOptions = __bind(this.setLabelOptions, this);
this.setOptions = __bind(this.setOptions, this);
this.setIcon = __bind(this.setIcon, this);
this.setCoords = __bind(this.setCoords, this);
this.isNotValid = __bind(this.isNotValid, this);
this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this);
this.createMarker = __bind(this.createMarker, this);
this.setMyScope = __bind(this.setMyScope, this);
this.updateModel = __bind(this.updateModel, this);
this.handleModelChanges = __bind(this.handleModelChanges, this);
this.destroy = __bind(this.destroy, this);
this.clonedModel = _.extend({}, this.model);
this.deferred = uiGmapPromise.defer();
_.each(this.keys, (function(_this) {
return function(v, k) {
return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k];
};
})(this));
this.idKey = this.idKeyKey || 'id';
if (this.model[this.idKey] != null) {
this.id = this.model[this.idKey];
}
MarkerChildModel.__super__.constructor.call(this, scope);
this.scope.getGMarker = (function(_this) {
return function() {
return _this.gObject;
};
})(this);
this.firstTime = true;
if (this.trackModel) {
this.scope.model = this.model;
this.scope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.handleModelChanges(newValue, oldValue);
}
};
})(this), true);
} else {
action = new PropertyAction((function(_this) {
return function(calledKey, newVal) {
if (!_this.firstTime) {
return _this.setMyScope(calledKey, scope);
}
};
})(this), false);
_.each(this.keys, function(v, k) {
return scope.$watch(k, action.sic, true);
});
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return destroy(_this);
};
})(this));
this.createMarker(this.model);
$log.info(this);
}
MarkerChildModel.prototype.destroy = function(removeFromManager) {
if (removeFromManager == null) {
removeFromManager = true;
}
this.removeFromManager = removeFromManager;
return this.scope.$destroy();
};
MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) {
var changes, ctr, len;
changes = this.getChanges(newValue, oldValue, IMarker.keys);
if (!this.firstTime) {
ctr = 0;
len = _.keys(changes).length;
return _.each(changes, (function(_this) {
return function(v, k) {
var doDraw;
ctr += 1;
doDraw = len === ctr;
_this.setMyScope(k, newValue, oldValue, false, true, doDraw);
return _this.needRedraw = true;
};
})(this));
}
};
MarkerChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return this.setMyScope('all', model, this.model);
};
MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) {
var coords;
if (doDraw == null) {
doDraw = true;
}
coords = this.getProp(this.coordsKey, this.model);
if (coords != null) {
if (!this.validateCoords(coords)) {
$log.debug('MarkerChild does not have coords yet. They may be defined later.');
return;
}
if (validCb != null) {
validCb();
}
if (doDraw && this.gObject) {
return this.gManager.add(this.gObject);
}
} else {
if (doDraw && this.gObject) {
return this.gManager.remove(this.gObject);
}
}
};
MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) {
var justCreated;
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
if (model == null) {
model = this.model;
} else {
this.model = model;
}
if (!this.gObject) {
this.setOptions(this.scope, doDraw);
justCreated = true;
}
switch (thingThatChanged) {
case 'all':
return _.each(this.keys, (function(_this) {
return function(v, k) {
return _this.setMyScope(k, model, oldModel, isInit, doDraw);
};
})(this));
case 'icon':
return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw);
case 'coords':
return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw);
case 'options':
if (!justCreated) {
return this.createMarker(model, oldModel, isInit, doDraw);
}
}
};
MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) {
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw);
return this.firstTime = false;
};
MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) {
if (gSetter == null) {
gSetter = void 0;
}
if (doDraw == null) {
doDraw = true;
}
if (gSetter != null) {
return gSetter(this.scope, doDraw);
}
};
if (MarkerChildModel.doDrawSelf && doDraw) {
MarkerChildModel.gManager.draw();
}
MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) {
var hasIdenticalScopes, hasNoGmarker;
if (doCheckGmarker == null) {
doCheckGmarker = true;
}
hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0;
hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false;
return hasIdenticalScopes || hasNoGmarker;
};
MarkerChildModel.prototype.setCoords = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var newGValue, newModelVal, oldGValue;
newModelVal = _this.getProp(_this.coordsKey, _this.model);
newGValue = _this.getCoords(newModelVal);
oldGValue = _this.gObject.getPosition();
if ((oldGValue != null) && (newGValue != null)) {
if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) {
return;
}
}
_this.gObject.setPosition(newGValue);
return _this.gObject.setVisible(_this.validateCoords(newModelVal));
};
})(this));
};
MarkerChildModel.prototype.setIcon = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, newValue, oldValue;
oldValue = _this.gObject.getIcon();
newValue = _this.getProp(_this.iconKey, _this.model);
if (oldValue === newValue) {
return;
}
_this.gObject.setIcon(newValue);
coords = _this.getProp(_this.coordsKey, _this.model);
_this.gObject.setPosition(_this.getCoords(coords));
return _this.gObject.setVisible(_this.validateCoords(coords));
};
})(this));
};
MarkerChildModel.prototype.setOptions = function(scope, doDraw) {
var _ref;
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope, false)) {
return;
}
this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, icon, _options;
coords = _this.getProp(_this.coordsKey, _this.model);
icon = _this.getProp(_this.iconKey, _this.model);
_options = _this.getProp(_this.optionsKey, _this.model);
_this.opts = _this.createOptions(coords, icon, _options);
if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) {
_this.gManager.remove(_this.gObject);
_this.gObject = void 0;
}
if (_this.gObject != null) {
_this.gObject.setOptions(_this.setLabelOptions(_this.opts));
}
if (!_this.gObject) {
if (_this.isLabel(_this.opts)) {
_this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts));
} else {
_this.gObject = new google.maps.Marker(_this.opts);
}
_.extend(_this.gObject, {
model: _this.model
});
}
if (_this.externalListeners) {
_this.removeEvents(_this.externalListeners);
}
if (_this.internalListeners) {
_this.removeEvents(_this.internalListeners);
}
_this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']);
_this.internalListeners = _this.setEvents(_this.gObject, {
events: _this.internalEvents(),
$evalAsync: function() {}
}, _this.model);
if (_this.id != null) {
return _this.gObject.key = _this.id;
}
};
})(this));
if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) {
this.deferred.resolve(this.gObject);
} else {
if (!this.gObject) {
return this.deferred.reject('gObject is null');
}
if (!(((_ref = this.gObject) != null ? _ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) {
$log.debug('gObject has no map yet');
this.deferred.resolve(this.gObject);
}
}
if (this.model[this.fitKey]) {
return this.gManager.fit();
}
};
MarkerChildModel.prototype.setLabelOptions = function(opts) {
opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor);
return opts;
};
MarkerChildModel.prototype.internalEvents = function() {
return {
dragend: (function(_this) {
return function(marker, eventName, model, mousearg) {
var events, modelToSet, newCoords;
modelToSet = _this.trackModel ? _this.scope.model : _this.model;
newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition());
modelToSet = _this.setVal(model, _this.coordsKey, newCoords);
events = _this.scope.events;
if ((events != null ? events.dragend : void 0) != null) {
events.dragend(marker, eventName, modelToSet, mousearg);
}
return _this.scope.$apply();
};
})(this),
click: (function(_this) {
return function(marker, eventName, model, mousearg) {
var click;
click = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _this.model);
if (_this.doClick && (click != null)) {
return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg));
}
};
})(this)
};
};
return MarkerChildModel;
})(ModelKey);
return MarkerChildModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) {
var PolygonChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polygon(opts);
};
base = new BaseGen(Builder, gFactory);
return PolygonChildModel = (function(_super) {
__extends(PolygonChildModel, _super);
function PolygonChildModel() {
return PolygonChildModel.__super__.constructor.apply(this, arguments);
}
return PolygonChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) {
var PolylineChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polyline(opts);
};
base = BaseGen(Builder, gFactory);
return PolylineChildModel = (function(_super) {
__extends(PolylineChildModel, _super);
function PolylineChildModel() {
return PolylineChildModel.__super__.constructor.apply(this, arguments);
}
return PolylineChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) {
var WindowChildModel;
WindowChildModel = (function(_super) {
__extends(WindowChildModel, _super);
WindowChildModel.include(GmapUtil);
WindowChildModel.include(EventsHelper);
function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) {
var maybeMarker;
this.model = model;
this.scope = scope;
this.opts = opts;
this.isIconVisibleOnClick = isIconVisibleOnClick;
this.mapCtrl = mapCtrl;
this.markerScope = markerScope;
this.element = element;
this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false;
this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true;
this.updateModel = __bind(this.updateModel, this);
this.destroy = __bind(this.destroy, this);
this.remove = __bind(this.remove, this);
this.getLatestPosition = __bind(this.getLatestPosition, this);
this.hideWindow = __bind(this.hideWindow, this);
this.showWindow = __bind(this.showWindow, this);
this.handleClick = __bind(this.handleClick, this);
this.watchOptions = __bind(this.watchOptions, this);
this.watchCoords = __bind(this.watchCoords, this);
this.createGWin = __bind(this.createGWin, this);
this.watchElement = __bind(this.watchElement, this);
this.watchAndDoShow = __bind(this.watchAndDoShow, this);
this.doShow = __bind(this.doShow, this);
this.clonedModel = _.clone(this.model, true);
this.getGmarker = function() {
var _ref, _ref1;
if (((_ref = this.markerScope) != null ? _ref['getGMarker'] : void 0) != null) {
return (_ref1 = this.markerScope) != null ? _ref1.getGMarker() : void 0;
}
};
this.listeners = [];
this.createGWin();
maybeMarker = this.getGmarker();
if (maybeMarker != null) {
maybeMarker.setClickable(true);
}
this.watchElement();
this.watchOptions();
this.watchCoords();
this.watchAndDoShow();
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.destroy();
};
})(this));
$log.info(this);
}
WindowChildModel.prototype.doShow = function(wasOpen) {
if (this.scope.show === true || wasOpen) {
return this.showWindow();
} else {
return this.hideWindow();
}
};
WindowChildModel.prototype.watchAndDoShow = function() {
if (this.model.show != null) {
this.scope.show = this.model.show;
}
this.scope.$watch('show', this.doShow, true);
return this.doShow();
};
WindowChildModel.prototype.watchElement = function() {
return this.scope.$watch((function(_this) {
return function() {
var wasOpen, _ref;
if (!(_this.element || _this.html)) {
return;
}
if (_this.html !== _this.element.html() && _this.gObject) {
if ((_ref = _this.opts) != null) {
_ref.content = void 0;
}
wasOpen = _this.gObject.isOpen();
_this.remove();
return _this.createGWin(wasOpen);
}
};
})(this));
};
WindowChildModel.prototype.createGWin = function(isOpen) {
var defaults, maybeMarker, _opts, _ref, _ref1;
if (isOpen == null) {
isOpen = false;
}
maybeMarker = this.getGmarker();
defaults = {};
if (this.opts != null) {
if (this.scope.coords) {
this.opts.position = this.getCoords(this.scope.coords);
}
defaults = this.opts;
}
if (this.element) {
this.html = _.isObject(this.element) ? this.element.html() : this.element;
}
_opts = this.scope.options ? this.scope.options : defaults;
this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts);
if (this.opts != null) {
if (!this.gObject) {
if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) {
this.gObject = new window.InfoBox(this.opts);
} else {
this.gObject = new google.maps.InfoWindow(this.opts);
}
this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() {
return ChromeFixes.maybeRepaint(this.content);
}));
this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) {
return function() {
if (maybeMarker) {
maybeMarker.setAnimation(_this.oldMarkerAnimation);
if (_this.markerIsVisibleAfterWindowClose) {
_.delay(function() {
maybeMarker.setVisible(false);
return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose);
}, 250);
}
}
_this.gObject.close();
_this.model.show = false;
if (_this.scope.closeClick != null) {
return _this.scope.$evalAsync(_this.scope.closeClick());
} else {
return _this.scope.$evalAsync();
}
};
})(this)));
}
this.gObject.setContent(this.opts.content);
this.handleClick(((_ref = this.scope) != null ? (_ref1 = _ref.options) != null ? _ref1.forceClick : void 0 : void 0) || isOpen);
return this.doShow(this.gObject.isOpen());
}
};
WindowChildModel.prototype.watchCoords = function() {
var scope;
scope = this.markerScope != null ? this.markerScope : this.scope;
return scope.$watch('coords', (function(_this) {
return function(newValue, oldValue) {
var pos;
if (newValue !== oldValue) {
if (newValue == null) {
_this.hideWindow();
} else if (!_this.validateCoords(newValue)) {
$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model)));
return;
}
pos = _this.getCoords(newValue);
_this.gObject.setPosition(pos);
if (_this.opts) {
return _this.opts.position = pos;
}
}
};
})(this), true);
};
WindowChildModel.prototype.watchOptions = function() {
return this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.opts = newValue;
if (_this.gObject != null) {
_this.gObject.setOptions(_this.opts);
if ((_this.opts.visible != null) && _this.opts.visible) {
return _this.showWindow();
} else if (_this.opts.visible != null) {
return _this.hideWindow();
}
}
}
};
})(this), true);
};
WindowChildModel.prototype.handleClick = function(forceClick) {
var click, maybeMarker;
if (this.gObject == null) {
return;
}
maybeMarker = this.getGmarker();
click = (function(_this) {
return function() {
if (_this.gObject == null) {
_this.createGWin();
}
_this.showWindow();
if (maybeMarker != null) {
_this.initialMarkerVisibility = maybeMarker.getVisible();
_this.oldMarkerAnimation = maybeMarker.getAnimation();
return maybeMarker.setVisible(_this.isIconVisibleOnClick);
}
};
})(this);
if (forceClick) {
click();
}
if (maybeMarker) {
return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, {
events: {
click: click
}
}, this.model));
}
};
WindowChildModel.prototype.showWindow = function() {
var compiled, show, templateScope;
if (this.gObject != null) {
show = (function(_this) {
return function() {
var isOpen, maybeMarker, pos;
if (!_this.gObject.isOpen()) {
maybeMarker = _this.getGmarker();
if ((_this.gObject != null) && (_this.gObject.getPosition != null)) {
pos = _this.gObject.getPosition();
}
if (maybeMarker) {
pos = maybeMarker.getPosition();
}
if (!pos) {
return;
}
_this.gObject.open(_this.mapCtrl, maybeMarker);
isOpen = _this.gObject.isOpen();
if (_this.model.show !== isOpen) {
return _this.model.show = isOpen;
}
}
};
})(this);
if (this.scope.templateUrl) {
return $http.get(this.scope.templateUrl, {
cache: $templateCache
}).then((function(_this) {
return function(content) {
var compiled, templateScope;
templateScope = _this.scope.$new();
if (angular.isDefined(_this.scope.templateParameter)) {
templateScope.parameter = _this.scope.templateParameter;
}
compiled = $compile(content.data)(templateScope);
_this.gObject.setContent(compiled[0]);
return show();
};
})(this));
} else if (this.scope.template) {
templateScope = this.scope.$new();
if (angular.isDefined(this.scope.templateParameter)) {
templateScope.parameter = this.scope.templateParameter;
}
compiled = $compile(this.scope.template)(templateScope);
this.gObject.setContent(compiled[0]);
return show();
} else {
return show();
}
}
};
WindowChildModel.prototype.hideWindow = function() {
if ((this.gObject != null) && this.gObject.isOpen()) {
return this.gObject.close();
}
};
WindowChildModel.prototype.getLatestPosition = function(overridePos) {
var maybeMarker;
maybeMarker = this.getGmarker();
if ((this.gObject != null) && (maybeMarker != null) && !overridePos) {
return this.gObject.setPosition(maybeMarker.getPosition());
} else {
if (overridePos) {
return this.gObject.setPosition(overridePos);
}
}
};
WindowChildModel.prototype.remove = function() {
this.hideWindow();
this.removeEvents(this.listeners);
this.listeners.length = 0;
delete this.gObject;
return delete this.opts;
};
WindowChildModel.prototype.destroy = function(manualOverride) {
var _ref;
if (manualOverride == null) {
manualOverride = false;
}
this.remove();
if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
}
};
WindowChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return _.extend(this.model, this.clonedModel);
};
return WindowChildModel;
})(BaseObject);
return WindowChildModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) {
var CircleParentModel;
return CircleParentModel = (function(_super) {
__extends(CircleParentModel, _super);
CircleParentModel.include(GmapUtil);
CircleParentModel.include(EventsHelper);
function CircleParentModel(scope, element, attrs, map, DEFAULTS) {
var clean, gObject, lastRadius;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
lastRadius = null;
clean = (function(_this) {
return function() {
lastRadius = null;
if (_this.listeners != null) {
_this.removeEvents(_this.listeners);
return _this.listeners = void 0;
}
};
})(this);
gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
}
};
})(this);
this.props = this.props.concat([
{
prop: 'center',
isColl: true
}, {
prop: 'fill',
isColl: true
}, 'radius'
]);
this.watchProps();
clean();
this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']);
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() {
/*
possible google bug, and or because a circle has two radii
radius_changed appears to fire twice (original and new) which is not too helpful
therefore we will check for radius changes manually and bail out if nothing has changed
*/
var newRadius, work;
newRadius = gObject.getRadius();
if (newRadius === lastRadius) {
return;
}
lastRadius = newRadius;
work = function() {
var _ref, _ref1;
if (newRadius !== scope.radius) {
scope.radius = newRadius;
}
if (((_ref = scope.events) != null ? _ref.radius_changed : void 0) && _.isFunction((_ref1 = scope.events) != null ? _ref1.radius_changed : void 0)) {
return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments);
}
};
if (!angular.mock) {
return scope.$evalAsync(function() {
return work();
});
} else {
return work();
}
}));
}
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() {
return scope.$evalAsync(function() {
if (angular.isDefined(scope.center.type)) {
scope.center.coordinates[1] = gObject.getCenter().lat();
return scope.center.coordinates[0] = gObject.getCenter().lng();
} else {
scope.center.latitude = gObject.getCenter().lat();
return scope.center.longitude = gObject.getCenter().lng();
}
});
}));
}
scope.$on('$destroy', (function(_this) {
return function() {
clean();
return gObject.setMap(null);
};
})(this));
$log.info(this);
}
return CircleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) {
var DrawingManagerParentModel;
return DrawingManagerParentModel = (function(_super) {
__extends(DrawingManagerParentModel, _super);
DrawingManagerParentModel.include(EventsHelper);
function DrawingManagerParentModel(scope, element, attrs, map) {
var gObject, listeners;
this.scope = scope;
this.attrs = attrs;
this.map = map;
gObject = new google.maps.drawing.DrawingManager(this.scope.options);
gObject.setMap(this.map);
listeners = void 0;
if (this.scope.control != null) {
this.scope.control.getDrawingManager = function() {
return gObject;
};
}
if (!this.scope["static"] && this.scope.options) {
this.scope.$watch('options', function(newValue) {
return gObject != null ? gObject.setOptions(newValue) : void 0;
}, true);
}
if (this.scope.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
scope.$on('$destroy', (function(_this) {
return function() {
if (listeners != null) {
_this.removeEvents(listeners);
}
gObject.setMap(null);
return gObject = null;
};
})(this));
}
return DrawingManagerParentModel;
})(BaseObject);
}
]);
}).call(this);
;
/*
- interface for all markers to derrive from
- to enforce a minimum set of requirements
- attributes
- coords
- icon
- implementation needed on watches
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [
"uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) {
var IMarkerParentModel;
IMarkerParentModel = (function(_super) {
__extends(IMarkerParentModel, _super);
IMarkerParentModel.prototype.DEFAULTS = {};
function IMarkerParentModel(scope, element, attrs, map) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.map = map;
this.onWatch = __bind(this.onWatch, this);
this.watch = __bind(this.watch, this);
this.validateScope = __bind(this.validateScope, this);
IMarkerParentModel.__super__.constructor.call(this, this.scope);
this.$log = Logger;
if (!this.validateScope(scope)) {
throw new String("Unable to construct IMarkerParentModel due to invalid scope");
}
this.doClick = angular.isDefined(attrs.click);
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
this.watch('coords', this.scope);
this.watch('icon', this.scope);
this.watch('options', this.scope);
scope.$on("$destroy", (function(_this) {
return function() {
return _this.onDestroy(scope);
};
})(this));
}
IMarkerParentModel.prototype.validateScope = function(scope) {
var ret;
if (scope == null) {
this.$log.error(this.constructor.name + ": invalid scope used");
return false;
}
ret = scope.coords != null;
if (!ret) {
this.$log.error(this.constructor.name + ": no valid coords attribute found");
return false;
}
return ret;
};
IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) {
if (equalityCheck == null) {
equalityCheck = true;
}
return scope.$watch(propNameToWatch, (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.onWatch(propNameToWatch, scope, newValue, oldValue);
}
};
})(this), equalityCheck);
};
IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {};
return IMarkerParentModel;
})(ModelKey);
return IMarkerParentModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [
"uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) {
var IWindowParentModel;
return IWindowParentModel = (function(_super) {
__extends(IWindowParentModel, _super);
IWindowParentModel.include(GmapUtil);
function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) {
IWindowParentModel.__super__.constructor.call(this, scope);
this.$log = Logger;
this.$timeout = $timeout;
this.$compile = $compile;
this.$http = $http;
this.$templateCache = $templateCache;
this.DEFAULTS = {};
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
}
IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return IWindowParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) {
var LayerParentModel;
LayerParentModel = (function(_super) {
__extends(LayerParentModel, _super);
function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0;
this.$log = $log != null ? $log : Logger;
this.createGoogleLayer = __bind(this.createGoogleLayer, this);
if (this.attrs.type == null) {
this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!');
return;
}
this.createGoogleLayer();
this.doShow = true;
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.gObject.setMap(this.gMap);
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.gObject.setMap(_this.gMap);
} else {
return _this.gObject.setMap(null);
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.gObject.setMap(null);
_this.gObject = null;
return _this.createGoogleLayer();
}
};
})(this), true);
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject.setMap(null);
};
})(this));
}
LayerParentModel.prototype.createGoogleLayer = function() {
var _base;
if (this.attrs.options == null) {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type]();
} else {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options);
}
if ((this.gObject != null) && (this.onLayerCreated != null)) {
return typeof (_base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? _base(this.gObject) : void 0;
}
};
return LayerParentModel;
})(BaseObject);
return LayerParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) {
var MapTypeParentModel;
MapTypeParentModel = (function(_super) {
__extends(MapTypeParentModel, _super);
function MapTypeParentModel(scope, element, attrs, gMap, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.$log = $log != null ? $log : Logger;
this.hideOverlay = __bind(this.hideOverlay, this);
this.showOverlay = __bind(this.showOverlay, this);
this.refreshMapType = __bind(this.refreshMapType, this);
this.createMapType = __bind(this.createMapType, this);
if (this.attrs.options == null) {
this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!');
return;
}
this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0;
this.doShow = true;
this.createMapType();
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.showOverlay();
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.showOverlay();
} else {
return _this.hideOverlay();
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
if (angular.isDefined(this.attrs.refresh)) {
this.scope.$watch('refresh', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.hideOverlay();
return _this.mapType = null;
};
})(this));
}
MapTypeParentModel.prototype.createMapType = function() {
if (this.scope.options.getTile != null) {
this.mapType = this.scope.options;
} else if (this.scope.options.getTileUrl != null) {
this.mapType = new google.maps.ImageMapType(this.scope.options);
} else {
this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!');
return;
}
if (this.attrs.id && this.scope.id) {
this.gMap.mapTypes.set(this.scope.id, this.mapType);
if (!angular.isDefined(this.attrs.show)) {
this.doShow = false;
}
}
return this.mapType.layerId = this.id;
};
MapTypeParentModel.prototype.refreshMapType = function() {
this.hideOverlay();
this.mapType = null;
this.createMapType();
if (this.doShow && (this.gMap != null)) {
return this.showOverlay();
}
};
MapTypeParentModel.prototype.showOverlay = function() {
return this.gMap.overlayMapTypes.push(this.mapType);
};
MapTypeParentModel.prototype.hideOverlay = function() {
var found;
found = false;
return this.gMap.overlayMapTypes.forEach((function(_this) {
return function(mapType, index) {
if (!found && mapType.layerId === _this.id) {
found = true;
_this.gMap.overlayMapTypes.removeAt(index);
}
};
})(this));
};
return MapTypeParentModel;
})(BaseObject);
return MapTypeParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [
"uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) {
var MarkersParentModel, _setPlurals;
_setPlurals = function(val, objToSet) {
objToSet.plurals = new PropMap();
objToSet.scope.plurals = objToSet.plurals;
return objToSet;
};
MarkersParentModel = (function(_super) {
__extends(MarkersParentModel, _super);
MarkersParentModel.include(GmapUtil);
MarkersParentModel.include(ModelsWatcher);
function MarkersParentModel(scope, element, attrs, map) {
this.onDestroy = __bind(this.onDestroy, this);
this.newChildMarker = __bind(this.newChildMarker, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.createAllNew = __bind(this.createAllNew, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.validateScope = __bind(this.validateScope, this);
this.onWatch = __bind(this.onWatch, this);
var self;
MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map);
this["interface"] = IMarker;
self = this;
_setPlurals(new PropMap(), this);
this.scope.pluralsUpdate = {
updateCtr: 0
};
this.$log.info(this);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
this.setIdKey(scope);
this.scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
if (!this.modelsLength()) {
this.modelsRendered = false;
}
this.scope.$watch('models', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) {
if (newValue.length === 0 && oldValue.length === 0) {
return;
}
_this.modelsRendered = true;
return _this.onWatch('models', scope, newValue, oldValue);
}
};
})(this), !this.isTrue(attrs.modelsbyref));
this.watch('doCluster', scope);
this.watch('clusterOptions', scope);
this.watch('clusterEvents', scope);
this.watch('fit', scope);
this.watch('idKey', scope);
this.gManager = void 0;
this.createAllNew(scope);
}
MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {
if (propNameToWatch === "idKey" && newValue !== oldValue) {
this.idKey = newValue;
}
if (this.doRebuildAll || propNameToWatch === 'doCluster') {
return this.rebuildAll(scope);
} else {
return this.pieceMeal(scope);
}
};
MarkersParentModel.prototype.validateScope = function(scope) {
var modelsNotDefined;
modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0;
if (modelsNotDefined) {
this.$log.error(this.constructor.name + ": no valid models attribute found");
}
return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined;
};
/*
Not used internally by this parent
created for consistency for external control in the API
*/
MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
MarkersParentModel.prototype.createAllNew = function(scope) {
var maybeCanceled, self, _ref, _ref1, _ref2;
if (this.gManager != null) {
this.gManager.clear();
delete this.gManager;
}
if (scope.doCluster) {
if (scope.clusterEvents) {
self = this;
if (!this.origClusterEvents) {
this.origClusterEvents = {
click: (_ref = scope.clusterEvents) != null ? _ref.click : void 0,
mouseout: (_ref1 = scope.clusterEvents) != null ? _ref1.mouseout : void 0,
mouseover: (_ref2 = scope.clusterEvents) != null ? _ref2.mouseover : void 0
};
} else {
angular.extend(scope.clusterEvents, this.origClusterEvents);
}
angular.extend(scope.clusterEvents, {
click: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'click');
},
mouseout: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseout');
},
mouseover: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseover');
}
});
}
this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents);
} else {
this.gManager = new MarkerManager(this.map);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.newChildMarker(model, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
_this.modelsRendered = true;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
return _this.scope.pluralsUpdate.updateCtr += 1;
}, _async.chunkSizeFrom(scope.chunk));
};
})(this));
};
MarkersParentModel.prototype.rebuildAll = function(scope) {
var _ref;
if (!scope.doRebuild && scope.doRebuild !== void 0) {
return;
}
if ((_ref = this.scope.plurals) != null ? _ref.length : void 0) {
return this.onDestroy(scope).then((function(_this) {
return function() {
return _this.createAllNew(scope);
};
})(this));
} else {
return this.createAllNew(scope);
}
};
MarkersParentModel.prototype.pieceMeal = function(scope) {
var maybeCanceled, payload;
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if (this.modelsLength() && this.scope.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
if (child.destroy != null) {
child.destroy();
}
_this.scope.plurals.remove(child.id);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
_this.newChildMarker(modelToAdd, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) {
scope.plurals = _this.scope.plurals;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(scope);
}
};
MarkersParentModel.prototype.newChildMarker = function(model, scope) {
var child, childScope, doDrawSelf, keys;
if (model[this.idKey] == null) {
this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
this.$log.info('child', child, 'markers', this.scope.plurals);
childScope = scope.$new(true);
childScope.events = scope.events;
keys = {};
IMarker.scopeKeys.forEach(function(k) {
return keys[k] = scope[k];
});
child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false);
this.scope.plurals.put(model[this.idKey], child);
return child;
};
MarkersParentModel.prototype.onDestroy = function(scope) {
MarkersParentModel.__super__.onDestroy.call(this, scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.scope.plurals.values(), function(model) {
if (model != null) {
return model.destroy(false);
}
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (_this.gManager != null) {
_this.gManager.clear();
}
_this.plurals.removeAll();
if (_this.plurals !== _this.scope.plurals) {
console.error('plurals out of sync for MarkersParentModel');
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
};
MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) {
var pair, _ref;
if (_.isFunction((_ref = this.scope.clusterEvents) != null ? _ref[fnName] : void 0)) {
pair = this.mapClusterToPlurals(cluster);
if (this.origClusterEvents[fnName]) {
return this.origClusterEvents[fnName](pair.cluster, pair.mapped);
}
}
};
MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) {
var mapped;
mapped = cluster.getMarkers().map((function(_this) {
return function(g) {
return _this.scope.plurals.get(g.key).model;
};
})(this));
return {
cluster: cluster,
mapped: mapped
};
};
MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return MarkersParentModel;
})(IMarkerParentModel);
return MarkersParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolygonsParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolygonChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolygon', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolygonChildModel, _async, uiGmapPromise, IPolygon) {
var PolygonsParentModel;
return PolygonsParentModel = (function(_super) {
__extends(PolygonsParentModel, _super);
PolygonsParentModel.include(ModelsWatcher);
function PolygonsParentModel(scope, element, attrs, gMap, defaults) {
var self;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.defaults = defaults;
this.createChild = __bind(this.createChild, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
PolygonsParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPolygon;
self = this;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPolygon.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.createChildScopes();
}
PolygonsParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
PolygonsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
PolygonsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
PolygonsParentModel.prototype.onDestroy = function(scope) {
PolygonsParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var _ref;
return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0;
});
};
})(this));
};
PolygonsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
PolygonsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error('No models to create Polygons from! I Need direct models!');
return;
}
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
PolygonsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
PolygonsParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var child;
child = _this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
child.isEnabled = false;
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
PolygonsParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
if (payload.updates.length) {
$log.warning("polygons updates: " + payload.updates.length + " will be missed");
}
return _async.each(payload.removals, function(child) {
if (child != null) {
child.destroy();
_this.plurals.remove(child.model[_this.idKey]);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
PolygonsParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(IPolygon.scopeKeys, childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolygonChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error("Polygon model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
return PolygonsParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolylinesParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolylineChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolyline', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolylineChildModel, _async, uiGmapPromise, IPolyline) {
var PolylinesParentModel;
return PolylinesParentModel = (function(_super) {
__extends(PolylinesParentModel, _super);
PolylinesParentModel.include(ModelsWatcher);
function PolylinesParentModel(scope, element, attrs, gMap, defaults) {
var self;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.defaults = defaults;
this.setChildScope = __bind(this.setChildScope, this);
this.createChild = __bind(this.createChild, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchOurScope = __bind(this.watchOurScope, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
this.watch = __bind(this.watch, this);
PolylinesParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPolyline;
self = this;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPolyline.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.watchOurScope(scope);
this.createChildScopes();
}
PolylinesParentModel.prototype.watch = function(scope, name, nameKey) {
return scope.$watch(name, (function(_this) {
return function(newValue, oldValue) {
var maybeCanceled;
if (newValue !== oldValue) {
maybeCanceled = null;
_this[nameKey] = _.isFunction(newValue) ? newValue() : newValue;
return _async.promiseLock(_this, uiGmapPromise.promiseTypes.update, "watch " + name + " " + nameKey, (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), function() {
return _async.each(_this.plurals.values(), function(model) {
model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
return maybeCanceled;
}, false);
});
}
};
})(this));
};
PolylinesParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (!(_.isEqual(newValue, oldValue) && (_this.lastNewValue !== newValue || _this.lastOldValue !== oldValue))) {
_this.lastNewValue = newValue;
_this.lastOldValue = oldValue;
if (_this.doINeedToWipe(newValue)) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
PolylinesParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
PolylinesParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
PolylinesParentModel.prototype.onDestroy = function(scope) {
PolylinesParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var _ref;
return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0;
});
};
})(this));
};
PolylinesParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
PolylinesParentModel.prototype.watchOurScope = function(scope) {
return _.each(IPolyline.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
_this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
return _this.watch(scope, name, nameKey);
};
})(this));
};
PolylinesParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error('No models to create Polylines from! I Need direct models!');
return;
}
if (this.gMap != null) {
if (this.scope.models != null) {
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
}
}
};
PolylinesParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
PolylinesParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
}
return maybeCanceled;
}).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
return _async.each(payload.removals, function(id) {
var child;
child = _this.plurals.get(id);
if (child != null) {
child.destroy();
_this.plurals.remove(id);
return maybeCanceled;
}
});
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
});
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
PolylinesParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolylineChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error("Polyline model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
PolylinesParentModel.prototype.setChildScope = function(childScope, model) {
IPolyline.scopeKeys.forEach((function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
return PolylinesParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) {
var RectangleParentModel;
return RectangleParentModel = (function(_super) {
__extends(RectangleParentModel, _super);
RectangleParentModel.include(GmapUtil);
RectangleParentModel.include(EventsHelper);
function RectangleParentModel(scope, element, attrs, map, DEFAULTS) {
var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
bounds = void 0;
dragging = false;
myListeners = [];
listeners = void 0;
fit = (function(_this) {
return function() {
if (_this.isTrue(attrs.fit)) {
return _this.fitMapBounds(_this.map, bounds);
}
};
})(this);
createBounds = (function(_this) {
return function() {
var _ref, _ref1;
if ((scope.bounds != null) && (((_ref = scope.bounds) != null ? _ref.sw : void 0) != null) && (((_ref1 = scope.bounds) != null ? _ref1.ne : void 0) != null) && _this.validateBoundPoints(scope.bounds)) {
bounds = _this.convertBoundPoints(scope.bounds);
return $log.info("new new bounds created: " + (JSON.stringify(bounds)));
} else if ((scope.bounds.getNorthEast != null) && (scope.bounds.getSouthWest != null)) {
return bounds = scope.bounds;
} else {
if (scope.bounds != null) {
return $log.error("Invalid bounds for newValue: " + (JSON.stringify(scope != null ? scope.bounds : void 0)));
}
}
};
})(this);
createBounds();
gObject = new google.maps.Rectangle(this.buildOpts(bounds));
$log.info("gObject (rectangle) created: " + gObject);
settingBoundsFromScope = false;
updateBounds = (function(_this) {
return function() {
var b, ne, sw;
b = gObject.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
if (settingBoundsFromScope) {
return;
}
return scope.$evalAsync(function(s) {
if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) {
s.bounds.ne = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.sw = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) {
return s.bounds = b;
}
});
};
})(this);
init = (function(_this) {
return function() {
fit();
_this.removeEvents(myListeners);
myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() {
return dragging = true;
}));
myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() {
dragging = false;
return updateBounds();
}));
return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() {
if (dragging) {
return;
}
return updateBounds();
}));
};
})(this);
clear = (function(_this) {
return function() {
_this.removeEvents(myListeners);
if (listeners != null) {
_this.removeEvents(listeners);
}
return gObject.setMap(null);
};
})(this);
if (bounds != null) {
init();
}
scope.$watch('bounds', (function(newValue, oldValue) {
var isNew;
if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) {
return;
}
settingBoundsFromScope = true;
if (newValue == null) {
clear();
return;
}
if (bounds == null) {
isNew = true;
} else {
fit();
}
createBounds();
gObject.setBounds(bounds);
settingBoundsFromScope = false;
if (isNew && (bounds != null)) {
return init();
}
}), true);
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
if ((bounds != null) && (newVals != null)) {
return gObject.setOptions(_this.buildOpts(bounds));
}
}
};
})(this);
this.props.push('bounds');
this.watchProps(this.props);
if (attrs.events != null) {
listeners = this.setEvents(gObject, scope, scope);
scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, scope, scope);
}
};
})(this));
}
scope.$on('$destroy', (function(_this) {
return function() {
return clear();
};
})(this));
$log.info(this);
}
return RectangleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) {
var SearchBoxParentModel;
SearchBoxParentModel = (function(_super) {
__extends(SearchBoxParentModel, _super);
SearchBoxParentModel.include(EventsHelper);
function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) {
var controlDiv;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.ctrlPosition = ctrlPosition;
this.template = template;
this.$log = $log != null ? $log : Logger;
this.setVisibility = __bind(this.setVisibility, this);
this.getBounds = __bind(this.getBounds, this);
this.setBounds = __bind(this.setBounds, this);
this.createSearchBox = __bind(this.createSearchBox, this);
this.addToParentDiv = __bind(this.addToParentDiv, this);
this.addAsMapControl = __bind(this.addAsMapControl, this);
this.init = __bind(this.init, this);
if (this.attrs.template == null) {
this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!');
return;
}
if (angular.isUndefined(this.scope.options)) {
this.scope.options = {};
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.visible)) {
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.autocomplete)) {
this.scope.options.autocomplete = false;
}
this.visible = scope.options.visible;
this.autocomplete = scope.options.autocomplete;
controlDiv = angular.element('<div></div>');
controlDiv.append(this.template);
this.input = controlDiv.find('input')[0];
this.init();
}
SearchBoxParentModel.prototype.init = function() {
this.createSearchBox();
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (angular.isObject(newValue)) {
if (newValue.bounds != null) {
_this.setBounds(newValue.bounds);
}
if (newValue.visible != null) {
if (_this.visible !== newValue.visible) {
return _this.setVisibility(newValue.visible);
}
}
}
};
})(this), true);
if (this.attrs.parentdiv != null) {
this.addToParentDiv();
} else {
this.addAsMapControl();
}
if (this.autocomplete) {
this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlace();
};
})(this));
} else {
this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlaces();
};
})(this));
}
this.listeners = this.setEvents(this.gObject, this.scope, this.scope);
this.$log.info(this);
return this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject = null;
};
})(this));
};
SearchBoxParentModel.prototype.addAsMapControl = function() {
return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
};
SearchBoxParentModel.prototype.addToParentDiv = function() {
this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv));
return this.parentDiv.append(this.input);
};
SearchBoxParentModel.prototype.createSearchBox = function() {
if (this.autocomplete) {
return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options);
} else {
return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options);
}
};
SearchBoxParentModel.prototype.setBounds = function(bounds) {
if (angular.isUndefined(bounds.isEmpty)) {
this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.');
} else {
if (bounds.isEmpty() === false) {
if (this.gObject != null) {
return this.gObject.setBounds(bounds);
}
}
}
};
SearchBoxParentModel.prototype.getBounds = function() {
return this.gObject.getBounds();
};
SearchBoxParentModel.prototype.setVisibility = function(val) {
if (this.attrs.parentdiv != null) {
if (val === false) {
this.parentDiv.addClass("ng-hide");
} else {
this.parentDiv.removeClass("ng-hide");
}
} else {
if (val === false) {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear();
} else {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
}
}
return this.visible = val;
};
return SearchBoxParentModel;
})(BaseObject);
return SearchBoxParentModel;
}
]);
}).call(this);
;
/*
WindowsChildModel generator where there are many ChildModels to a parent.
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [
'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) {
var WindowsParentModel;
WindowsParentModel = (function(_super) {
__extends(WindowsParentModel, _super);
WindowsParentModel.include(ModelsWatcher);
function WindowsParentModel(scope, element, attrs, ctrls, gMap, markersScope) {
this.gMap = gMap;
this.markersScope = markersScope;
this.modelKeyComparison = __bind(this.modelKeyComparison, this);
this.interpolateContent = __bind(this.interpolateContent, this);
this.setChildScope = __bind(this.setChildScope, this);
this.createWindow = __bind(this.createWindow, this);
this.setContentKeys = __bind(this.setContentKeys, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchOurScope = __bind(this.watchOurScope, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
this.go = __bind(this.go, this);
WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache);
this["interface"] = IWindow;
this.plurals = new PropMap();
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.linked = new Linked(scope, element, attrs, ctrls);
this.models = void 0;
this.contentKeys = void 0;
this.isIconVisibleOnClick = void 0;
this.firstTime = true;
this.firstWatchModels = true;
this.$log.info(self);
this.parentScope = void 0;
this.go(scope);
}
WindowsParentModel.prototype.go = function(scope) {
this.watchOurScope(scope);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
return this.createChildScopes();
};
WindowsParentModel.prototype.watchModels = function(scope) {
var itemToWatch;
itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models';
return scope.$watch(itemToWatch, (function(_this) {
return function(newValue, oldValue) {
var doScratch;
if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) {
_this.firstWatchModels = false;
if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) {
return _this.rebuildAll(scope, true, true);
} else {
doScratch = _this.plurals.length === 0;
if (_this.existingPieces != null) {
return _.last(_this.existingPieces._content).then(function() {
return _this.createChildScopes(doScratch);
});
} else {
return _this.createChildScopes(doScratch);
}
}
}
};
})(this), true);
};
WindowsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
WindowsParentModel.prototype.onDestroy = function(scope) {
WindowsParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy();
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var _ref;
return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0;
});
};
})(this));
};
WindowsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
_this.firstWatchModels = true;
_this.firstTime = true;
return _this.rebuildAll(scope, false, true);
};
})(this));
};
WindowsParentModel.prototype.watchOurScope = function(scope) {
return _.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
};
})(this));
};
WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
var modelsNotDefined, _ref, _ref1;
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
/*
being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl)
we will assume that all scope values are string expressions either pointing to a key (propName) or using
'self' to point the model as container/object of interest.
This may force redundant information into the model, but this appears to be the most flexible approach.
*/
this.isIconVisibleOnClick = true;
if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) {
this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick;
}
modelsNotDefined = angular.isUndefined(this.linked.scope.models);
if (modelsNotDefined && (this.markersScope === void 0 || (((_ref = this.markersScope) != null ? _ref.plurals : void 0) === void 0 || ((_ref1 = this.markersScope) != null ? _ref1.models : void 0) === void 0))) {
this.$log.error('No models to create windows from! Need direct models or models derived from markers!');
return;
}
if (this.gMap != null) {
if (this.linked.scope.models != null) {
this.watchIdKey(this.linked.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.linked.scope, false);
} else {
return this.pieceMeal(this.linked.scope, false);
}
} else {
this.parentScope = this.markersScope;
this.watchIdKey(this.parentScope);
if (isCreatingFromScratch) {
return this.createAllNew(this.markersScope, true, 'plurals', false);
} else {
return this.pieceMeal(this.markersScope, true, 'plurals', false);
}
}
}
};
WindowsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
this.setContentKeys(scope.models);
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var gMarker, _ref;
gMarker = hasGMarker ? (_ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? _ref.gObject : void 0 : void 0;
if (!maybeCanceled) {
if (!gMarker && _this.markersScope) {
$log.error('Unable to get gMarker from markersScope!');
}
_this.createWindow(model, gMarker, _this.gMap);
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled, payload;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
_this.plurals.remove(child.id);
if (child.destroy != null) {
child.destroy(true);
}
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
var gMarker, _ref;
gMarker = (_ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? _ref.gObject : void 0;
if (!gMarker) {
throw 'Gmarker undefined';
}
_this.createWindow(modelToAdd, gMarker, _this.gMap);
return maybeCanceled;
});
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
$log.debug('pieceMeal: rebuildAll');
return this.rebuildAll(this.scope, true, true);
}
};
WindowsParentModel.prototype.setContentKeys = function(models) {
if (this.modelsLength()) {
return this.contentKeys = Object.keys(models[0]);
}
};
WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) {
var child, childScope, fakeElement, opts, _ref, _ref1;
childScope = this.linked.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
fakeElement = {
html: (function(_this) {
return function() {
return _this.interpolateContent(_this.linked.element.html(), model);
};
})(this)
};
this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {};
opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS);
child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (_ref = this.markersScope) != null ? (_ref1 = _ref.plurals.get(model[this.idKey])) != null ? _ref1.scope : void 0 : void 0, fakeElement, false, true);
if (model[this.idKey] == null) {
this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.');
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
WindowsParentModel.prototype.setChildScope = function(childScope, model) {
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
WindowsParentModel.prototype.interpolateContent = function(content, model) {
var exp, interpModel, key, _i, _len, _ref;
if (this.contentKeys === void 0 || this.contentKeys.length === 0) {
return;
}
exp = $interpolate(content);
interpModel = {};
_ref = this.contentKeys;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
interpModel[key] = model[key];
}
return exp(interpModel);
};
WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) {
var isEqual, scope;
scope = this.scope.coords != null ? this.scope : this.parentScope;
if (scope == null) {
throw 'No scope or parentScope set!';
}
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
return WindowsParentModel;
})(IWindowParentModel);
return WindowsParentModel;
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [
"uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) {
return _.extend(ICircle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new CircleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [
"uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) {
var Control;
return Control = (function(_super) {
__extends(Control, _super);
function Control() {
this.link = __bind(this.link, this);
Control.__super__.constructor.call(this);
}
Control.prototype.link = function(scope, element, attrs, ctrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
var index, position;
if (angular.isUndefined(scope.template)) {
_this.$log.error('mapControl: could not find a valid template property');
return;
}
index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0;
position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER';
if (!maps.ControlPosition[position]) {
_this.$log.error('mapControl: invalid position property');
return;
}
return IControl.mapPromise(scope, ctrl).then(function(map) {
var control, controlDiv;
control = void 0;
controlDiv = angular.element('<div></div>');
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
var templateCtrl, templateScope;
templateScope = scope.$new();
controlDiv.append(template);
if (angular.isDefined(scope.controller)) {
templateCtrl = $controller(scope.controller, {
$scope: templateScope
});
controlDiv.children().data('$ngControllerController', templateCtrl);
}
control = $compile(controlDiv.children())(templateScope);
if (index) {
return control[0].index = index;
}
}).error(function(error) {
return _this.$log.error('mapControl: template could not be found');
}).then(function() {
return map.controls[google.maps.ControlPosition[position]].push(control[0]);
});
});
};
})(this));
};
return Control;
})(IControl);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) {
return {
restrict: 'EMA',
transclude: true,
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>',
require: '^' + 'uiGmapGoogleMap',
scope: {
keyboardkey: '=',
options: '=',
spec: '='
},
controller: [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'uiGmapDragZoom';
return _.extend(this, CtrlHandle.handle($scope, $element));
}
],
link: function(scope, element, attrs, ctrl) {
return CtrlHandle.mapPromise(scope, ctrl).then(function(map) {
var enableKeyDragZoom, setKeyAction, setOptionsAction;
enableKeyDragZoom = function(opts) {
map.enableKeyDragZoom(opts);
if (scope.spec) {
return scope.spec.enableKeyDragZoom(opts);
}
};
setKeyAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom({
key: newVal
});
} else {
return enableKeyDragZoom();
}
});
setOptionsAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom(newVal);
}
});
scope.$watch('keyboardkey', setKeyAction.sic);
setKeyAction.sic(scope.keyboardkey);
scope.$watch('options', setOptionsAction.sic);
return setOptionsAction.sic(scope.options);
});
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [
"uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) {
return _.extend(IDrawingManager, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then(function(map) {
return new DrawingManagerParentModel(scope, element, attrs, map);
});
}
});
}
]);
}).call(this);
;
/*
- Link up Polygons to be sent back to a controller
- inject the draw function into a controllers scope so that controller can call the directive to draw on demand
- draw function creates the DrawFreeHandChildModel which manages itself
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [
'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) {
var FreeDrawPolygons;
return FreeDrawPolygons = (function(_super) {
__extends(FreeDrawPolygons, _super);
function FreeDrawPolygons() {
this.link = __bind(this.link, this);
return FreeDrawPolygons.__super__.constructor.apply(this, arguments);
}
FreeDrawPolygons.include(CtrlHandle);
FreeDrawPolygons.prototype.restrict = 'EMA';
FreeDrawPolygons.prototype.replace = true;
FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap';
FreeDrawPolygons.prototype.scope = {
polygons: '=',
draw: '=',
revertmapoptions: '='
};
FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) {
return this.mapPromise(scope, ctrl).then((function(_this) {
return function(map) {
var freeHand, listener;
if (!scope.polygons) {
return $log.error('No polygons to bind to!');
}
if (!_.isArray(scope.polygons)) {
return $log.error('Free Draw Polygons must be of type Array!');
}
freeHand = new DrawFreeHandChildModel(map, scope.revertmapoptions);
listener = void 0;
return scope.draw = function() {
if (typeof listener === "function") {
listener();
}
return freeHand.engage(scope.polygons).then(function() {
var firstTime;
firstTime = true;
return listener = scope.$watchCollection('polygons', function(newValue, oldValue) {
var removals;
if (firstTime || newValue === oldValue) {
firstTime = false;
return;
}
removals = uiGmapLodash.differenceObjects(oldValue, newValue);
return removals.forEach(function(p) {
return p.setMap(null);
});
});
});
};
};
})(this));
};
return FreeDrawPolygons;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [
function() {
var DEFAULTS;
DEFAULTS = {};
return {
restrict: "EA",
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
center: "=center",
radius: "=radius",
stroke: "=stroke",
fill: "=fill",
clickable: "=",
draggable: "=",
editable: "=",
geodesic: "=",
icons: "=icons",
visible: "=",
events: "="
}
};
}
]);
}).call(this);
;
/*
- interface for all controls to derive from
- to enforce a minimum set of requirements
- attributes
- template
- position
- controller
- index
*/
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [
"uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) {
var IControl;
return IControl = (function(_super) {
__extends(IControl, _super);
IControl.extend(CtrlHandle);
function IControl() {
this.restrict = 'EA';
this.replace = true;
this.require = '^' + 'uiGmapGoogleMap';
this.scope = {
template: '@template',
position: '@position',
controller: '@controller',
index: '@index'
};
this.$log = Logger;
}
IControl.prototype.link = function(scope, element, attrs, ctrl) {
throw new Exception("Not implemented!!");
};
return IControl;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [
function() {
return {
restrict: 'EA',
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
"static": '@',
control: '=',
options: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [
'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) {
var IMarker;
return IMarker = (function(_super) {
__extends(IMarker, _super);
IMarker.scope = {
coords: '=coords',
icon: '=icon',
click: '&click',
options: '=options',
events: '=events',
fit: '=fit',
idKey: '=idkey',
control: '=control'
};
IMarker.scopeKeys = _.keys(IMarker.scope);
IMarker.keys = IMarker.scopeKeys;
IMarker.extend(CtrlHandle);
function IMarker() {
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.replace = true;
this.scope = _.extend(this.scope || {}, IMarker.scope);
}
return IMarker;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolygon;
return IPolygon = (function(_super) {
__extends(IPolygon, _super);
IPolygon.scope = {
path: '=path',
stroke: '=stroke',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
fill: '=',
icons: '=icons',
visible: '=',
"static": '=',
events: '=',
zIndex: '=zindex',
fit: '=',
control: '=control'
};
IPolygon.scopeKeys = _.keys(IPolygon.scope);
IPolygon.include(GmapUtil);
IPolygon.extend(CtrlHandle);
function IPolygon() {}
IPolygon.prototype.restrict = 'EMA';
IPolygon.prototype.replace = true;
IPolygon.prototype.require = '^' + 'uiGmapGoogleMap';
IPolygon.prototype.scope = IPolygon.scope;
IPolygon.prototype.DEFAULTS = {};
IPolygon.prototype.$log = Logger;
return IPolygon;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolyline;
return IPolyline = (function(_super) {
__extends(IPolyline, _super);
IPolyline.scope = {
path: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
icons: '=',
visible: '=',
"static": '=',
fit: '=',
events: '='
};
IPolyline.scopeKeys = _.keys(IPolyline.scope);
IPolyline.include(GmapUtil);
IPolyline.extend(CtrlHandle);
function IPolyline() {}
IPolyline.prototype.restrict = 'EMA';
IPolyline.prototype.replace = true;
IPolyline.prototype.require = '^' + 'uiGmapGoogleMap';
IPolyline.prototype.scope = IPolyline.scope;
IPolyline.prototype.DEFAULTS = {};
IPolyline.prototype.$log = Logger;
return IPolyline;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [
function() {
'use strict';
var DEFAULTS;
DEFAULTS = {};
return {
restrict: 'EMA',
require: '^' + 'uiGmapGoogleMap',
replace: true,
scope: {
bounds: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
fill: '=',
visible: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [
'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) {
var IWindow;
return IWindow = (function(_super) {
__extends(IWindow, _super);
IWindow.scope = {
coords: '=coords',
template: '=template',
templateUrl: '=templateurl',
templateParameter: '=templateparameter',
isIconVisibleOnClick: '=isiconvisibleonclick',
closeClick: '&closeclick',
options: '=options',
control: '=control',
show: '=show'
};
IWindow.scopeKeys = _.keys(IWindow.scope);
IWindow.include(ChildEvents);
IWindow.extend(CtrlHandle);
function IWindow() {
this.restrict = 'EMA';
this.template = void 0;
this.transclude = true;
this.priority = -100;
this.require = '^' + 'uiGmapGoogleMap';
this.replace = true;
this.scope = _.extend(this.scope || {}, IWindow.scope);
}
return IWindow;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [
'$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) {
'use strict';
var DEFAULTS, Map, initializeItems;
DEFAULTS = void 0;
initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer];
return Map = (function(_super) {
__extends(Map, _super);
Map.include(GmapUtil);
function Map() {
this.link = __bind(this.link, this);
var ctrlFn, self;
ctrlFn = function($scope) {
var ctrlObj, retCtrl;
retCtrl = void 0;
$scope.$on('$destroy', function() {
return IsReady.reset();
});
ctrlObj = CtrlHandle.handle($scope);
$scope.ctrlType = 'Map';
$scope.deferred.promise.then(function() {
return initializeItems.forEach(function(i) {
return i.init();
});
});
ctrlObj.getMap = function() {
return $scope.map;
};
retCtrl = _.extend(this, ctrlObj);
return retCtrl;
};
this.controller = ['$scope', ctrlFn];
self = this;
}
Map.prototype.restrict = 'EMA';
Map.prototype.transclude = true;
Map.prototype.replace = false;
Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>';
Map.prototype.scope = {
center: '=',
zoom: '=',
dragging: '=',
control: '=',
options: '=',
events: '=',
eventOpts: '=',
styles: '=',
bounds: '=',
update: '='
};
Map.prototype.link = function(scope, element, attrs) {
var listeners, unbindCenterWatch;
listeners = [];
scope.$on('$destroy', function() {
return EventsHelper.removeEvents(listeners);
});
scope.idleAndZoomChanged = false;
if (scope.center == null) {
unbindCenterWatch = scope.$watch('center', (function(_this) {
return function() {
if (!scope.center) {
return;
}
unbindCenterWatch();
return _this.link(scope, element, attrs);
};
})(this));
return;
}
return GoogleMapApi.then((function(_this) {
return function(maps) {
var customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise, _gMap, _ref;
DEFAULTS = {
mapTypeId: maps.MapTypeId.ROADMAP
};
spawned = IsReady.spawn();
resolveSpawned = function() {
return spawned.deferred.resolve({
instance: spawned.instance,
map: _gMap
});
};
if (!_this.validateCoords(scope.center)) {
$log.error('angular-google-maps: could not find a valid center property');
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error('angular-google-maps: map zoom property not set');
return;
}
el = angular.element(element);
el.addClass('angular-google-map');
opts = {
options: {}
};
if (attrs.options) {
opts.options = scope.options;
}
if (attrs.styles) {
opts.styles = scope.styles;
}
if (attrs.type) {
type = attrs.type.toUpperCase();
if (google.maps.MapTypeId.hasOwnProperty(type)) {
opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()];
} else {
$log.error("angular-google-maps: invalid map type '" + attrs.type + "'");
}
}
mapOptions = angular.extend({}, DEFAULTS, opts, {
center: _this.getCoords(scope.center),
zoom: scope.zoom,
bounds: scope.bounds
});
_gMap = new google.maps.Map(el.find('div')[1], mapOptions);
_gMap['uiGmap_id'] = uuid.generate();
dragging = false;
listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() {
scope.deferred.resolve(_gMap);
return resolveSpawned();
}));
disabledEvents = attrs.events && (((_ref = scope.events) != null ? _ref.blacklist : void 0) != null) ? scope.events.blacklist : [];
if (_.isString(disabledEvents)) {
disabledEvents = [disabledEvents];
}
maybeHookToEvent = function(eventName, fn, prefn) {
if (!_.contains(disabledEvents, eventName)) {
if (prefn) {
prefn();
}
return listeners.push(google.maps.event.addListener(_gMap, eventName, function() {
var _ref1;
if (!((_ref1 = scope.update) != null ? _ref1.lazy : void 0)) {
return fn();
}
}));
}
};
if (!_.contains(disabledEvents, 'all')) {
maybeHookToEvent('dragstart', function() {
dragging = true;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
maybeHookToEvent('dragend', function() {
dragging = false;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
updateCenter = function(c, s) {
if (c == null) {
c = _gMap.center;
}
if (s == null) {
s = scope;
}
if (_.contains(disabledEvents, 'center')) {
return;
}
if (angular.isDefined(s.center.type)) {
if (s.center.coordinates[1] !== c.lat()) {
s.center.coordinates[1] = c.lat();
}
if (s.center.coordinates[0] !== c.lng()) {
return s.center.coordinates[0] = c.lng();
}
} else {
if (s.center.latitude !== c.lat()) {
s.center.latitude = c.lat();
}
if (s.center.longitude !== c.lng()) {
return s.center.longitude = c.lng();
}
}
};
settingFromDirective = false;
maybeHookToEvent('idle', function() {
var b, ne, sw;
b = _gMap.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
settingFromDirective = true;
return scope.$evalAsync(function(s) {
updateCenter();
if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) {
s.bounds.northeast = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.southwest = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if (!_.contains(disabledEvents, 'zoom')) {
s.zoom = _gMap.zoom;
scope.idleAndZoomChanged = !scope.idleAndZoomChanged;
}
return settingFromDirective = false;
});
});
}
if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) {
getEventHandler = function(eventName) {
return function() {
return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]);
};
};
customListeners = [];
for (eventName in scope.events) {
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) {
customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName)));
}
}
listeners.concat(customListeners);
}
_gMap.getOptions = function() {
return mapOptions;
};
scope.map = _gMap;
if ((attrs.control != null) && (scope.control != null)) {
scope.control.refresh = function(maybeCoords) {
var coords, _ref1, _ref2;
if (_gMap == null) {
return;
}
if (((typeof google !== "undefined" && google !== null ? (_ref1 = google.maps) != null ? (_ref2 = _ref1.event) != null ? _ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) {
google.maps.event.trigger(_gMap, 'resize');
}
if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) {
coords = _this.getCoords(maybeCoords);
if (_this.isTrue(attrs.pan)) {
return _gMap.panTo(coords);
} else {
return _gMap.setCenter(coords);
}
}
};
scope.control.getGMap = function() {
return _gMap;
};
scope.control.getMapOptions = function() {
return mapOptions;
};
scope.control.getCustomEventListeners = function() {
return customListeners;
};
scope.control.removeEvents = function(yourListeners) {
return EventsHelper.removeEvents(yourListeners);
};
}
scope.$watch('center', function(newValue, oldValue) {
var coords, settingCenterFromScope;
if (newValue === oldValue || settingFromDirective) {
return;
}
coords = _this.getCoords(scope.center);
if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) {
return;
}
settingCenterFromScope = true;
if (!dragging) {
if (!_this.validateCoords(newValue)) {
$log.error("Invalid center for newValue: " + (JSON.stringify(newValue)));
}
if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) {
_gMap.panTo(coords);
} else {
_gMap.setCenter(coords);
}
}
return settingCenterFromScope = false;
}, true);
zoomPromise = null;
scope.$watch('zoom', function(newValue, oldValue) {
var settingZoomFromScope, _ref1, _ref2;
if (newValue == null) {
return;
}
if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) {
return;
}
settingZoomFromScope = true;
if (zoomPromise != null) {
$timeout.cancel(zoomPromise);
}
return zoomPromise = $timeout(function() {
_gMap.setZoom(newValue);
return settingZoomFromScope = false;
}, ((_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.zoomMs : void 0 : void 0) + 20, false);
});
scope.$watch('bounds', function(newValue, oldValue) {
var bounds, ne, sw, _ref1, _ref2, _ref3, _ref4;
if (newValue === oldValue) {
return;
}
if (((newValue != null ? (_ref1 = newValue.northeast) != null ? _ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref2 = newValue.northeast) != null ? _ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (_ref3 = newValue.southwest) != null ? _ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref4 = newValue.southwest) != null ? _ref4.longitude : void 0 : void 0) == null)) {
$log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue)));
return;
}
ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude);
sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude);
bounds = new google.maps.LatLngBounds(sw, ne);
return _gMap.fitBounds(bounds);
});
return ['options', 'styles'].forEach(function(toWatch) {
return scope.$watch(toWatch, function(newValue, oldValue) {
var watchItem;
watchItem = this.exp;
if (_.isEqual(newValue, oldValue)) {
return;
}
if (watchItem === 'options') {
opts.options = newValue;
} else {
opts.options[watchItem] = newValue;
}
if (_gMap != null) {
return _gMap.setOptions(opts);
}
}, true);
});
};
})(this));
};
return Map;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [
"uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) {
var Marker;
return Marker = (function(_super) {
__extends(Marker, _super);
function Marker() {
this.link = __bind(this.link, this);
Marker.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-marker" ng-transclude></span>';
$log.info(this);
}
Marker.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Marker';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Marker.prototype.link = function(scope, element, attrs, ctrl) {
var mapPromise;
mapPromise = IMarker.mapPromise(scope, ctrl);
mapPromise.then((function(_this) {
return function(map) {
var doClick, doDrawSelf, gManager, keys, m, trackModel;
gManager = new MarkerManager(map);
keys = _.object(IMarker.keys, IMarker.keys);
m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false);
m.deferred.promise.then(function(gMarker) {
return scope.deferred.resolve(gMarker);
});
if (scope.control != null) {
return scope.control.getGMarkers = gManager.getGMarkers;
}
};
})(this));
return scope.$on('$destroy', (function(_this) {
return function() {
var gManager;
if (typeof gManager !== "undefined" && gManager !== null) {
gManager.clear();
}
return gManager = null;
};
})(this));
};
return Marker;
})(IMarker);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [
"uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) {
var Markers;
return Markers = (function(_super) {
__extends(Markers, _super);
function Markers() {
Markers.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-markers" ng-transclude></span>';
Plural.extend(this, {
doCluster: '=docluster',
clusterOptions: '=clusteroptions',
clusterEvents: '=clusterevents',
modelsByRef: '=modelsbyref'
});
$log.info(this);
}
Markers.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Markers';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Markers.prototype.link = function(scope, element, attrs, ctrl) {
var parentModel, ready;
parentModel = void 0;
ready = function() {
return scope.deferred.resolve();
};
return IMarker.mapPromise(scope, ctrl).then(function(map) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.$watch('idleAndZoomChanged', function() {
return _.defer(parentModel.gManager.draw);
});
parentModel = new MarkersParentModel(scope, element, attrs, map);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGMarkers = function() {
var _ref;
return (_ref = parentModel.gManager) != null ? _ref.getGMarkers() : void 0;
};
scope.control.getChildMarkers = function() {
return parentModel.plurals;
};
}
return _.last(parentModel.existingPieces._content).then(function() {
return ready();
});
});
};
return Markers;
})(IMarker);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [
function() {
var _initControl;
_initControl = function(scope, parent) {
if (scope.control == null) {
return;
}
scope.control.updateModels = function(models) {
scope.models = models;
return parent.createChildScopes(false);
};
scope.control.newModels = function(models) {
scope.models = models;
return parent.rebuildAll(scope, true, true);
};
scope.control.clean = function() {
return parent.rebuildAll(scope, false, true);
};
scope.control.getPlurals = function() {
return parent.plurals;
};
scope.control.getManager = function() {
return parent.gManager;
};
scope.control.hasManager = function() {
return (parent.gManager != null) === true;
};
return scope.control.managerDraw = function() {
var _ref;
if (scope.control.hasManager()) {
return (_ref = scope.control.getManager()) != null ? _ref.draw() : void 0;
}
};
};
return {
extend: function(obj, obj2) {
return _.extend(obj.scope || {}, obj2 || {}, {
idKey: '=idkey',
doRebuildAll: '=dorebuildall',
models: '=models',
chunk: '=chunk',
cleanchunk: '=cleanchunk',
control: '=control'
});
},
link: function(scope, parent) {
return _initControl(scope, parent);
}
};
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) {
var Polygon;
return Polygon = (function(_super) {
__extends(Polygon, _super);
function Polygon() {
this.link = __bind(this.link, this);
return Polygon.__super__.constructor.apply(this, arguments);
}
Polygon.prototype.link = function(scope, element, attrs, mapCtrl) {
var children, promise;
children = [];
promise = IPolygon.mapPromise(scope, mapCtrl);
if (scope.control != null) {
scope.control.getInstance = this;
scope.control.polygons = children;
scope.control.promise = promise;
}
return promise.then((function(_this) {
return function(map) {
return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygon;
})(IPolygon);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) {
var Polygons;
return Polygons = (function(_super) {
__extends(Polygons, _super);
function Polygons() {
this.link = __bind(this.link, this);
Polygons.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polygons.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polygons: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polygons: no models found to create from');
}
return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygons;
})(Interface);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) {
var Polyline;
return Polyline = (function(_super) {
__extends(Polyline, _super);
function Polyline() {
this.link = __bind(this.link, this);
return Polyline.__super__.constructor.apply(this, arguments);
}
Polyline.prototype.link = function(scope, element, attrs, mapCtrl) {
return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) {
_this.$log.warn('polyline: no valid path attribute found');
}
return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS);
};
})(this));
};
return Polyline;
})(IPolyline);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) {
var Polylines;
return Polylines = (function(_super) {
__extends(Polylines, _super);
function Polylines() {
this.link = __bind(this.link, this);
Polylines.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polylines.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polylines: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polylines: no models found to create from');
}
return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polylines;
})(IPolyline);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) {
return _.extend(IRectangle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new RectangleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [
'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) {
var Window;
return Window = (function(_super) {
__extends(Window, _super);
Window.include(GmapUtil);
function Window() {
this.link = __bind(this.link, this);
Window.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker'];
this.template = '<span class="angular-google-maps-window" ng-transclude></span>';
$log.debug(this);
this.childWindows = [];
}
Window.prototype.link = function(scope, element, attrs, ctrls) {
var markerCtrl, markerScope;
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
this.mapPromise = IWindow.mapPromise(scope, ctrls[0]);
return this.mapPromise.then((function(_this) {
return function(mapCtrl) {
var isIconVisibleOnClick;
isIconVisibleOnClick = true;
if (angular.isDefined(attrs.isiconvisibleonclick)) {
isIconVisibleOnClick = scope.isIconVisibleOnClick;
}
if (!markerCtrl) {
_this.init(scope, element, isIconVisibleOnClick, mapCtrl);
return;
}
return markerScope.deferred.promise.then(function(gMarker) {
return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope);
});
};
})(this));
};
Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) {
var childWindow, defaults, gMarker, hasScopeCoords, opts;
defaults = scope.options != null ? scope.options : {};
hasScopeCoords = (scope != null) && this.validateCoords(scope.coords);
if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) {
gMarker = markerScope.getGMarker();
}
opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults;
if (mapCtrl != null) {
childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element);
this.childWindows.push(childWindow);
scope.$on('$destroy', (function(_this) {
return function() {
_this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) {
return child1.scope.$id === child2.scope.$id;
});
return _this.childWindows.length = 0;
};
})(this));
}
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.gObject;
});
};
})(this);
scope.control.getChildWindows = (function(_this) {
return function() {
return _this.childWindows;
};
})(this);
scope.control.getPlurals = scope.control.getChildWindows;
scope.control.showWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.showWindow();
});
};
})(this);
scope.control.hideWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.hideWindow();
});
};
})(this);
}
if ((this.onChildCreation != null) && (childWindow != null)) {
return this.onChildCreation(childWindow);
}
};
return Window;
})(IWindow);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [
'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) {
/*
Windows directive where many windows map to the models property
*/
var Windows;
return Windows = (function(_super) {
__extends(Windows, _super);
function Windows() {
this.init = __bind(this.init, this);
this.link = __bind(this.link, this);
Windows.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers'];
this.template = '<span class="angular-google-maps-windows" ng-transclude></span>';
Plural.extend(this);
$log.debug(this);
}
Windows.prototype.link = function(scope, element, attrs, ctrls) {
var mapScope, markerCtrl, markerScope;
mapScope = ctrls[0].getScope();
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
return mapScope.deferred.promise.then((function(_this) {
return function(map) {
var promise, _ref;
promise = (markerScope != null ? (_ref = markerScope.deferred) != null ? _ref.promise : void 0 : void 0) || uiGmapPromise.resolve();
return promise.then(function() {
var pieces, _ref1;
pieces = (_ref1 = _this.parentModel) != null ? _ref1.existingPieces : void 0;
if (pieces) {
return pieces.then(function() {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
});
} else {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
}
});
};
})(this));
};
Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) {
var parentModel;
parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return parentModel.plurals.map(function(child) {
return child.gObject;
});
};
})(this);
return scope.control.getChildWindows = (function(_this) {
return function() {
return parentModel.plurals;
};
})(this);
}
};
return Windows;
})(IWindow);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Nick Baugh - https://github.com/niftylettuce
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [
"uiGmapMap", function(Map) {
return new Map();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [
'$timeout', 'uiGmapMarker', function($timeout, Marker) {
return new Marker($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [
'$timeout', 'uiGmapMarkers', function($timeout, Markers) {
return new Markers($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [
'uiGmapPolygon', function(Polygon) {
return new Polygon();
}
]);
}).call(this);
;
/*
@authors
Julian Popescu - https://github.com/jpopesculian
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [
"uiGmapCircle", function(Circle) {
return Circle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [
"uiGmapPolyline", function(Polyline) {
return new Polyline();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [
'uiGmapPolylines', function(Polylines) {
return new Polylines();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Chentsu Lin - https://github.com/ChenTsuLin
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [
"uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) {
return Rectangle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [
"$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) {
return new Window($timeout, $compile, $http, $templateCache);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [
"$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) {
return new Windows($timeout, $compile, $http, $templateCache, $interpolate);
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [
'$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) {
var Layer;
Layer = (function() {
function Layer() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>';
this.replace = true;
this.scope = {
show: '=show',
type: '=type',
namespace: '=namespace',
options: '=options',
onCreated: '&oncreated'
};
}
Layer.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (scope.onCreated != null) {
return new LayerParentModel(scope, element, attrs, map, scope.onCreated);
} else {
return new LayerParentModel(scope, element, attrs, map);
}
};
})(this));
};
return Layer;
})();
return new Layer();
}
]);
}).call(this);
;
/*
@authors
Adam Kreitals, [email protected]
*/
/*
mapControl directive
This directive is used to create a custom control element on an existing map.
This directive creates a new scope.
{attribute template required} string url of the template to be used for the control
{attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER
{attribute controller optional} string controller to be applied to the template
{attribute index optional} number index for controlling the order of similarly positioned mapControl elements
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [
"uiGmapControl", function(Control) {
return new Control();
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [
'uiGmapDragZoom', function(DragZoom) {
return DragZoom;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [
"uiGmapDrawingManager", function(DrawingManager) {
return DrawingManager;
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
* Brunt of the work is in DrawFreeHandChildModel
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [
'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) {
return new FreeDrawPolygons();
}
]);
}).call(this);
;
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [
"$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) {
var MapType;
MapType = (function() {
function MapType() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = "EMA";
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>';
this.replace = true;
this.scope = {
show: "=show",
options: '=options',
refresh: '=refresh',
id: '@'
};
}
MapType.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new MapTypeParentModel(scope, element, attrs, map);
};
})(this));
};
return MapType;
})();
return new MapType();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [
'uiGmapPolygons', function(Polygons) {
return new Polygons();
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
*/
/*
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [
'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) {
var SearchBox;
SearchBox = (function() {
SearchBox.prototype.require = 'ngModel';
function SearchBox() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>';
this.replace = true;
this.scope = {
template: '=template',
events: '=events',
position: '=?position',
options: '=?options',
parentdiv: '=?parentdiv',
ngModel: "=?"
};
}
SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
if (angular.isUndefined(scope.events)) {
_this.$log.error('searchBox: the events property is required');
return;
}
return mapCtrl.getScope().deferred.promise.then(function(map) {
var ctrlPosition;
ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT';
if (!maps.ControlPosition[ctrlPosition]) {
_this.$log.error('searchBox: invalid position property');
return;
}
return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope));
});
});
};
})(this));
};
return SearchBox;
})();
return new SearchBox();
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [
'$animate', 'uiGmapLogger', function($animate, $log) {
return {
scope: {
'uiGmapShow': '=',
'uiGmapAfterShow': '&',
'uiGmapAfterHide': '&'
},
link: function(scope, element) {
var angular_post_1_3_handle, angular_pre_1_3_handle, handle;
angular_post_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide').then(function() {
return cb();
});
};
angular_pre_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide', cb);
};
handle = function(animateAction, cb) {
if (angular.version.major > 1) {
return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\"");
}
if (angular.version.major === 1 && angular.version.minor < 3) {
return angular_pre_1_3_handle(animateAction, cb);
}
return angular_post_1_3_handle(animateAction, cb);
};
return scope.$watch('uiGmapShow', function(show) {
if (show) {
handle('removeClass', scope.uiGmapAfterShow);
}
if (!show) {
return handle('addClass', scope.uiGmapAfterHide);
}
});
}
};
}
]);
}).call(this);
;angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapuuid', function() {
//BEGIN REPLACE
/*
Version: core-1.0
The MIT License: Copyright (c) 2012 LiosK.
*/
function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c};
//END REPLACE
return UUID;
});
;// wrap the utility libraries needed in ./lib
// http://google-maps-utility-library-v3.googlecode.com/svn/
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapGoogleMapsUtilV3', function () {
return {
init: _.once(function () {
//BEGIN REPLACE
/**
* @name InfoBox
* @version 1.1.13 [March 19, 2014]
* @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)
* @copyright Copyright 2010 Gary Little [gary at luxcentral.com]
* @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class.
* <p>
* An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several
* additional properties for advanced styling. An InfoBox can also be used as a map label.
* <p>
* An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint browser:true */
/*global google */
/**
* @name InfoBoxOptions
* @class This class represents the optional parameter passed to the {@link InfoBox} constructor.
* @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).
* @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>.
* @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.
* @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox
* (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>)
* to the map pixel corresponding to <tt>position</tt>.
* @property {LatLng} position The geographic location at which to display the InfoBox.
* @property {number} zIndex The CSS z-index style value for the InfoBox.
* Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property.
* @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container.
* @property {Object} [boxStyle] An object literal whose properties define specific CSS
* style values to be applied to the InfoBox. Style values defined here override those that may
* be defined in the <code>boxClass</code> style sheet. If this property is changed after the
* InfoBox has been created, all previously set styles (except those defined in the style sheet)
* are removed from the InfoBox before the new style values are applied.
* @property {string} closeBoxMargin The CSS margin style value for the close box.
* The default is "2px" (a 2-pixel margin on all sides).
* @property {string} closeBoxURL The URL of the image representing the close box.
* Note: The default is the URL for Google's standard close box.
* Set this property to "" if no close box is required.
* @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the
* map edge after an auto-pan.
* @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>.
* [Deprecated in favor of the <tt>visible</tt> property.]
* @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>.
* @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code>
* location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned).
* @property {string} pane The pane where the InfoBox is to appear (default is "floatPane").
* Set the pane to "mapPane" if the InfoBox is being used as a map label.
* Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object.
* @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,
* mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox
* (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set
* this property to <tt>true</tt> if the InfoBox is being used as a map label.
*/
/**
* Creates an InfoBox with the options specified in {@link InfoBoxOptions}.
* Call <tt>InfoBox.open</tt> to add the box to the map.
* @constructor
* @param {InfoBoxOptions} [opt_opts]
*/
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
//
this.content_ = opt_opts.content || "";
this.disableAutoPan_ = opt_opts.disableAutoPan || false;
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
//
this.boxClass_ = opt_opts.boxClass || "infoBox";
this.boxStyle_ = opt_opts.boxStyle || {};
this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
if (opt_opts.closeBoxURL === "") {
this.closeBoxURL_ = "";
}
this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
if (typeof opt_opts.visible === "undefined") {
if (typeof opt_opts.isHidden === "undefined") {
opt_opts.visible = true;
} else {
opt_opts.visible = !opt_opts.isHidden;
}
}
this.isHidden_ = !opt_opts.visible;
this.alignBottom_ = opt_opts.alignBottom || false;
this.pane_ = opt_opts.pane || "floatPane";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.moveListener_ = null;
this.contextListener_ = null;
this.eventListeners_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();
/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function () {
var i;
var events;
var bw;
var me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
//
var cancelHandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
// This handler ignores the current event in the InfoBox and conditionally prevents
// the event from being passed on to the map. It is used for the contextmenu event.
//
var ignoreHandler = function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
if (!me.enableEventPropagation_) {
cancelHandler(e);
}
};
if (!this.div_) {
this.div_ = document.createElement("div");
this.setBoxStyle_();
if (typeof this.content_.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(this.content_);
}
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) {
this.fixedWidthSet_ = true;
} else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.div_.style.overflow = "auto";
this.fixedWidthSet_ = true;
} else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
this.panBox_(this.disableAutoPan_);
if (!this.enableEventPropagation_) {
this.eventListeners_ = [];
// Cancel event propagation.
//
// Note: mousemove not included (to resolve Issue 152)
events = ["mousedown", "mouseover", "mouseout", "mouseup",
"click", "dblclick", "touchstart", "touchend", "touchmove"];
for (i = 0; i < events.length; i++) {
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));
}
// Workaround for Google bug that causes the cursor to change to a pointer
// when the mouse moves over a marker underneath InfoBox.
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) {
this.style.cursor = "default";
}));
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
/**
* This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
* @name InfoBox#domready
* @event
*/
google.maps.event.trigger(this, "domready");
}
};
/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function () {
var img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right"; // Do this because Opera chokes on style='float: right;'
img += " style='";
img += " position: relative;"; // Required by MSIE
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
/**
* Adds the click handler to the InfoBox close box.
* @private
*/
InfoBox.prototype.addClickHandler_ = function () {
var closeBox;
if (this.closeBoxURL_ !== "") {
closeBox = this.div_.firstChild;
this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_());
} else {
this.closeListener_ = null;
}
};
/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function () {
var me = this;
return function (e) {
// 1.0.3 fix: Always prevent propagation of a close box click to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
/**
* This event is fired when the InfoBox's close box is clicked.
* @name InfoBox#closeclick
* @event
*/
google.maps.event.trigger(me, "closeclick");
me.close();
};
};
/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function (disablePan) {
var map;
var bounds;
var xOffset = 0, yOffset = 0;
if (!disablePan) {
map = this.getMap();
if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama
if (!map.getBounds().contains(this.position_)) {
// Marker not in visible area of map, so set center
// of map to the marker position first.
map.setCenter(this.position_);
}
bounds = map.getBounds();
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var iwWidth = this.div_.offsetWidth;
var iwHeight = this.div_.offsetHeight;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);
if (pixPosition.x < (-iwOffsetX + padX)) {
xOffset = pixPosition.x + iwOffsetX - padX;
} else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
}
if (this.alignBottom_) {
if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
} else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
}
} else {
if (pixPosition.y < (-iwOffsetY + padY)) {
yOffset = pixPosition.y + iwOffsetY - padY;
} else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
}
}
if (!(xOffset === 0 && yOffset === 0)) {
// Move the map to the shifted center.
//
var c = map.getCenter();
map.panBy(xOffset, yOffset);
}
}
}
};
/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function () {
var i, boxStyle;
if (this.div_) {
// Apply style values from the style sheet defined in the boxClass parameter:
this.div_.className = this.boxClass_;
// Clear existing inline style values:
this.div_.style.cssText = "";
// Apply style values defined in the boxStyle parameter:
boxStyle = this.boxStyle_;
for (i in boxStyle) {
if (boxStyle.hasOwnProperty(i)) {
this.div_.style[i] = boxStyle[i];
}
}
// Fix for iOS disappearing InfoBox problem.
// See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad
this.div_.style.WebkitTransform = "translateZ(0)";
// Fix up opacity style for benefit of MSIE:
//
if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {
// See http://www.quirksmode.org/css/opacity.html
this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\"";
this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
}
// Apply required styles:
//
this.div_.style.position = "absolute";
this.div_.style.visibility = 'hidden';
if (this.zIndex_ !== null) {
this.div_.style.zIndex = this.zIndex_;
}
}
};
/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function () {
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";
if (this.alignBottom_) {
this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
} else {
this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
}
if (this.isHidden_) {
this.div_.style.visibility = "hidden";
} else {
this.div_.style.visibility = "visible";
}
};
/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
* <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
* properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
* is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function (opt_opts) {
if (typeof opt_opts.boxClass !== "undefined") { // Must be first
this.boxClass_ = opt_opts.boxClass;
this.setBoxStyle_();
}
if (typeof opt_opts.boxStyle !== "undefined") { // Must be second
this.boxStyle_ = opt_opts.boxStyle;
this.setBoxStyle_();
}
if (typeof opt_opts.content !== "undefined") {
this.setContent(opt_opts.content);
}
if (typeof opt_opts.disableAutoPan !== "undefined") {
this.disableAutoPan_ = opt_opts.disableAutoPan;
}
if (typeof opt_opts.maxWidth !== "undefined") {
this.maxWidth_ = opt_opts.maxWidth;
}
if (typeof opt_opts.pixelOffset !== "undefined") {
this.pixelOffset_ = opt_opts.pixelOffset;
}
if (typeof opt_opts.alignBottom !== "undefined") {
this.alignBottom_ = opt_opts.alignBottom;
}
if (typeof opt_opts.position !== "undefined") {
this.setPosition(opt_opts.position);
}
if (typeof opt_opts.zIndex !== "undefined") {
this.setZIndex(opt_opts.zIndex);
}
if (typeof opt_opts.closeBoxMargin !== "undefined") {
this.closeBoxMargin_ = opt_opts.closeBoxMargin;
}
if (typeof opt_opts.closeBoxURL !== "undefined") {
this.closeBoxURL_ = opt_opts.closeBoxURL;
}
if (typeof opt_opts.infoBoxClearance !== "undefined") {
this.infoBoxClearance_ = opt_opts.infoBoxClearance;
}
if (typeof opt_opts.isHidden !== "undefined") {
this.isHidden_ = opt_opts.isHidden;
}
if (typeof opt_opts.visible !== "undefined") {
this.isHidden_ = !opt_opts.visible;
}
if (typeof opt_opts.enableEventPropagation !== "undefined") {
this.enableEventPropagation_ = opt_opts.enableEventPropagation;
}
if (this.div_) {
this.draw();
}
};
/**
* Sets the content of the InfoBox.
* The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function (content) {
this.content_ = content;
if (this.div_) {
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
// Odd code required to make things work with MSIE.
//
if (!this.fixedWidthSet_) {
this.div_.style.width = "";
}
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
// Perverse code required to make things work with MSIE.
// (Ensures the close box does, in fact, float to the right.)
//
if (!this.fixedWidthSet_) {
this.div_.style.width = this.div_.offsetWidth + "px";
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
}
this.addClickHandler_();
}
/**
* This event is fired when the content of the InfoBox changes.
* @name InfoBox#content_changed
* @event
*/
google.maps.event.trigger(this, "content_changed");
};
/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) {
this.draw();
}
/**
* This event is fired when the position of the InfoBox changes.
* @name InfoBox#position_changed
* @event
*/
google.maps.event.trigger(this, "position_changed");
};
/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function (index) {
this.zIndex_ = index;
if (this.div_) {
this.div_.style.zIndex = index;
}
/**
* This event is fired when the zIndex of the InfoBox changes.
* @name InfoBox#zindex_changed
* @event
*/
google.maps.event.trigger(this, "zindex_changed");
};
/**
* Sets the visibility of the InfoBox.
* @param {boolean} isVisible
*/
InfoBox.prototype.setVisible = function (isVisible) {
this.isHidden_ = !isVisible;
if (this.div_) {
this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible");
}
};
/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function () {
return this.content_;
};
/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function () {
return this.position_;
};
/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function () {
return this.zIndex_;
};
/**
* Returns a flag indicating whether the InfoBox is visible.
* @returns {boolean}
*/
InfoBox.prototype.getVisible = function () {
var isVisible;
if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) {
isVisible = false;
} else {
isVisible = !this.isHidden_;
}
return isVisible;
};
/**
* Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.show = function () {
this.isHidden_ = false;
if (this.div_) {
this.div_.style.visibility = "visible";
}
};
/**
* Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.hide = function () {
this.isHidden_ = true;
if (this.div_) {
this.div_.style.visibility = "hidden";
}
};
/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
* (usually a <tt>google.maps.Marker</tt>) is specified, the position
* of the InfoBox is set to the position of the <tt>anchor</tt>. If the
* anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function (map, anchor) {
var me = this;
if (anchor) {
this.position_ = anchor.getPosition();
this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () {
me.setPosition(this.getPosition());
});
}
this.setMap(map);
if (this.div_) {
this.panBox_();
}
};
/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function () {
var i;
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.eventListeners_) {
for (i = 0; i < this.eventListeners_.length; i++) {
google.maps.event.removeListener(this.eventListeners_[i]);
}
this.eventListeners_ = null;
}
if (this.moveListener_) {
google.maps.event.removeListener(this.moveListener_);
this.moveListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
/**
* @name KeyDragZoom for V3
* @version 2.0.9 [December 17, 2012] NOT YET RELEASED
* @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com]
* @fileoverview This library adds a drag zoom capability to a V3 Google map.
* When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code>
* while dragging a box around an area of interest will zoom the map in to that area when
* the mouse button is released. Optionally, a visual control can also be supplied for turning
* a drag zoom operation on and off.
* Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code>
* <p>
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh.
* <p>
* Note that if the map's container has a border around it, the border widths must be specified
* in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation.
* <p>NL: 2009-05-28: initial port to core API V3.
* <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove).
* <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position.
* <br>GL: 2010-06-15: added a visual control option.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
/*jslint browser:true */
/*global window,google */
/* Utility functions use "var funName=function()" syntax to allow use of the */
/* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */
/**
* Converts "thin", "medium", and "thick" to pixel widths
* in an MSIE environment. Not called for other browsers
* because getComputedStyle() returns pixel widths automatically.
* @param {string} widthValue The value of the border width parameter.
*/
var toPixels = function (widthValue) {
var px;
switch (widthValue) {
case "thin":
px = "2px";
break;
case "medium":
px = "4px";
break;
case "thick":
px = "6px";
break;
default:
px = widthValue;
}
return px;
};
/**
* Get the widths of the borders of an HTML element.
*
* @param {Node} h The HTML element.
* @return {Object} The width object {top, bottom left, right}.
*/
var getBorderWidths = function (h) {
var computedStyle;
var bw = {};
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
return bw;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (h.currentStyle) {
// The current styles may not be in pixel units so try to convert (bad!)
bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0;
bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0;
bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0;
bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0;
return bw;
}
}
// Shouldn't get this far for any modern browser
bw.top = parseInt(h.style["border-top-width"], 10) || 0;
bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0;
bw.left = parseInt(h.style["border-left-width"], 10) || 0;
bw.right = parseInt(h.style["border-right-width"], 10) || 0;
return bw;
};
// Page scroll values for use by getMousePosition. To prevent flickering on MSIE
// they are calculated only when the document actually scrolls, not every time the
// mouse moves (as they would be if they were calculated inside getMousePosition).
var scroll = {
x: 0,
y: 0
};
var getScrollValue = function (e) {
scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft);
scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop);
};
getScrollValue();
/**
* Get the position of the mouse relative to the document.
* @param {Event} e The mouse event.
* @return {Object} The position object {left, top}.
*/
var getMousePosition = function (e) {
var posX = 0, posY = 0;
e = e || window.event;
if (typeof e.pageX !== "undefined") {
posX = e.pageX;
posY = e.pageY;
} else if (typeof e.clientX !== "undefined") { // MSIE
posX = e.clientX + scroll.x;
posY = e.clientY + scroll.y;
}
return {
left: posX,
top: posY
};
};
/**
* Get the position of an HTML element relative to the document.
* @param {Node} h The HTML element.
* @return {Object} The position object {left, top}.
*/
var getElementPosition = function (h) {
var posX = h.offsetLeft;
var posY = h.offsetTop;
var parent = h.offsetParent;
// Add offsets for all ancestors in the hierarchy
while (parent !== null) {
// Adjust for scrolling elements which may affect the map position.
//
// See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific
//
// "...make sure that every element [on a Web page] with an overflow
// of anything other than visible also has a position style set to
// something other than the default static..."
if (parent !== document.body && parent !== document.documentElement) {
posX -= parent.scrollLeft;
posY -= parent.scrollTop;
}
// See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5
// Example: http://notebook.kulchenko.com/maps/gridmove
var m = parent;
// This is the "normal" way to get offset information:
var moffx = m.offsetLeft;
var moffy = m.offsetTop;
// This covers those cases where a transform is used:
if (!moffx && !moffy && window.getComputedStyle) {
var matrix = document.defaultView.getComputedStyle(m, null).MozTransform ||
document.defaultView.getComputedStyle(m, null).WebkitTransform;
if (matrix) {
if (typeof matrix === "string") {
var parms = matrix.split(",");
moffx += parseInt(parms[4], 10) || 0;
moffy += parseInt(parms[5], 10) || 0;
}
}
}
posX += moffx;
posY += moffy;
parent = parent.offsetParent;
}
return {
left: posX,
top: posY
};
};
/**
* Set the properties of an object to those from another object.
* @param {Object} obj The target object.
* @param {Object} vals The source object.
*/
var setVals = function (obj, vals) {
if (obj && vals) {
for (var x in vals) {
if (vals.hasOwnProperty(x)) {
obj[x] = vals[x];
}
}
}
return obj;
};
/**
* Set the opacity. If op is not passed in, this function just performs an MSIE fix.
* @param {Node} h The HTML element.
* @param {number} op The opacity value (0-1).
*/
var setOpacity = function (h, op) {
if (typeof op !== "undefined") {
h.style.opacity = op;
}
if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") {
h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")";
}
};
/**
* @name KeyDragZoomOptions
* @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>.
* @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>.
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh. Also note that the
* <code>alt</code> hot key refers to the Option key on a Macintosh.
* @property {Object} [boxStyle={border: "4px solid #736AFF"}]
* An object literal defining the CSS styles of the zoom box.
* Border widths must be specified in pixel units (or as thin, medium, or thick).
* @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}]
* An object literal defining the CSS styles of the veil pane which covers the map when a drag
* zoom is activated. The previous name for this property was <code>paneStyle</code> but the use
* of this name is now deprecated.
* @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is
* selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area
* selection tool.
* @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used.
* @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual
* control. To prevent the visual control from being printed, set this property to the name of
* a class, defined inside a <code>@media print</code> rule, which sets the CSS
* <code>display</code> style to <code>none</code>.
* @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP]
* The position of the visual control.
* @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values
* provided by this property are the offsets (in pixels) from the location at which the control
* would normally be drawn to the desired drawing location.
* @property {number} [visualPositionIndex=null] The index of the visual control.
* The index is for controlling the placement of the control relative to other controls at the
* position given by <code>visualPosition</code>; controls with a lower index are placed first.
* Use a negative value to place the control <i>before</i> any default controls. No index is
* generally required.
* @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"]
* The URL of the sprite image used for showing the visual control in the on, off, and hot
* (i.e., when the mouse is over the control) states. The three images within the sprite must
* be the same size and arranged in on-hot-off order in a single row with no spaces between images.
* @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by
* this property are the size (in pixels) of each of the images within <code>visualSprite</code>.
* @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}]
* An object literal defining the help tips that appear when
* the mouse moves over the visual control. The <code>off</code> property is the tip to be shown
* when the control is off and the <code>on</code> property is the tip to be shown when the
* control is on.
*/
/**
* @name DragZoom
* @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key
* or by turning on the visual control.
* This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly.
* Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
function DragZoom(map, opt_zoomOpts) {
var me = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
}
/**
* Initialize the tool.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
DragZoom.prototype.init_ = function (map, opt_zoomOpts) {
var i;
var me = this;
this.map_ = map;
opt_zoomOpts = opt_zoomOpts || {};
this.key_ = opt_zoomOpts.key || "shift";
this.key_ = this.key_.toLowerCase();
this.borderWidths_ = getBorderWidths(this.map_.getDiv());
this.veilDiv_ = [];
for (i = 0; i < 4; i++) {
this.veilDiv_[i] = document.createElement("div");
// Prevents selection of other elements on the webpage
// when a drag zoom operation is in progress:
this.veilDiv_[i].onselectstart = function () {
return false;
};
// Apply default style values for the veil:
setVals(this.veilDiv_[i].style, {
backgroundColor: "gray",
opacity: 0.25,
cursor: "crosshair"
});
// Apply style values specified in veilStyle parameter:
setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle"
setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle"
// Apply mandatory style values:
setVals(this.veilDiv_[i].style, {
position: "absolute",
overflow: "hidden",
display: "none"
});
// Workaround for Firefox Shift-Click problem:
if (this.key_ === "shift") {
this.veilDiv_[i].style.MozUserSelect = "none";
}
setOpacity(this.veilDiv_[i]);
// An IE fix: If the background is transparent it cannot capture mousedown
// events, so if it is, change the background to white with 0 opacity.
if (this.veilDiv_[i].style.backgroundColor === "transparent") {
this.veilDiv_[i].style.backgroundColor = "white";
setOpacity(this.veilDiv_[i], 0);
}
this.map_.getDiv().appendChild(this.veilDiv_[i]);
}
this.noZoom_ = opt_zoomOpts.noZoom || false;
this.visualEnabled_ = opt_zoomOpts.visualEnabled || false;
this.visualClass_ = opt_zoomOpts.visualClass || "";
this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP;
this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0);
this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null;
this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png";
this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20);
this.visualTips_ = opt_zoomOpts.visualTips || {};
this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode";
this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode";
this.boxDiv_ = document.createElement("div");
// Apply default style values for the zoom box:
setVals(this.boxDiv_.style, {
border: "4px solid #736AFF"
});
// Apply style values specified in boxStyle parameter:
setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle);
// Apply mandatory style values:
setVals(this.boxDiv_.style, {
position: "absolute",
display: "none"
});
setOpacity(this.boxDiv_);
this.map_.getDiv().appendChild(this.boxDiv_);
this.boxBorderWidths_ = getBorderWidths(this.boxDiv_);
this.listeners_ = [
google.maps.event.addDomListener(document, "keydown", function (e) {
me.onKeyDown_(e);
}),
google.maps.event.addDomListener(document, "keyup", function (e) {
me.onKeyUp_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(document, "mousedown", function (e) {
me.onMouseDownDocument_(e);
}),
google.maps.event.addDomListener(document, "mousemove", function (e) {
me.onMouseMove_(e);
}),
google.maps.event.addDomListener(document, "mouseup", function (e) {
me.onMouseUp_(e);
}),
google.maps.event.addDomListener(window, "scroll", getScrollValue)
];
this.hotKeyDown_ = false;
this.mouseDown_ = false;
this.dragging_ = false;
this.startPt_ = null;
this.endPt_ = null;
this.mapWidth_ = null;
this.mapHeight_ = null;
this.mousePosn_ = null;
this.mapPosn_ = null;
if (this.visualEnabled_) {
this.buttonDiv_ = this.initControl_(this.visualPositionOffset_);
if (this.visualPositionIndex_ !== null) {
this.buttonDiv_.index = this.visualPositionIndex_;
}
this.map_.controls[this.visualPosition_].push(this.buttonDiv_);
this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1;
}
};
/**
* Initializes the visual control and returns its DOM element.
* @param {Size} offset The offset of the control from its normal position.
* @return {Node} The DOM element containing the visual control.
*/
DragZoom.prototype.initControl_ = function (offset) {
var control;
var image;
var me = this;
control = document.createElement("div");
control.className = this.visualClass_;
control.style.position = "relative";
control.style.overflow = "hidden";
control.style.height = this.visualSize_.height + "px";
control.style.width = this.visualSize_.width + "px";
control.title = this.visualTips_.off;
image = document.createElement("img");
image.src = this.visualSprite_;
image.style.position = "absolute";
image.style.left = -(this.visualSize_.width * 2) + "px";
image.style.top = 0 + "px";
control.appendChild(image);
control.onclick = function (e) {
me.hotKeyDown_ = !me.hotKeyDown_;
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
me.activatedByControl_ = true;
google.maps.event.trigger(me, "activate");
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
google.maps.event.trigger(me, "deactivate");
}
me.onMouseMove_(e); // Updates the veil
};
control.onmouseover = function () {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px";
};
control.onmouseout = function () {
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
}
};
control.ondragstart = function () {
return false;
};
setVals(control.style, {
cursor: "pointer",
marginTop: offset.height + "px",
marginLeft: offset.width + "px"
});
return control;
};
/**
* Returns <code>true</code> if the hot key is being pressed when an event occurs.
* @param {Event} e The keyboard event.
* @return {boolean} Flag indicating whether the hot key is down.
*/
DragZoom.prototype.isHotKeyDown_ = function (e) {
var isHot;
e = e || window.event;
isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl");
if (!isHot) {
// Need to look at keyCode for Opera because it
// doesn't set the shiftKey, altKey, ctrlKey properties
// unless a non-modifier event is being reported.
//
// See http://cross-browser.com/x/examples/shift_mode.php
// Also see http://unixpapa.com/js/key.html
switch (e.keyCode) {
case 16:
if (this.key_ === "shift") {
isHot = true;
}
break;
case 17:
if (this.key_ === "ctrl") {
isHot = true;
}
break;
case 18:
if (this.key_ === "alt") {
isHot = true;
}
break;
}
}
return isHot;
};
/**
* Returns <code>true</code> if the mouse is on top of the map div.
* The position is captured in onMouseMove_.
* @return {boolean}
*/
DragZoom.prototype.isMouseOnMap_ = function () {
var mousePosn = this.mousePosn_;
if (mousePosn) {
var mapPosn = this.mapPosn_;
var mapDiv = this.map_.getDiv();
return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) &&
mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight);
} else {
// if user never moved mouse
return false;
}
};
/**
* Show the veil if the hot key is down and the mouse is over the map,
* otherwise hide the veil.
*/
DragZoom.prototype.setVeilVisibility_ = function () {
var i;
if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) {
var mapDiv = this.map_.getDiv();
this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right);
this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom);
if (this.activatedByControl_) { // Veil covers entire map (except control)
var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width;
var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height;
var width = this.visualSize_.width;
var height = this.visualSize_.height;
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
} else {
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.width = this.mapWidth_ + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
for (i = 1; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.width = "0px";
this.veilDiv_[i].style.height = "0px";
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
}
} else {
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
}
};
/**
* Handle key down. Show the veil if the hot key has been pressed.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyDown_ = function (e) {
if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.hotKeyDown_ = true;
this.activatedByControl_ = false;
this.setVeilVisibility_();
/**
* This event is fired when the hot key is pressed.
* @name DragZoom#activate
* @event
*/
google.maps.event.trigger(this, "activate");
}
};
/**
* Get the <code>google.maps.Point</code> of the mouse position.
* @param {Event} e The mouse event.
* @return {Point} The mouse position.
*/
DragZoom.prototype.getMousePoint_ = function (e) {
var mousePosn = getMousePosition(e);
var p = new google.maps.Point();
p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left;
p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top;
p.x = Math.min(p.x, this.mapWidth_);
p.y = Math.min(p.y, this.mapHeight_);
p.x = Math.max(p.x, 0);
p.y = Math.max(p.y, 0);
return p;
};
/**
* Handle mouse down.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDown_ = function (e) {
if (this.map_ && this.hotKeyDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.dragging_ = true;
this.startPt_ = this.endPt_ = this.getMousePoint_(e);
this.boxDiv_.style.width = this.boxDiv_.style.height = "0px";
var prj = this.prjov_.getProjection();
var latlng = prj.fromContainerPixelToLatLng(this.startPt_);
/**
* This event is fired when the drag operation begins.
* The parameter passed is the geographic position of the starting point.
* @name DragZoom#dragstart
* @param {LatLng} latlng The geographic position of the starting point.
* @event
*/
google.maps.event.trigger(this, "dragstart", latlng);
}
};
/**
* Handle mouse down at the document level.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDownDocument_ = function (e) {
this.mouseDown_ = true;
};
/**
* Handle mouse move.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseMove_ = function (e) {
this.mousePosn_ = getMousePosition(e);
if (this.dragging_) {
this.endPt_ = this.getMousePoint_(e);
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// For benefit of MSIE 7/8 ensure following values are not negative:
var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right));
var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom));
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
// Selection rectangle:
this.boxDiv_.style.top = top + "px";
this.boxDiv_.style.left = left + "px";
this.boxDiv_.style.width = boxWidth + "px";
this.boxDiv_.style.height = boxHeight + "px";
this.boxDiv_.style.display = "block";
/**
* This event is fired repeatedly while the user drags a box across the area of interest.
* The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code>
* (for performance reasons), relative to the map container. Also passed is the projection object
* so that the event listener, if necessary, can convert the pixel positions to geographic
* coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>.
* @name DragZoom#drag
* @param {Point} southwestPixel The southwest point of the selection area.
* @param {Point} northeastPixel The northeast point of the selection area.
* @param {MapCanvasProjection} prj The projection object.
* @event
*/
google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection());
} else if (!this.mouseDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.setVeilVisibility_();
}
};
/**
* Handle mouse up.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseUp_ = function (e) {
var z;
var me = this;
this.mouseDown_ = false;
if (this.dragging_) {
if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) {
this.onKeyUp_(e); // Cancel event
return;
}
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// Google Maps API bug: setCenter() doesn't work as expected if the map has a
// border on the left or top. The code here includes a workaround for this problem.
var kGoogleCenteringBug = true;
if (kGoogleCenteringBug) {
left += this.borderWidths_.left;
top += this.borderWidths_.top;
}
var prj = this.prjov_.getProjection();
var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
if (this.noZoom_) {
this.boxDiv_.style.display = "none";
} else {
// Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens.
z = this.map_.getZoom();
this.map_.fitBounds(bnds);
if (this.map_.getZoom() < z) {
this.map_.setZoom(z);
}
// Redraw box after zoom:
var swPt = prj.fromLatLngToContainerPixel(sw);
var nePt = prj.fromLatLngToContainerPixel(ne);
if (kGoogleCenteringBug) {
swPt.x -= this.borderWidths_.left;
swPt.y -= this.borderWidths_.top;
nePt.x -= this.borderWidths_.left;
nePt.y -= this.borderWidths_.top;
}
this.boxDiv_.style.left = swPt.x + "px";
this.boxDiv_.style.top = nePt.y + "px";
this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px";
this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px";
// Hide box asynchronously after 1 second:
setTimeout(function () {
me.boxDiv_.style.display = "none";
}, 1000);
}
this.dragging_ = false;
this.onMouseMove_(e); // Updates the veil
/**
* This event is fired when the drag operation ends.
* The parameter passed is the geographic bounds of the selected area.
* Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends.
* @name DragZoom#dragend
* @param {LatLngBounds} bnds The geographic bounds of the selected area.
* @event
*/
google.maps.event.trigger(this, "dragend", bnds);
// if the hot key isn't down, the drag zoom must have been activated by turning
// on the visual control. In this case, finish up by simulating a key up event.
if (!this.isHotKeyDown_(e)) {
this.onKeyUp_(e);
}
}
};
/**
* Handle key up.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyUp_ = function (e) {
var i;
var left, top, width, height, prj, sw, ne;
var bnds = null;
if (this.map_ && this.hotKeyDown_) {
this.hotKeyDown_ = false;
if (this.dragging_) {
this.boxDiv_.style.display = "none";
this.dragging_ = false;
// Calculate the bounds when drag zoom was cancelled
left = Math.min(this.startPt_.x, this.endPt_.x);
top = Math.min(this.startPt_.y, this.endPt_.y);
width = Math.abs(this.startPt_.x - this.endPt_.x);
height = Math.abs(this.startPt_.y - this.endPt_.y);
prj = this.prjov_.getProjection();
sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
bnds = new google.maps.LatLngBounds(sw, ne);
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
if (this.visualEnabled_) {
this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px";
this.buttonDiv_.title = this.visualTips_.off;
this.buttonDiv_.style.display = "";
}
/**
* This event is fired when the hot key is released.
* The parameter passed is the geographic bounds of the selected area immediately
* before the hot key was released.
* @name DragZoom#deactivate
* @param {LatLngBounds} bnds The geographic bounds of the selected area immediately
* before the hot key was released.
* @event
*/
google.maps.event.trigger(this, "deactivate", bnds);
}
};
/**
* @name google.maps.Map
* @class These are new methods added to the Google Maps JavaScript API V3's
* <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a>
* class.
*/
/**
* Enables drag zoom. The user can zoom to an area of interest by holding down the hot key
* <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning
* on the visual control then dragging a box around the area.
* @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters.
*/
google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) {
this.dragZoom_ = new DragZoom(this, opt_zoomOpts);
};
/**
* Disables drag zoom.
*/
google.maps.Map.prototype.disableKeyDragZoom = function () {
var i;
var d = this.dragZoom_;
if (d) {
for (i = 0; i < d.listeners_.length; ++i) {
google.maps.event.removeListener(d.listeners_[i]);
}
this.getDiv().removeChild(d.boxDiv_);
for (i = 0; i < d.veilDiv_.length; i++) {
this.getDiv().removeChild(d.veilDiv_[i]);
}
if (d.visualEnabled_) {
// Remove the custom control:
this.controls[d.visualPosition_].removeAt(d.controlIndex_);
}
d.prjov_.setMap(null);
this.dragZoom_ = null;
}
};
/**
* Returns <code>true</code> if the drag zoom feature has been enabled.
* @return {boolean}
*/
google.maps.Map.prototype.keyDragZoomEnabled = function () {
return this.dragZoom_ !== null;
};
/**
* Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called.
* With this object you can use <code>google.maps.event.addListener</code> to attach event listeners
* for the "activate", "deactivate", "dragstart", "drag", and "dragend" events.
* @return {DragZoom}
*/
google.maps.Map.prototype.getDragZoomObject = function () {
return this.dragZoom_;
};
})();
/**
* @name MarkerClustererPlus for Google Maps V3
* @version 2.1.1 [November 4, 2013]
* @author Gary Little
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of markers.
* <p>
* This is an enhanced V3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
* <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
* >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
* <p>
* v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
* adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
* and <code>calculator</code> properties as well as support for four more events. It also allows
* greater control over the styling of the text that appears on the cluster marker. The
* documentation has been significantly improved and the overall code has been simplified and
* polished. Very large numbers of markers can now be managed without causing Javascript timeout
* errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
* deprecated. The new name is <code>click</code>, so please change your application code now.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @name ClusterIconStyle
* @class This class represents the object for values in the <code>styles</code> array passed
* to the {@link MarkerClusterer} constructor. The element in this array that is used to
* style the cluster icon is determined by calling the <code>calculator</code> function.
*
* @property {string} url The URL of the cluster icon image file. Required.
* @property {number} height The display height (in pixels) of the cluster icon. Required.
* @property {number} width The display width (in pixels) of the cluster icon. Required.
* @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
* where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
* where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
* increases to the right of center. The default is <code>[0, 0]</code>.
* @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
* spot on the cluster icon that is to be aligned with the cluster position. The format is
* <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
* <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
* anchor position is the center of the cluster icon.
* @property {string} [textColor="black"] The color of the label text shown on the
* cluster icon.
* @property {number} [textSize=11] The size (in pixels) of the label text shown on the
* cluster icon.
* @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
* property for the label text shown on the cluster icon.
* @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
* within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
* (the same format as for the CSS <code>background-position</code> property). You must set
* this property appropriately when the image defined by <code>url</code> represents a sprite
* containing multiple images. Note that the position <i>must</i> be specified in px units.
*/
/**
* @name ClusterIconInfo
* @class This class is an object containing general information about a cluster icon. This is
* the object that a <code>calculator</code> function returns.
*
* @property {string} text The text of the label to be shown on the cluster icon.
* @property {number} index The index plus 1 of the element in the <code>styles</code>
* array to be used to style the cluster icon.
* @property {string} title The tooltip to display when the mouse moves over the cluster icon.
* If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
* value of the <code>title</code> property passed to the MarkerClusterer.
*/
/**
* A cluster icon.
*
* @constructor
* @extends google.maps.OverlayView
* @param {Cluster} cluster The cluster with which the icon is to be associated.
* @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
* to use for various cluster sizes.
* @private
*/
function ClusterIcon(cluster, styles) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.cluster_ = cluster;
this.className_ = cluster.getMarkerClusterer().getClusterClass();
this.styles_ = styles;
this.center_ = null;
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}
/**
* Adds the icon to the DOM.
*/
ClusterIcon.prototype.onAdd = function () {
var cClusterIcon = this;
var cMouseDownInCluster;
var cDraggingMapByCluster;
this.div_ = document.createElement("div");
this.div_.className = this.className_;
if (this.visible_) {
this.show();
}
this.getPanes().overlayMouseTarget.appendChild(this.div_);
// Fix for Issue 157
this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () {
cDraggingMapByCluster = cMouseDownInCluster;
});
google.maps.event.addDomListener(this.div_, "mousedown", function () {
cMouseDownInCluster = true;
cDraggingMapByCluster = false;
});
google.maps.event.addDomListener(this.div_, "click", function (e) {
cMouseDownInCluster = false;
if (!cDraggingMapByCluster) {
var theBounds;
var mz;
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when a cluster marker is clicked.
* @name MarkerClusterer#click
* @param {Cluster} c The cluster that was clicked.
* @event
*/
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// The default click handler follows. Disable it by setting
// the zoomOnClick property to false.
if (mc.getZoomOnClick()) {
// Zoom into the cluster.
mz = mc.getMaxZoom();
theBounds = cClusterIcon.cluster_.getBounds();
mc.getMap().fitBounds(theBounds);
// There is a fix for Issue 170 here:
setTimeout(function () {
mc.getMap().fitBounds(theBounds);
// Don't zoom beyond the max zoom level
if (mz !== null && (mc.getMap().getZoom() > mz)) {
mc.getMap().setZoom(mz + 1);
}
}, 100);
}
// Prevent event propagation to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
});
google.maps.event.addDomListener(this.div_, "mouseover", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves over a cluster marker.
* @name MarkerClusterer#mouseover
* @param {Cluster} c The cluster that the mouse moved over.
* @event
*/
google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
});
google.maps.event.addDomListener(this.div_, "mouseout", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves out of a cluster marker.
* @name MarkerClusterer#mouseout
* @param {Cluster} c The cluster that the mouse moved out of.
* @event
*/
google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
});
};
/**
* Removes the icon from the DOM.
*/
ClusterIcon.prototype.onRemove = function () {
if (this.div_ && this.div_.parentNode) {
this.hide();
google.maps.event.removeListener(this.boundsChangedListener_);
google.maps.event.clearInstanceListeners(this.div_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the icon.
*/
ClusterIcon.prototype.draw = function () {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + "px";
this.div_.style.left = pos.x + "px";
}
};
/**
* Hides the icon.
*/
ClusterIcon.prototype.hide = function () {
if (this.div_) {
this.div_.style.display = "none";
}
this.visible_ = false;
};
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
/**
* Sets the icon styles to the appropriate element in the styles array.
*
* @param {ClusterIconInfo} sums The icon label text and styles index.
*/
ClusterIcon.prototype.useStyle = function (sums) {
this.sums_ = sums;
var index = Math.max(0, sums.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style.url;
this.height_ = style.height;
this.width_ = style.width;
this.anchorText_ = style.anchorText || [0, 0];
this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
this.textColor_ = style.textColor || "black";
this.textSize_ = style.textSize || 11;
this.textDecoration_ = style.textDecoration || "none";
this.fontWeight_ = style.fontWeight || "bold";
this.fontStyle_ = style.fontStyle || "normal";
this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
this.backgroundPosition_ = style.backgroundPosition || "0 0";
};
/**
* Sets the position at which to center the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function (center) {
this.center_ = center;
};
/**
* Creates the cssText style parameter based on the position of the icon.
*
* @param {google.maps.Point} pos The position of the icon.
* @return {string} The CSS style text.
*/
ClusterIcon.prototype.createCss = function (pos) {
var style = [];
style.push("cursor: pointer;");
style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
return style.join("");
};
/**
* Returns the position at which to place the DIV depending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
*/
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
pos.x -= this.anchorIcon_[1];
pos.y -= this.anchorIcon_[0];
pos.x = parseInt(pos.x, 10);
pos.y = parseInt(pos.y, 10);
return pos;
};
/**
* Creates a single cluster that manages a group of proximate markers.
* Used internally, do not call this constructor directly.
* @constructor
* @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
* cluster is associated.
*/
function Cluster(mc) {
this.markerClusterer_ = mc;
this.map_ = mc.getMap();
this.gridSize_ = mc.getGridSize();
this.minClusterSize_ = mc.getMinimumClusterSize();
this.averageCenter_ = mc.getAverageCenter();
this.markers_ = [];
this.center_ = null;
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}
/**
* Returns the number of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {number} The number of markers in the cluster.
*/
Cluster.prototype.getSize = function () {
return this.markers_.length;
};
/**
* Returns the array of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {Array} The array of markers in the cluster.
*/
Cluster.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the center of the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {google.maps.LatLng} The center of the cluster.
*/
Cluster.prototype.getCenter = function () {
return this.center_;
};
/**
* Returns the map with which the cluster is associated.
*
* @return {google.maps.Map} The map.
* @ignore
*/
Cluster.prototype.getMap = function () {
return this.map_;
};
/**
* Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
*
* @return {MarkerClusterer} The associated marker clusterer.
* @ignore
*/
Cluster.prototype.getMarkerClusterer = function () {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
Cluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
Cluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = [];
delete this.markers_;
};
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
Cluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
for (i = 0; i < mCount; i++) {
this.markers_[i].setMap(null);
}
} else {
marker.setMap(null);
}
this.updateIcon_();
return true;
};
/**
* Determines if a marker lies within the cluster's bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
* @ignore
*/
Cluster.prototype.isMarkerInClusterBounds = function (marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Calculates the extended bounds of the cluster with the grid.
*/
Cluster.prototype.calculateBounds_ = function () {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Updates the cluster icon.
*/
Cluster.prototype.updateIcon_ = function () {
var mCount = this.markers_.length;
var mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
this.clusterIcon_.hide();
return;
}
if (mCount < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.useStyle(sums);
this.clusterIcon_.show();
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
var i;
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) !== -1;
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
return true;
}
}
}
return false;
};
/**
* @name MarkerClustererOptions
* @class This class represents the optional parameter passed to
* the {@link MarkerClusterer} constructor.
* @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
* @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
* <code>null</code> if clustering is to be enabled at all zoom levels.
* @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
* clicked. You may want to set this to <code>false</code> if you have installed a handler
* for the <code>click</code> event and it deals with zooming on its own.
* @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
* the average position of all markers in the cluster. If set to <code>false</code>, the
* cluster marker is positioned at the location of the first marker added to the cluster.
* @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
* before the markers are hidden and a cluster marker appears.
* @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
* may want to set this to <code>true</code> to ensure that hidden markers are not included
* in the marker count that appears on a cluster marker (this count is the value of the
* <code>text</code> property of the result returned by the default <code>calculator</code>).
* If set to <code>true</code> and you change the visibility of a marker being clustered, be
* sure to also call <code>MarkerClusterer.repaint()</code>.
* @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
* marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
* different tooltip for each cluster marker.)
* @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
* the text to be displayed on a cluster marker and the index indicating which style to use
* for the cluster marker. The input parameters for the function are (1) the array of markers
* represented by a cluster marker and (2) the number of cluster icon styles. It returns a
* {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
* <code>text</code> property which is the number of markers in the cluster and an
* <code>index</code> property which is one higher than the lowest integer such that
* <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
* array, whichever is less. The <code>styles</code> array element used has an index of
* <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
* <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
* for a cluster icon representing 125 markers so the element used in the <code>styles</code>
* array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
* property that contains the text of the tooltip to be used for the cluster marker. If
* <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
* property for the MarkerClusterer.
* @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
* for the cluster markers. Use this class to define CSS styles that are not set up by the code
* that processes the <code>styles</code> array.
* @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
* of the cluster markers to be used. The element to be used to style a given cluster marker
* is determined by the function defined by the <code>calculator</code> property.
* The default is an array of {@link ClusterIconStyle} elements whose properties are derived
* from the values for <code>imagePath</code>, <code>imageExtension</code>, and
* <code>imageSizes</code>.
* @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
* have sizes that are some multiple (typically double) of their actual display size. Icons such
* as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
* Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
* @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
* number of markers to be processed in a single batch when using a browser other than
* Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
* @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
* being used, markers are processed in several batches with a small delay inserted between
* each batch in an attempt to avoid Javascript timeout errors. Set this property to the
* number of markers to be processed in a single batch; select as high a number as you can
* without causing a timeout error in the browser. This number might need to be as low as 100
* if 15,000 markers are being managed, for example.
* @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
* The full URL of the root name of the group of image files to use for cluster icons.
* The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
* where n is the image file number (1, 2, etc.).
* @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
* The extension name for the cluster icon image files (e.g., <code>"png"</code> or
* <code>"jpg"</code>).
* @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
* An array of numbers containing the widths of the group of
* <code>imagePath</code>n.<code>imageExtension</code> image files.
* (The images are assumed to be square.)
*/
/**
* Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
* @constructor
* @extends google.maps.OverlayView
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
* @param {MarkerClustererOptions} [opt_options] The optional parameters.
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
opt_markers = opt_markers || [];
opt_options = opt_options || {};
this.markers_ = [];
this.clusters_ = [];
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
this.gridSize_ = opt_options.gridSize || 60;
this.minClusterSize_ = opt_options.minimumClusterSize || 2;
this.maxZoom_ = opt_options.maxZoom || null;
this.styles_ = opt_options.styles || [];
this.title_ = opt_options.title || "";
this.zoomOnClick_ = true;
if (opt_options.zoomOnClick !== undefined) {
this.zoomOnClick_ = opt_options.zoomOnClick;
}
this.averageCenter_ = false;
if (opt_options.averageCenter !== undefined) {
this.averageCenter_ = opt_options.averageCenter;
}
this.ignoreHidden_ = false;
if (opt_options.ignoreHidden !== undefined) {
this.ignoreHidden_ = opt_options.ignoreHidden;
}
this.enableRetinaIcons_ = false;
if (opt_options.enableRetinaIcons !== undefined) {
this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
}
this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
this.clusterClass_ = opt_options.clusterClass || "cluster";
if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
// Try to avoid IE timeout when processing a huge number of markers:
this.batchSize_ = this.batchSizeIE_;
}
this.setupStyles_();
this.addMarkers(opt_markers, true);
this.setMap(map); // Note: this causes onAdd to be called
}
/**
* Implementation of the onAdd interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function () {
var cMarkerClusterer = this;
this.activeMap_ = this.getMap();
this.ready_ = true;
this.repaint();
// Add the map event listeners
this.listeners_ = [
google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
cMarkerClusterer.resetViewport_(false);
// Workaround for this Google bug: when map is at level 0 and "-" of
// zoom slider is clicked, a "zoom_changed" event is fired even though
// the map doesn't zoom out any further. In this situation, no "idle"
// event is triggered so the cluster markers that have been removed
// do not get redrawn. Same goes for a zoom in at maxZoom.
if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) {
google.maps.event.trigger(this, "idle");
}
}),
google.maps.event.addListener(this.getMap(), "idle", function () {
cMarkerClusterer.redraw_();
})
];
};
/**
* Implementation of the onRemove interface method.
* Removes map event listeners and all cluster icons from the DOM.
* All managed markers are also put back on the map.
* @ignore
*/
MarkerClusterer.prototype.onRemove = function () {
var i;
// Put all the managed markers back on the map:
for (i = 0; i < this.markers_.length; i++) {
if (this.markers_[i].getMap() !== this.activeMap_) {
this.markers_[i].setMap(this.activeMap_);
}
}
// Remove all clusters:
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Remove map event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
};
/**
* Implementation of the draw interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function () {};
/**
* Sets up the styles object.
*/
MarkerClusterer.prototype.setupStyles_ = function () {
var i, size;
if (this.styles_.length > 0) {
return;
}
for (i = 0; i < this.imageSizes_.length; i++) {
size = this.imageSizes_[i];
this.styles_.push({
url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fits the map to the bounds of the markers managed by the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function () {
var i;
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
this.getMap().fitBounds(bounds);
};
/**
* Returns the value of the <code>gridSize</code> property.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function () {
return this.gridSize_;
};
/**
* Sets the value of the <code>gridSize</code> property.
*
* @param {number} gridSize The grid size.
*/
MarkerClusterer.prototype.setGridSize = function (gridSize) {
this.gridSize_ = gridSize;
};
/**
* Returns the value of the <code>minimumClusterSize</code> property.
*
* @return {number} The minimum cluster size.
*/
MarkerClusterer.prototype.getMinimumClusterSize = function () {
return this.minClusterSize_;
};
/**
* Sets the value of the <code>minimumClusterSize</code> property.
*
* @param {number} minimumClusterSize The minimum cluster size.
*/
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
this.minClusterSize_ = minimumClusterSize;
};
/**
* Returns the value of the <code>maxZoom</code> property.
*
* @return {number} The maximum zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function () {
return this.maxZoom_;
};
/**
* Sets the value of the <code>maxZoom</code> property.
*
* @param {number} maxZoom The maximum zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Returns the value of the <code>styles</code> property.
*
* @return {Array} The array of styles defining the cluster markers to be used.
*/
MarkerClusterer.prototype.getStyles = function () {
return this.styles_;
};
/**
* Sets the value of the <code>styles</code> property.
*
* @param {Array.<ClusterIconStyle>} styles The array of styles to use.
*/
MarkerClusterer.prototype.setStyles = function (styles) {
this.styles_ = styles;
};
/**
* Returns the value of the <code>title</code> property.
*
* @return {string} The content of the title text.
*/
MarkerClusterer.prototype.getTitle = function () {
return this.title_;
};
/**
* Sets the value of the <code>title</code> property.
*
* @param {string} title The value of the title property.
*/
MarkerClusterer.prototype.setTitle = function (title) {
this.title_ = title;
};
/**
* Returns the value of the <code>zoomOnClick</code> property.
*
* @return {boolean} True if zoomOnClick property is set.
*/
MarkerClusterer.prototype.getZoomOnClick = function () {
return this.zoomOnClick_;
};
/**
* Sets the value of the <code>zoomOnClick</code> property.
*
* @param {boolean} zoomOnClick The value of the zoomOnClick property.
*/
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
this.zoomOnClick_ = zoomOnClick;
};
/**
* Returns the value of the <code>averageCenter</code> property.
*
* @return {boolean} True if averageCenter property is set.
*/
MarkerClusterer.prototype.getAverageCenter = function () {
return this.averageCenter_;
};
/**
* Sets the value of the <code>averageCenter</code> property.
*
* @param {boolean} averageCenter The value of the averageCenter property.
*/
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
this.averageCenter_ = averageCenter;
};
/**
* Returns the value of the <code>ignoreHidden</code> property.
*
* @return {boolean} True if ignoreHidden property is set.
*/
MarkerClusterer.prototype.getIgnoreHidden = function () {
return this.ignoreHidden_;
};
/**
* Sets the value of the <code>ignoreHidden</code> property.
*
* @param {boolean} ignoreHidden The value of the ignoreHidden property.
*/
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
this.ignoreHidden_ = ignoreHidden;
};
/**
* Returns the value of the <code>enableRetinaIcons</code> property.
*
* @return {boolean} True if enableRetinaIcons property is set.
*/
MarkerClusterer.prototype.getEnableRetinaIcons = function () {
return this.enableRetinaIcons_;
};
/**
* Sets the value of the <code>enableRetinaIcons</code> property.
*
* @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
*/
MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {
this.enableRetinaIcons_ = enableRetinaIcons;
};
/**
* Returns the value of the <code>imageExtension</code> property.
*
* @return {string} The value of the imageExtension property.
*/
MarkerClusterer.prototype.getImageExtension = function () {
return this.imageExtension_;
};
/**
* Sets the value of the <code>imageExtension</code> property.
*
* @param {string} imageExtension The value of the imageExtension property.
*/
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
this.imageExtension_ = imageExtension;
};
/**
* Returns the value of the <code>imagePath</code> property.
*
* @return {string} The value of the imagePath property.
*/
MarkerClusterer.prototype.getImagePath = function () {
return this.imagePath_;
};
/**
* Sets the value of the <code>imagePath</code> property.
*
* @param {string} imagePath The value of the imagePath property.
*/
MarkerClusterer.prototype.setImagePath = function (imagePath) {
this.imagePath_ = imagePath;
};
/**
* Returns the value of the <code>imageSizes</code> property.
*
* @return {Array} The value of the imageSizes property.
*/
MarkerClusterer.prototype.getImageSizes = function () {
return this.imageSizes_;
};
/**
* Sets the value of the <code>imageSizes</code> property.
*
* @param {Array} imageSizes The value of the imageSizes property.
*/
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
this.imageSizes_ = imageSizes;
};
/**
* Returns the value of the <code>calculator</code> property.
*
* @return {function} the value of the calculator property.
*/
MarkerClusterer.prototype.getCalculator = function () {
return this.calculator_;
};
/**
* Sets the value of the <code>calculator</code> property.
*
* @param {function(Array.<google.maps.Marker>, number)} calculator The value
* of the calculator property.
*/
MarkerClusterer.prototype.setCalculator = function (calculator) {
this.calculator_ = calculator;
};
/**
* Returns the value of the <code>batchSizeIE</code> property.
*
* @return {number} the value of the batchSizeIE property.
*/
MarkerClusterer.prototype.getBatchSizeIE = function () {
return this.batchSizeIE_;
};
/**
* Sets the value of the <code>batchSizeIE</code> property.
*
* @param {number} batchSizeIE The value of the batchSizeIE property.
*/
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
this.batchSizeIE_ = batchSizeIE;
};
/**
* Returns the value of the <code>clusterClass</code> property.
*
* @return {string} the value of the clusterClass property.
*/
MarkerClusterer.prototype.getClusterClass = function () {
return this.clusterClass_;
};
/**
* Sets the value of the <code>clusterClass</code> property.
*
* @param {string} clusterClass The value of the clusterClass property.
*/
MarkerClusterer.prototype.setClusterClass = function (clusterClass) {
this.clusterClass_ = clusterClass;
};
/**
* Returns the array of markers managed by the clusterer.
*
* @return {Array} The array of markers managed by the clusterer.
*/
MarkerClusterer.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the number of markers managed by the clusterer.
*
* @return {number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function () {
return this.markers_.length;
};
/**
* Returns the current array of clusters formed by the clusterer.
*
* @return {Array} The array of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getClusters = function () {
return this.clusters_;
};
/**
* Returns the number of clusters formed by the clusterer.
*
* @return {number} The number of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getTotalClusters = function () {
return this.clusters_.length;
};
/**
* Adds a marker to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Adds an array of markers to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
var key;
for (key in markers) {
if (markers.hasOwnProperty(key)) {
this.pushMarkerTo_(markers[key]);
}
}
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
// If the marker is draggable add a listener so we can update the clusters on the dragend:
if (marker.getDraggable()) {
var cMarkerClusterer = this;
google.maps.event.addListener(marker, "dragend", function () {
if (cMarkerClusterer.ready_) {
this.isAdded = false;
cMarkerClusterer.repaint();
}
});
}
marker.isAdded = false;
this.markers_.push(marker);
};
/**
* Removes a marker from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
* marker was removed from the clusterer.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if the marker was removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes an array of markers from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
* were removed from the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if markers were removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
var i, r;
var removed = false;
for (i = 0; i < markers.length; i++) {
r = this.removeMarker_(markers[i]);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
MarkerClusterer.prototype.removeMarker_ = function (marker) {
var i;
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
index = i;
break;
}
}
}
if (index === -1) {
// Marker is not in our list of markers, so do nothing:
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
return true;
};
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = [];
};
/**
* Recalculates and redraws all the marker clusters from scratch.
* Call this after changing any properties.
*/
MarkerClusterer.prototype.repaint = function () {
var oldClusters = this.clusters_.slice();
this.clusters_ = [];
this.resetViewport_(false);
this.redraw_();
// Remove the old clusters.
// Do it in a timeout to prevent blinking effect.
setTimeout(function () {
var i;
for (i = 0; i < oldClusters.length; i++) {
oldClusters[i].remove();
}
}, 0);
};
/**
* Returns the current bounds extended by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
* @ignore
*/
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Redraws all the clusters.
*/
MarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
for (i = 0; i < this.markers_.length; i++) {
marker = this.markers_[i];
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
};
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Determines if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringbegin", this);
if (typeof this.timerRefStatic !== "undefined") {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
for (i = iFirst; i < iLast; i++) {
marker = this.markers_[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringend", this);
}
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* The default function for determining the label text and style
* for a cluster icon.
*
* @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
* @param {number} numStyles The number of marker styles available.
* @return {ClusterIconInfo} The information resource for the cluster.
* @constant
* @ignore
*/
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index,
title: title
};
};
/**
* The number of markers to process in one batch.
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE = 2000;
/**
* The number of markers to process in one batch (IE only).
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE_IE = 500;
/**
* The default root name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m";
/**
* The default extension name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_EXTENSION = "png";
/**
* The default array of sizes for the marker cluster images.
*
* @type {Array.<number>}
* @constant
*/
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
/**
* @name MarkerWithLabel for V3
* @version 1.1.10 [April 8, 2014]
* @author Gary Little (inspired by code from Marc Ridey of Google).
* @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
* @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
* <code>google.maps.Marker</code> class.
* <p>
* MarkerWithLabel allows you to define markers with associated labels. As you would expect,
* if the marker is draggable, so too will be the label. In addition, a marker with a label
* responds to all mouse events in the same manner as a regular marker. It also fires mouse
* events and "property changed" events just as a regular marker would. Version 1.1 adds
* support for the raiseOnDrag feature introduced in API V3.3.
* <p>
* If you drag a marker by its label, you can cancel the drag and return the marker to its
* original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
* itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint browser:true */
/*global document,google */
/**
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
* @private
*/
function inherits(childCtor, parentCtor) {
/* @constructor */
function tempCtor() {}
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/* @override */
childCtor.prototype.constructor = childCtor;
}
/**
* This constructor creates a label and associates it with a marker.
* It is for the private use of the MarkerWithLabel class.
* @constructor
* @param {Marker} marker The marker with which the label is to be associated.
* @param {string} crossURL The URL of the cross image =.
* @param {string} handCursor The URL of the hand cursor.
* @private
*/
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.setAttribute("onselectstart", "return false;");
this.eventDiv_.setAttribute("ondragstart", "return false;");
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
inherits(MarkerLabel_, google.maps.OverlayView);
/**
* Returns the DIV for the cross used when dragging a marker when the
* raiseOnDrag parameter set to true. One cross is shared with all markers.
* @param {string} crossURL The URL of the cross image =.
* @private
*/
MarkerLabel_.getSharedCross = function (crossURL) {
var div;
if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") {
div = document.createElement("img");
div.style.cssText = "position: absolute; z-index: 1000002; display: none;";
// Hopefully Google never changes the standard "X" attributes:
div.style.marginLeft = "-8px";
div.style.marginTop = "-9px";
div.src = crossURL;
MarkerLabel_.getSharedCross.crossDiv = div;
}
return MarkerLabel_.getSharedCross.crossDiv;
};
/**
* Adds the DIV representing the label to the DOM. This method is called
* automatically when the marker's <code>setMap</code> method is called.
* @private
*/
MarkerLabel_.prototype.onAdd = function () {
var me = this;
var cMouseIsDown = false;
var cDraggingLabel = false;
var cSavedZIndex;
var cLatOffset, cLngOffset;
var cIgnoreClick;
var cRaiseEnabled;
var cStartPosition;
var cStartCenter;
// Constants:
var cRaiseOffset = 20;
var cDraggingCursor = "url(" + this.handCursorURL_ + ")";
// Stops all processing of an event.
//
var cAbortEvent = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
var cStopBounce = function () {
me.marker_.setAnimation(null);
};
this.getPanes().overlayImage.appendChild(this.labelDiv_);
this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_);
// One cross is shared with all markers, so only add it once:
if (typeof MarkerLabel_.getSharedCross.processed === "undefined") {
this.getPanes().overlayImage.appendChild(this.crossDiv_);
MarkerLabel_.getSharedCross.processed = true;
}
this.listeners_ = [
google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
this.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseover", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) {
if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {
this.style.cursor = me.marker_.getCursor();
google.maps.event.trigger(me.marker_, "mouseout", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) {
cDraggingLabel = false;
if (me.marker_.getDraggable()) {
cMouseIsDown = true;
this.style.cursor = cDraggingCursor;
}
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "mousedown", e);
cAbortEvent(e); // Prevent map pan when starting a drag on a label
}
}),
google.maps.event.addDomListener(document, "mouseup", function (mEvent) {
var position;
if (cMouseIsDown) {
cMouseIsDown = false;
me.eventDiv_.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseup", mEvent);
}
if (cDraggingLabel) {
if (cRaiseEnabled) { // Lower the marker & label
position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());
position.y += cRaiseOffset;
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
// This is not the same bouncing style as when the marker portion is dragged,
// but it will have to do:
try { // Will fail if running Google Maps API earlier than V3.3
me.marker_.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(cStopBounce, 1406);
} catch (e) {}
}
me.crossDiv_.style.display = "none";
me.marker_.setZIndex(cSavedZIndex);
cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag
cDraggingLabel = false;
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragend", mEvent);
}
}),
google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) {
var position;
if (cMouseIsDown) {
if (cDraggingLabel) {
// Change the reported location from the mouse position to the marker position:
mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);
position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);
if (cRaiseEnabled) {
me.crossDiv_.style.left = position.x + "px";
me.crossDiv_.style.top = position.y + "px";
me.crossDiv_.style.display = "";
position.y -= cRaiseOffset;
}
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly
me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px";
}
google.maps.event.trigger(me.marker_, "drag", mEvent);
} else {
// Calculate offsets from the click point to the marker position:
cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();
cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();
cSavedZIndex = me.marker_.getZIndex();
cStartPosition = me.marker_.getPosition();
cStartCenter = me.marker_.getMap().getCenter();
cRaiseEnabled = me.marker_.get("raiseOnDrag");
cDraggingLabel = true;
me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragstart", mEvent);
}
}
}),
google.maps.event.addDomListener(document, "keydown", function (e) {
if (cDraggingLabel) {
if (e.keyCode === 27) { // Esc key
cRaiseEnabled = false;
me.marker_.setPosition(cStartPosition);
me.marker_.getMap().setCenter(cStartCenter);
google.maps.event.trigger(document, "mouseup", e);
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "click", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
if (cIgnoreClick) { // Ignore the click reported when a label drag ends
cIgnoreClick = false;
} else {
google.maps.event.trigger(me.marker_, "click", e);
cAbortEvent(e); // Prevent click from being passed on to map
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "dblclick", e);
cAbortEvent(e); // Prevent map zoom when double-clicking on a label
}
}),
google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) {
if (!cDraggingLabel) {
cRaiseEnabled = this.get("raiseOnDrag");
}
}),
google.maps.event.addListener(this.marker_, "drag", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(cRaiseOffset);
// During a drag, the marker's z-index is temporarily set to 1000000 to
// ensure it appears above all other markers. Also set the label's z-index
// to 1000000 (plus or minus 1 depending on whether the label is supposed
// to be above or below the marker).
me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1);
}
}
}),
google.maps.event.addListener(this.marker_, "dragend", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(0); // Also restores z-index of label
}
}
}),
google.maps.event.addListener(this.marker_, "position_changed", function () {
me.setPosition();
}),
google.maps.event.addListener(this.marker_, "zindex_changed", function () {
me.setZIndex();
}),
google.maps.event.addListener(this.marker_, "visible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "labelvisible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "title_changed", function () {
me.setTitle();
}),
google.maps.event.addListener(this.marker_, "labelcontent_changed", function () {
me.setContent();
}),
google.maps.event.addListener(this.marker_, "labelanchor_changed", function () {
me.setAnchor();
}),
google.maps.event.addListener(this.marker_, "labelclass_changed", function () {
me.setStyles();
}),
google.maps.event.addListener(this.marker_, "labelstyle_changed", function () {
me.setStyles();
})
];
};
/**
* Removes the DIV for the label from the DOM. It also removes all event handlers.
* This method is called automatically when the marker's <code>setMap(null)</code>
* method is called.
* @private
*/
MarkerLabel_.prototype.onRemove = function () {
var i;
this.labelDiv_.parentNode.removeChild(this.labelDiv_);
this.eventDiv_.parentNode.removeChild(this.eventDiv_);
// Remove event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
/**
* Draws the label on the map.
* @private
*/
MarkerLabel_.prototype.draw = function () {
this.setContent();
this.setTitle();
this.setStyles();
};
/**
* Sets the content of the label.
* The content can be plain text or an HTML DOM node.
* @private
*/
MarkerLabel_.prototype.setContent = function () {
var content = this.marker_.get("labelContent");
if (typeof content.nodeType === "undefined") {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
} else {
this.labelDiv_.innerHTML = ""; // Remove current content
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.eventDiv_.innerHTML = ""; // Remove current content
this.eventDiv_.appendChild(content);
}
};
/**
* Sets the content of the tool tip for the label. It is
* always set to be the same as for the marker itself.
* @private
*/
MarkerLabel_.prototype.setTitle = function () {
this.eventDiv_.title = this.marker_.getTitle() || "";
};
/**
* Sets the style of the label by setting the style sheet and applying
* other specific styles requested.
* @private
*/
MarkerLabel_.prototype.setStyles = function () {
var i, labelStyle;
// Apply style values from the style sheet defined in the labelClass parameter:
this.labelDiv_.className = this.marker_.get("labelClass");
this.eventDiv_.className = this.labelDiv_.className;
// Clear existing inline style values:
this.labelDiv_.style.cssText = "";
this.eventDiv_.style.cssText = "";
// Apply style values defined in the labelStyle parameter:
labelStyle = this.marker_.get("labelStyle");
for (i in labelStyle) {
if (labelStyle.hasOwnProperty(i)) {
this.labelDiv_.style[i] = labelStyle[i];
this.eventDiv_.style[i] = labelStyle[i];
}
}
this.setMandatoryStyles();
};
/**
* Sets the mandatory styles to the DIV representing the label as well as to the
* associated event DIV. This includes setting the DIV position, z-index, and visibility.
* @private
*/
MarkerLabel_.prototype.setMandatoryStyles = function () {
this.labelDiv_.style.position = "absolute";
this.labelDiv_.style.overflow = "hidden";
// Make sure the opacity setting causes the desired effect on MSIE:
if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") {
this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\"";
this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")";
}
this.eventDiv_.style.position = this.labelDiv_.style.position;
this.eventDiv_.style.overflow = this.labelDiv_.style.overflow;
this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE
this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\"";
this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE
this.setAnchor();
this.setPosition(); // This also updates z-index, if necessary.
this.setVisible();
};
/**
* Sets the anchor point of the label.
* @private
*/
MarkerLabel_.prototype.setAnchor = function () {
var anchor = this.marker_.get("labelAnchor");
this.labelDiv_.style.marginLeft = -anchor.x + "px";
this.labelDiv_.style.marginTop = -anchor.y + "px";
this.eventDiv_.style.marginLeft = -anchor.x + "px";
this.eventDiv_.style.marginTop = -anchor.y + "px";
};
/**
* Sets the position of the label. The z-index is also updated, if necessary.
* @private
*/
MarkerLabel_.prototype.setPosition = function (yOffset) {
var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());
if (typeof yOffset === "undefined") {
yOffset = 0;
}
this.labelDiv_.style.left = Math.round(position.x) + "px";
this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px";
this.eventDiv_.style.left = this.labelDiv_.style.left;
this.eventDiv_.style.top = this.labelDiv_.style.top;
this.setZIndex();
};
/**
* Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index
* of the label is set to the vertical coordinate of the label. This is in keeping with the default
* stacking order for Google Maps: markers to the south are in front of markers to the north.
* @private
*/
MarkerLabel_.prototype.setZIndex = function () {
var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1);
if (typeof this.marker_.getZIndex() === "undefined") {
this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
} else {
this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
}
};
/**
* Sets the visibility of the label. The label is visible only if the marker itself is
* visible (i.e., its visible property is true) and the labelVisible property is true.
* @private
*/
MarkerLabel_.prototype.setVisible = function () {
if (this.marker_.get("labelVisible")) {
this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none";
} else {
this.labelDiv_.style.display = "none";
}
this.eventDiv_.style.display = this.labelDiv_.style.display;
};
/**
* @name MarkerWithLabelOptions
* @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.
* The properties available are the same as for <code>google.maps.Marker</code> with the addition
* of the properties listed below. To change any of these additional properties after the labeled
* marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>.
* <p>
* When any of these properties changes, a property changed event is fired. The names of these
* events are derived from the name of the property and are of the form <code>propertyname_changed</code>.
* For example, if the content of the label changes, a <code>labelcontent_changed</code> event
* is fired.
* <p>
* @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).
* @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so
* that its top left corner is positioned at the anchor point of the associated marker. Use this
* property to change the anchor point of the label. For example, to center a 50px-wide label
* beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>.
* (Note: x-values increase to the right and y-values increase to the top.)
* @property {string} [labelClass] The name of the CSS class defining the styles for the label.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {Object} [labelStyle] An object literal whose properties define specific CSS
* style values to be applied to the label. Style values defined here override those that may
* be defined in the <code>labelClass</code> style sheet. If this property is changed after the
* label has been created, all previously set styles (except those defined in the style sheet)
* are removed from the label before the new style values are applied.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its
* associated marker should appear in the background (i.e., in a plane below the marker).
* The default is <code>false</code>, which causes the label to appear in the foreground.
* @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.
* The default is <code>true</code>. Note that even if <code>labelVisible</code> is
* <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also
* visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>).
* @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be
* raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is
* being created and a version of Google Maps API earlier than V3.3 is being used, this property
* must be set to <code>false</code>.
* @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the
* marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel,
* so the value of this parameter is always forced to <code>false</code>.
* @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"]
* The URL of the cross image to be displayed while dragging a marker.
* @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"]
* The URL of the cursor to be displayed while dragging a marker.
*/
/**
* Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.
* @constructor
* @param {MarkerWithLabelOptions} [opt_options] The optional parameters.
*/
function MarkerWithLabel(opt_options) {
opt_options = opt_options || {};
opt_options.labelContent = opt_options.labelContent || "";
opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);
opt_options.labelClass = opt_options.labelClass || "markerLabels";
opt_options.labelStyle = opt_options.labelStyle || {};
opt_options.labelInBackground = opt_options.labelInBackground || false;
if (typeof opt_options.labelVisible === "undefined") {
opt_options.labelVisible = true;
}
if (typeof opt_options.raiseOnDrag === "undefined") {
opt_options.raiseOnDrag = true;
}
if (typeof opt_options.clickable === "undefined") {
opt_options.clickable = true;
}
if (typeof opt_options.draggable === "undefined") {
opt_options.draggable = false;
}
if (typeof opt_options.optimized === "undefined") {
opt_options.optimized = false;
}
opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png";
opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur";
opt_options.optimized = false; // Optimized rendering is not supported
this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker
// Call the parent constructor. It calls Marker.setValues to initialize, so all
// the new parameters are conveniently saved and can be accessed with get/set.
// Marker.set triggers a property changed event (called "propertyname_changed")
// that the marker label listens for in order to react to state changes.
google.maps.Marker.apply(this, arguments);
}
inherits(MarkerWithLabel, google.maps.Marker);
/**
* Overrides the standard Marker setMap function.
* @param {Map} theMap The map to which the marker is to be added.
* @private
*/
MarkerWithLabel.prototype.setMap = function (theMap) {
// Call the inherited function...
google.maps.Marker.prototype.setMap.apply(this, arguments);
// ... then deal with the label:
this.label.setMap(theMap);
};
//END REPLACE
window.InfoBox = InfoBox;
window.Cluster = Cluster;
window.ClusterIcon = ClusterIcon;
window.MarkerClusterer = MarkerClusterer;
window.MarkerLabel_ = MarkerLabel_;
window.MarkerWithLabel = MarkerWithLabel;
})
};
});
;/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapDataStructures', function() {
return {
Graph: __webpack_require__(1).Graph,
Queue: __webpack_require__(1).Queue
};
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
(function() {
module.exports = {
Graph: __webpack_require__(2),
Heap: __webpack_require__(3),
LinkedList: __webpack_require__(4),
Map: __webpack_require__(5),
Queue: __webpack_require__(6),
RedBlackTree: __webpack_require__(7),
Trie: __webpack_require__(8)
};
}).call(this);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/*
Graph implemented as a modified incidence list. O(1) for every typical
operation except `removeNode()` at O(E) where E is the number of edges.
## Overview example:
```js
var graph = new Graph;
graph.addNode('A'); // => a node object. For more info, log the output or check
// the documentation for addNode
graph.addNode('B');
graph.addNode('C');
graph.addEdge('A', 'C'); // => an edge object
graph.addEdge('A', 'B');
graph.getEdge('B', 'A'); // => undefined. Directed edge!
graph.getEdge('A', 'B'); // => the edge object previously added
graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property
// of an edge object. Feel free to attach
// other properties
graph.getInEdgesOf('B'); // => array of edge objects, in this case only one;
// connecting A to B
graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C
graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward
// the node itself are only counted once
forEachNode(function(nodeObject) {
console.log(node);
});
forEachEdge(function(edgeObject) {
console.log(edgeObject);
});
graph.removeNode('C'); // => 'C'. The edge between A and C also removed
graph.removeEdge('A', 'B'); // => the edge object removed
```
## Properties:
- nodeSize: total number of nodes.
- edgeSize: total number of edges.
*/
(function() {
var Graph,
__hasProp = {}.hasOwnProperty;
Graph = (function() {
function Graph() {
this._nodes = {};
this.nodeSize = 0;
this.edgeSize = 0;
}
Graph.prototype.addNode = function(id) {
/*
The `id` is a unique identifier for the node, and should **not** change
after it's added. It will be used for adding, retrieving and deleting
related edges too.
**Note** that, internally, the ids are kept in an object. JavaScript's
object hashes the id `'2'` and `2` to the same key, so please stick to a
simple id data type such as number or string.
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs. **Undefined if node id already exists**,
as to avoid accidental overrides.
*/
if (!this._nodes[id]) {
this.nodeSize++;
return this._nodes[id] = {
_outEdges: {},
_inEdges: {}
};
}
};
Graph.prototype.getNode = function(id) {
/*
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs.
*/
return this._nodes[id];
};
Graph.prototype.removeNode = function(id) {
/*
_Returns:_ the node object removed, or undefined if it didn't exist in the
first place.
*/
var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1;
nodeToRemove = this._nodes[id];
if (!nodeToRemove) {
return;
} else {
_ref = nodeToRemove._outEdges;
for (outEdgeId in _ref) {
if (!__hasProp.call(_ref, outEdgeId)) continue;
this.removeEdge(id, outEdgeId);
}
_ref1 = nodeToRemove._inEdges;
for (inEdgeId in _ref1) {
if (!__hasProp.call(_ref1, inEdgeId)) continue;
this.removeEdge(inEdgeId, id);
}
this.nodeSize--;
delete this._nodes[id];
}
return nodeToRemove;
};
Graph.prototype.addEdge = function(fromId, toId, weight) {
var edgeToAdd, fromNode, toNode;
if (weight == null) {
weight = 1;
}
/*
`fromId` and `toId` are the node id specified when it was created using
`addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively
makes this an unweighted graph. Under the hood, `weight` is just a normal
property of the edge object.
_Returns:_ the edge object created. Feel free to attach additional custom
properties on it for graph algorithms' needs. **Or undefined** if the nodes
of id `fromId` or `toId` aren't found, or if an edge already exists between
the two nodes.
*/
if (this.getEdge(fromId, toId)) {
return;
}
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
return;
}
edgeToAdd = {
weight: weight
};
fromNode._outEdges[toId] = edgeToAdd;
toNode._inEdges[fromId] = edgeToAdd;
this.edgeSize++;
return edgeToAdd;
};
Graph.prototype.getEdge = function(fromId, toId) {
/*
_Returns:_ the edge object, or undefined if the nodes of id `fromId` or
`toId` aren't found.
*/
var fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
} else {
return fromNode._outEdges[toId];
}
};
Graph.prototype.removeEdge = function(fromId, toId) {
/*
_Returns:_ the edge object removed, or undefined of edge wasn't found.
*/
var edgeToDelete, fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
edgeToDelete = this.getEdge(fromId, toId);
if (!edgeToDelete) {
return;
}
delete fromNode._outEdges[toId];
delete toNode._inEdges[fromId];
this.edgeSize--;
return edgeToDelete;
};
Graph.prototype.getInEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that are directed toward the node, or
empty array if no such edge or node exists.
*/
var fromId, inEdges, toNode, _ref;
toNode = this._nodes[nodeId];
inEdges = [];
_ref = toNode != null ? toNode._inEdges : void 0;
for (fromId in _ref) {
if (!__hasProp.call(_ref, fromId)) continue;
inEdges.push(this.getEdge(fromId, nodeId));
}
return inEdges;
};
Graph.prototype.getOutEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that go out of the node, or empty array
if no such edge or node exists.
*/
var fromNode, outEdges, toId, _ref;
fromNode = this._nodes[nodeId];
outEdges = [];
_ref = fromNode != null ? fromNode._outEdges : void 0;
for (toId in _ref) {
if (!__hasProp.call(_ref, toId)) continue;
outEdges.push(this.getEdge(nodeId, toId));
}
return outEdges;
};
Graph.prototype.getAllEdgesOf = function(nodeId) {
/*
**Note:** not the same as concatenating `getInEdgesOf()` and
`getOutEdgesOf()`. Some nodes might have an edge pointing toward itself.
This method solves that duplication.
_Returns:_ an array of edge objects linked to the node, no matter if they're
outgoing or coming. Duplicate edge created by self-pointing nodes are
removed. Only one copy stays. Empty array if node has no edge.
*/
var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1;
inEdges = this.getInEdgesOf(nodeId);
outEdges = this.getOutEdgesOf(nodeId);
if (inEdges.length === 0) {
return outEdges;
}
selfEdge = this.getEdge(nodeId, nodeId);
for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (inEdges[i] === selfEdge) {
_ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1];
inEdges.pop();
break;
}
}
return inEdges.concat(outEdges);
};
Graph.prototype.forEachNode = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each node once.
Pass a function of the form `fn(nodeObject, nodeId)`.
_Returns:_ undefined.
*/
var nodeId, nodeObject, _ref;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
operation(nodeObject, nodeId);
}
};
Graph.prototype.forEachEdge = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each edge once.
Pass a function of the form `fn(edgeObject)`.
_Returns:_ undefined.
*/
var edgeObject, nodeId, nodeObject, toId, _ref, _ref1;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
_ref1 = nodeObject._outEdges;
for (toId in _ref1) {
if (!__hasProp.call(_ref1, toId)) continue;
edgeObject = _ref1[toId];
operation(edgeObject);
}
}
};
return Graph;
})();
module.exports = Graph;
}).call(this);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/*
Minimum heap, i.e. smallest node at root.
**Note:** does not accept null or undefined. This is by design. Those values
cause comparison problems and might report false negative during extraction.
## Overview example:
```js
var heap = new Heap([5, 6, 3, 4]);
heap.add(10); // => 10
heap.removeMin(); // => 3
heap.peekMin(); // => 4
```
## Properties:
- size: total number of items.
*/
(function() {
var Heap, _leftChild, _parent, _rightChild;
Heap = (function() {
function Heap(dataToHeapify) {
var i, item, _i, _j, _len, _ref;
if (dataToHeapify == null) {
dataToHeapify = [];
}
/*
Pass an optional array to be heapified. Takes only O(n) time.
*/
this._data = [void 0];
for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) {
item = dataToHeapify[_i];
if (item != null) {
this._data.push(item);
}
}
if (this._data.length > 1) {
for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) {
this._upHeap(i);
}
}
this.size = this._data.length - 1;
}
Heap.prototype.add = function(value) {
/*
**Remember:** rejects null and undefined for mentioned reasons.
_Returns:_ the value added.
*/
if (value == null) {
return;
}
this._data.push(value);
this._upHeap(this._data.length - 1);
this.size++;
return value;
};
Heap.prototype.removeMin = function() {
/*
_Returns:_ the smallest item (the root).
*/
var min;
if (this._data.length === 1) {
return;
}
this.size--;
if (this._data.length === 2) {
return this._data.pop();
}
min = this._data[1];
this._data[1] = this._data.pop();
this._downHeap();
return min;
};
Heap.prototype.peekMin = function() {
/*
Check the smallest item without removing it.
_Returns:_ the smallest item (the root).
*/
return this._data[1];
};
Heap.prototype._upHeap = function(index) {
var valueHolder, _ref;
valueHolder = this._data[index];
while (this._data[index] < this._data[_parent(index)] && index > 1) {
_ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1];
index = _parent(index);
}
};
Heap.prototype._downHeap = function() {
var currentIndex, smallerChildIndex, _ref;
currentIndex = 1;
while (_leftChild(currentIndex < this._data.length)) {
smallerChildIndex = _leftChild(currentIndex);
if (smallerChildIndex < this._data.length - 1) {
if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) {
smallerChildIndex = _rightChild(currentIndex);
}
}
if (this._data[smallerChildIndex] < this._data[currentIndex]) {
_ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1];
currentIndex = smallerChildIndex;
} else {
break;
}
}
};
return Heap;
})();
_parent = function(index) {
return index >> 1;
};
_leftChild = function(index) {
return index << 1;
};
_rightChild = function(index) {
return (index << 1) + 1;
};
module.exports = Heap;
}).call(this);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
Doubly Linked.
## Overview example:
```js
var list = new LinkedList([5, 4, 9]);
list.add(12); // => 12
list.head.next.value; // => 4
list.tail.value; // => 12
list.at(-1); // => 12
list.removeAt(2); // => 9
list.remove(4); // => 4
list.indexOf(5); // => 0
list.add(5, 1); // => 5. Second 5 at position 1.
list.indexOf(5, 1); // => 1
```
## Properties:
- head: first item.
- tail: last item.
- size: total number of items.
- item.value: value passed to the item when calling `add()`.
- item.prev: previous item.
- item.next: next item.
*/
(function() {
var LinkedList;
LinkedList = (function() {
function LinkedList(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Can pass an array of elements to link together during `new LinkedList()`
initiation.
*/
this.head = {
prev: void 0,
value: void 0,
next: void 0
};
this.tail = {
prev: void 0,
value: void 0,
next: void 0
};
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
this.add(value);
}
}
LinkedList.prototype.at = function(position) {
/*
Get the item at `position` (optional). Accepts negative index:
```js
myList.at(-1); // Returns the last element.
```
However, passing a negative index that surpasses the boundary will return
undefined:
```js
myList = new LinkedList([2, 6, 8, 3])
myList.at(-5); // Undefined.
myList.at(-4); // 2.
```
_Returns:_ item gotten, or undefined if not found.
*/
var currentNode, i, _i, _j, _ref;
if (!((-this.size <= position && position < this.size))) {
return;
}
position = this._adjust(position);
if (position * 2 < this.size) {
currentNode = this.head;
for (i = _i = 1; _i <= position; i = _i += 1) {
currentNode = currentNode.next;
}
} else {
currentNode = this.tail;
for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) {
currentNode = currentNode.prev;
}
}
return currentNode;
};
LinkedList.prototype.add = function(value, position) {
var currentNode, nodeToAdd, _ref, _ref1, _ref2;
if (position == null) {
position = this.size;
}
/*
Add a new item at `position` (optional). Defaults to adding at the end.
`position`, just like in `at()`, can be negative (within the negative
boundary). Position specifies the place the value's going to be, and the old
node will be pushed higher. `add(-2)` on list of size 7 is the same as
`add(5)`.
_Returns:_ item added.
*/
if (!((-this.size <= position && position <= this.size))) {
return;
}
nodeToAdd = {
value: value
};
position = this._adjust(position);
if (this.size === 0) {
this.head = nodeToAdd;
} else {
if (position === 0) {
_ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2];
} else {
currentNode = this.at(position - 1);
_ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3];
}
}
if (position === this.size) {
this.tail = nodeToAdd;
}
this.size++;
return value;
};
LinkedList.prototype.removeAt = function(position) {
var currentNode, valueToReturn, _ref;
if (position == null) {
position = this.size - 1;
}
/*
Remove an item at index `position` (optional). Defaults to the last item.
Index can be negative (within the boundary).
_Returns:_ item removed.
*/
if (!((-this.size <= position && position < this.size))) {
return;
}
if (this.size === 0) {
return;
}
position = this._adjust(position);
if (this.size === 1) {
valueToReturn = this.head.value;
this.head.value = this.tail.value = void 0;
} else {
if (position === 0) {
valueToReturn = this.head.value;
this.head = this.head.next;
this.head.prev = void 0;
} else {
currentNode = this.at(position);
valueToReturn = currentNode.value;
currentNode.prev.next = currentNode.next;
if ((_ref = currentNode.next) != null) {
_ref.prev = currentNode.prev;
}
if (position === this.size - 1) {
this.tail = currentNode.prev;
}
}
}
this.size--;
return valueToReturn;
};
LinkedList.prototype.remove = function(value) {
/*
Remove the item using its value instead of position. **Will remove the fist
occurrence of `value`.**
_Returns:_ the value, or undefined if value's not found.
*/
var currentNode;
if (value == null) {
return;
}
currentNode = this.head;
while (currentNode && currentNode.value !== value) {
currentNode = currentNode.next;
}
if (!currentNode) {
return;
}
if (this.size === 1) {
this.head.value = this.tail.value = void 0;
} else if (currentNode === this.head) {
this.head = this.head.next;
this.head.prev = void 0;
} else if (currentNode === this.tail) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else {
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
}
this.size--;
return value;
};
LinkedList.prototype.indexOf = function(value, startingPosition) {
var currentNode, position;
if (startingPosition == null) {
startingPosition = 0;
}
/*
Find the index of an item, similarly to `array.indexOf()`. Defaults to start
searching from the beginning, by can start at another position by passing
`startingPosition`. This parameter can also be negative; but unlike the
other methods of this class, `startingPosition` (optional) can be as small
as desired; a value of -999 for a list of size 5 will start searching
normally, at the beginning.
**Note:** searches forwardly, **not** backwardly, i.e:
```js
var myList = new LinkedList([2, 3, 1, 4, 3, 5])
myList.indexOf(3, -3); // Returns 4, not 1
```
_Returns:_ index of item found, or -1 if not found.
*/
if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) {
return -1;
}
startingPosition = Math.max(0, this._adjust(startingPosition));
currentNode = this.at(startingPosition);
position = startingPosition;
while (currentNode) {
if (currentNode.value === value) {
break;
}
currentNode = currentNode.next;
position++;
}
if (position === this.size) {
return -1;
} else {
return position;
}
};
LinkedList.prototype._adjust = function(position) {
if (position < 0) {
return this.size + position;
} else {
return position;
}
};
return LinkedList;
})();
module.exports = LinkedList;
}).call(this);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/*
Kind of a stopgap measure for the upcoming [JavaScript
Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets)
**Note:** due to JavaScript's limitations, hashing something other than Boolean,
Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a
hidden unique property into the object. This means `set`, `get`, `has` and
`delete` must employ the same object, and not a mere identical copy as in the
case of, say, a string.
## Overview example:
```js
var map = new Map({'alice': 'wonderland', 20: 'ok'});
map.set('20', 5); // => 5
map.get('20'); // => 5
map.has('alice'); // => true
map.delete(20) // => true
var arr = [1, 2];
map.add(arr, 'goody'); // => 'goody'
map.has(arr); // => true
map.has([1, 2]); // => false. Needs to compare by reference
map.forEach(function(key, value) {
console.log(key, value);
});
```
## Properties:
- size: The total number of `(key, value)` pairs.
*/
(function() {
var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType,
__hasProp = {}.hasOwnProperty;
SPECIAL_TYPE_KEY_PREFIX = '_mapId_';
Map = (function() {
Map._mapIdTracker = 0;
Map._newMapId = function() {
return this._mapIdTracker++;
};
function Map(objectToMap) {
/*
Pass an optional object whose (key, value) pair will be hashed. **Careful**
not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's
native object behavior will crush the first 5 property before it gets to
constructor.
*/
var key, value;
this._content = {};
this._itemId = 0;
this._id = Map._newMapId();
this.size = 0;
for (key in objectToMap) {
if (!__hasProp.call(objectToMap, key)) continue;
value = objectToMap[key];
this.set(key, value);
}
}
Map.prototype.hash = function(key, makeHash) {
var propertyForMap, type;
if (makeHash == null) {
makeHash = false;
}
/*
The hash function for hashing keys is public. Feel free to replace it with
your own. The `makeHash` parameter is optional and accepts a boolean
(defaults to `false`) indicating whether or not to produce a new hash (for
the first use, naturally).
_Returns:_ the hash.
*/
type = _extractDataType(key);
if (_isSpecialType(key)) {
propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id;
if (makeHash && !key[propertyForMap]) {
key[propertyForMap] = this._itemId++;
}
return propertyForMap + '_' + key[propertyForMap];
} else {
return type + '_' + key;
}
};
Map.prototype.set = function(key, value) {
/*
_Returns:_ value.
*/
if (!this.has(key)) {
this.size++;
}
this._content[this.hash(key, true)] = [value, key];
return value;
};
Map.prototype.get = function(key) {
/*
_Returns:_ value corresponding to the key, or undefined if not found.
*/
var _ref;
return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0;
};
Map.prototype.has = function(key) {
/*
Check whether a value exists for the key.
_Returns:_ true or false.
*/
return this.hash(key) in this._content;
};
Map.prototype["delete"] = function(key) {
/*
Remove the (key, value) pair.
_Returns:_ **true or false**. Unlike most of this library, this method
doesn't return the deleted value. This is so that it conforms to the future
JavaScript `map.delete()`'s behavior.
*/
var hashedKey;
hashedKey = this.hash(key);
if (hashedKey in this._content) {
delete this._content[hashedKey];
if (_isSpecialType(key)) {
delete key[SPECIAL_TYPE_KEY_PREFIX + this._id];
}
this.size--;
return true;
}
return false;
};
Map.prototype.forEach = function(operation) {
/*
Traverse through the map. Pass a function of the form `fn(key, value)`.
_Returns:_ undefined.
*/
var key, value, _ref;
_ref = this._content;
for (key in _ref) {
if (!__hasProp.call(_ref, key)) continue;
value = _ref[key];
operation(value[1], value[0]);
}
};
return Map;
})();
_isSpecialType = function(key) {
var simpleHashableTypes, simpleType, type, _i, _len;
simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function'];
type = _extractDataType(key);
for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) {
simpleType = simpleHashableTypes[_i];
if (type === simpleType) {
return false;
}
}
return true;
};
_extractDataType = function(type) {
return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1];
};
module.exports = Map;
}).call(this);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*
Amortized O(1) dequeue!
## Overview example:
```js
var queue = new Queue([1, 6, 4]);
queue.enqueue(10); // => 10
queue.dequeue(); // => 1
queue.dequeue(); // => 6
queue.dequeue(); // => 4
queue.peek(); // => 10
queue.dequeue(); // => 10
queue.peek(); // => undefined
```
## Properties:
- size: The total number of items.
*/
(function() {
var Queue;
Queue = (function() {
function Queue(initialArray) {
if (initialArray == null) {
initialArray = [];
}
/*
Pass an optional array to be transformed into a queue. The item at index 0
is the first to be dequeued.
*/
this._content = initialArray;
this._dequeueIndex = 0;
this.size = this._content.length;
}
Queue.prototype.enqueue = function(item) {
/*
_Returns:_ the item.
*/
this.size++;
this._content.push(item);
return item;
};
Queue.prototype.dequeue = function() {
/*
_Returns:_ the dequeued item.
*/
var itemToDequeue;
if (this.size === 0) {
return;
}
this.size--;
itemToDequeue = this._content[this._dequeueIndex];
this._dequeueIndex++;
if (this._dequeueIndex * 2 > this._content.length) {
this._content = this._content.slice(this._dequeueIndex);
this._dequeueIndex = 0;
}
return itemToDequeue;
};
Queue.prototype.peek = function() {
/*
Check the next item to be dequeued, without removing it.
_Returns:_ the item.
*/
return this._content[this._dequeueIndex];
};
return Queue;
})();
module.exports = Queue;
}).call(this);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*
Credit to Wikipedia's article on [Red-black
tree](http://en.wikipedia.org/wiki/Red–black_tree)
**Note:** doesn't handle duplicate entries, undefined and null. This is by
design.
## Overview example:
```js
var rbt = new RedBlackTree([7, 5, 1, 8]);
rbt.add(2); // => 2
rbt.add(10); // => 10
rbt.has(5); // => true
rbt.peekMin(); // => 1
rbt.peekMax(); // => 10
rbt.removeMin(); // => 1
rbt.removeMax(); // => 10
rbt.remove(8); // => 8
```
## Properties:
- size: The total number of items.
*/
(function() {
var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf;
NODE_FOUND = 0;
NODE_TOO_BIG = 1;
NODE_TOO_SMALL = 2;
STOP_SEARCHING = 3;
RED = 1;
BLACK = 2;
RedBlackTree = (function() {
function RedBlackTree(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Pass an optional array to be turned into binary tree. **Note:** does not
accept duplicate, undefined and null.
*/
this._root;
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
if (value != null) {
this.add(value);
}
}
}
RedBlackTree.prototype.add = function(value) {
/*
Again, make sure to not pass a value already in the tree, or undefined, or
null.
_Returns:_ value added.
*/
var currentNode, foundNode, nodeToInsert, _ref;
if (value == null) {
return;
}
this.size++;
nodeToInsert = {
value: value,
_color: RED
};
if (!this._root) {
this._root = nodeToInsert;
} else {
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else {
if (value < node.value) {
if (node._left) {
return NODE_TOO_BIG;
} else {
nodeToInsert._parent = node;
node._left = nodeToInsert;
return STOP_SEARCHING;
}
} else {
if (node._right) {
return NODE_TOO_SMALL;
} else {
nodeToInsert._parent = node;
node._right = nodeToInsert;
return STOP_SEARCHING;
}
}
}
});
if (foundNode != null) {
return;
}
}
currentNode = nodeToInsert;
while (true) {
if (currentNode === this._root) {
currentNode._color = BLACK;
break;
}
if (currentNode._parent._color === BLACK) {
break;
}
if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) {
currentNode._parent._color = BLACK;
_uncleOf(currentNode)._color = BLACK;
_grandParentOf(currentNode)._color = RED;
currentNode = _grandParentOf(currentNode);
continue;
}
if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) {
this._rotateLeft(currentNode._parent);
currentNode = currentNode._left;
} else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) {
this._rotateRight(currentNode._parent);
currentNode = currentNode._right;
}
currentNode._parent._color = BLACK;
_grandParentOf(currentNode)._color = RED;
if (_isLeft(currentNode)) {
this._rotateRight(_grandParentOf(currentNode));
} else {
this._rotateLeft(_grandParentOf(currentNode));
}
break;
}
return value;
};
RedBlackTree.prototype.has = function(value) {
/*
_Returns:_ true or false.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (foundNode) {
return true;
} else {
return false;
}
};
RedBlackTree.prototype.peekMin = function() {
/*
Check the minimum value without removing it.
_Returns:_ the minimum value.
*/
var _ref;
return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.peekMax = function() {
/*
Check the maximum value without removing it.
_Returns:_ the maximum value.
*/
var _ref;
return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.remove = function(value) {
/*
_Returns:_ the value removed, or undefined if the value's not found.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (!foundNode) {
return;
}
this._removeNode(this._root, foundNode);
this.size--;
return value;
};
RedBlackTree.prototype.removeMin = function() {
/*
_Returns:_ smallest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMinNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype.removeMax = function() {
/*
_Returns:_ biggest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMaxNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype._removeNode = function(root, node) {
var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if (node._left && node._right) {
successor = _peekMinNode(node._right);
node.value = successor.value;
node = successor;
}
successor = node._left || node._right;
if (!successor) {
successor = {
color: BLACK,
_right: void 0,
_left: void 0,
isLeaf: true
};
}
successor._parent = node._parent;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = successor;
}
if (node._color === BLACK) {
if (successor._color === RED) {
successor._color = BLACK;
if (!successor._parent) {
this._root = successor;
}
} else {
while (true) {
if (!successor._parent) {
if (!successor.isLeaf) {
this._root = successor;
} else {
this._root = void 0;
}
break;
}
sibling = _siblingOf(successor);
if ((sibling != null ? sibling._color : void 0) === RED) {
successor._parent._color = RED;
sibling._color = BLACK;
if (_isLeft(successor)) {
this._rotateLeft(successor._parent);
} else {
this._rotateRight(successor._parent);
}
}
sibling = _siblingOf(successor);
if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
if (successor.isLeaf) {
successor._parent[_leftOrRight(successor)] = void 0;
}
successor = successor._parent;
continue;
}
if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
successor._parent._color = BLACK;
break;
}
if ((sibling != null ? sibling._color : void 0) === BLACK) {
if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) {
sibling._color = RED;
if ((_ref4 = sibling._left) != null) {
_ref4._color = BLACK;
}
this._rotateRight(sibling);
} else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) {
sibling._color = RED;
if ((_ref6 = sibling._right) != null) {
_ref6._color = BLACK;
}
this._rotateLeft(sibling);
}
break;
}
sibling = _siblingOf(successor);
sibling._color = successor._parent._color;
if (_isLeft(successor)) {
sibling._right._color = BLACK;
this._rotateRight(successor._parent);
} else {
sibling._left._color = BLACK;
this._rotateLeft(successor._parent);
}
}
}
}
if (successor.isLeaf) {
return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0;
}
};
RedBlackTree.prototype._rotateLeft = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._right;
}
node._right._parent = node._parent;
node._parent = node._right;
node._right = node._right._left;
node._parent._left = node;
if ((_ref1 = node._right) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
RedBlackTree.prototype._rotateRight = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._left;
}
node._left._parent = node._parent;
node._parent = node._left;
node._left = node._left._right;
node._parent._right = node;
if ((_ref1 = node._left) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
return RedBlackTree;
})();
_isLeft = function(node) {
return node === node._parent._left;
};
_leftOrRight = function(node) {
if (_isLeft(node)) {
return '_left';
} else {
return '_right';
}
};
_findNode = function(startingNode, comparator) {
var comparisonResult, currentNode, foundNode;
currentNode = startingNode;
foundNode = void 0;
while (currentNode) {
comparisonResult = comparator(currentNode);
if (comparisonResult === NODE_FOUND) {
foundNode = currentNode;
break;
}
if (comparisonResult === NODE_TOO_BIG) {
currentNode = currentNode._left;
} else if (comparisonResult === NODE_TOO_SMALL) {
currentNode = currentNode._right;
} else if (comparisonResult === STOP_SEARCHING) {
break;
}
}
return foundNode;
};
_peekMinNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._left) {
return NODE_TOO_BIG;
} else {
return NODE_FOUND;
}
});
};
_peekMaxNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._right) {
return NODE_TOO_SMALL;
} else {
return NODE_FOUND;
}
});
};
_grandParentOf = function(node) {
var _ref;
return (_ref = node._parent) != null ? _ref._parent : void 0;
};
_uncleOf = function(node) {
if (!_grandParentOf(node)) {
return;
}
if (_isLeft(node._parent)) {
return _grandParentOf(node)._right;
} else {
return _grandParentOf(node)._left;
}
};
_siblingOf = function(node) {
if (_isLeft(node)) {
return node._parent._right;
} else {
return node._parent._left;
}
};
module.exports = RedBlackTree;
}).call(this);
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/*
Good for fast insertion/removal/lookup of strings.
## Overview example:
```js
var trie = new Trie(['bear', 'beer']);
trie.add('hello'); // => 'hello'
trie.add('helloha!'); // => 'helloha!'
trie.has('bears'); // => false
trie.longestPrefixOf('beatrice'); // => 'bea'
trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!']
trie.remove('beers'); // => undefined. 'beer' still exists
trie.remove('Beer') // => undefined. Case-sensitive
trie.remove('beer') // => 'beer'. Removed
```
## Properties:
- size: The total number of words.
*/
(function() {
var Queue, Trie, WORD_END, _hasAtLeastNChildren,
__hasProp = {}.hasOwnProperty;
Queue = __webpack_require__(6);
WORD_END = 'end';
Trie = (function() {
function Trie(words) {
var word, _i, _len;
if (words == null) {
words = [];
}
/*
Pass an optional array of strings to be inserted initially.
*/
this._root = {};
this.size = 0;
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
this.add(word);
}
}
Trie.prototype.add = function(word) {
/*
Add a whole string to the trie.
_Returns:_ the word added. Will return undefined (without adding the value)
if the word passed is null or undefined.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return;
}
this.size++;
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
currentNode[letter] = {};
}
currentNode = currentNode[letter];
}
currentNode[WORD_END] = true;
return word;
};
Trie.prototype.has = function(word) {
/*
__Returns:_ true or false.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return false;
}
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return false;
}
currentNode = currentNode[letter];
}
if (currentNode[WORD_END]) {
return true;
} else {
return false;
}
};
Trie.prototype.longestPrefixOf = function(word) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
```js
var trie = new Trie;
trie.add('hello');
trie.longestPrefixOf('he'); // 'he'
trie.longestPrefixOf('hello'); // 'hello'
trie.longestPrefixOf('helloha!'); // 'hello'
```
_Returns:_ the prefix string, or empty string if no prefix found.
*/
var currentNode, letter, prefix, _i, _len;
if (word == null) {
return '';
}
currentNode = this._root;
prefix = '';
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
break;
}
prefix += letter;
currentNode = currentNode[letter];
}
return prefix;
};
Trie.prototype.wordsWithPrefix = function(prefix) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
**Watch out for edge cases.**
```js
var trie = new Trie;
trie.wordsWithPrefix(''); // []. Check later case below.
trie.add('');
trie.wordsWithPrefix(''); // ['']
trie.add('he');
trie.add('hello');
trie.add('hell');
trie.add('bear');
trie.add('z');
trie.add('zebra');
trie.wordsWithPrefix('hel'); // ['hell', 'hello']
```
_Returns:_ an array of strings, or empty array if no word found.
*/
var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref;
if (prefix == null) {
return [];
}
(prefix != null) || (prefix = '');
words = [];
currentNode = this._root;
for (_i = 0, _len = prefix.length; _i < _len; _i++) {
letter = prefix[_i];
currentNode = currentNode[letter];
if (currentNode == null) {
return [];
}
}
queue = new Queue();
queue.enqueue([currentNode, '']);
while (queue.size !== 0) {
_ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1];
if (node[WORD_END]) {
words.push(prefix + accumulatedLetters);
}
for (letter in node) {
if (!__hasProp.call(node, letter)) continue;
subNode = node[letter];
queue.enqueue([subNode, accumulatedLetters + letter]);
}
}
return words;
};
Trie.prototype.remove = function(word) {
/*
_Returns:_ the string removed, or undefined if the word in its whole doesn't
exist. **Note:** this means removing `beers` when only `beer` exists will
return undefined and conserve `beer`.
*/
var currentNode, i, letter, prefix, _i, _j, _len, _ref;
if (word == null) {
return;
}
currentNode = this._root;
prefix = [];
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return;
}
currentNode = currentNode[letter];
prefix.push([letter, currentNode]);
}
if (!currentNode[WORD_END]) {
return;
}
this.size--;
delete currentNode[WORD_END];
if (_hasAtLeastNChildren(currentNode, 1)) {
return word;
}
for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) {
if (!_hasAtLeastNChildren(prefix[i][1], 1)) {
delete prefix[i - 1][1][prefix[i][0]];
} else {
break;
}
}
if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) {
delete this._root[prefix[0][0]];
}
return word;
};
return Trie;
})();
_hasAtLeastNChildren = function(node, n) {
var child, childCount;
if (n === 0) {
return true;
}
childCount = 0;
for (child in node) {
if (!__hasProp.call(node, child)) continue;
childCount++;
if (childCount >= n) {
return true;
}
}
return false;
};
module.exports = Trie;
}).call(this);
/***/ }
/******/ ]);;/**
* Performance overrides on MarkerClusterer custom to Angular Google Maps
*
* Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14.
*/
angular.module('uiGmapgoogle-maps.extensions')
.service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) {
return {
init: _.once(function () {
(function () {
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
window.NgMapCluster = (function (_super) {
__extends(NgMapCluster, _super);
function NgMapCluster(opts) {
NgMapCluster.__super__.constructor.call(this, opts);
this.markers_ = new PropMap();
}
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
NgMapCluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
var oldMarker = this.markers_.get(marker.key);
if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
this.markers_.each(function (m) {
m.setMap(null);
});
} else {
marker.setMap(null);
}
//this.updateIcon_();
return true;
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key));
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
NgMapCluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.getMarkers().each(function(m){
bounds.extend(m.getPosition());
});
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
NgMapCluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = new PropMap();
delete this.markers_;
};
return NgMapCluster;
})(Cluster);
window.NgMapMarkerClusterer = (function (_super) {
__extends(NgMapMarkerClusterer, _super);
function NgMapMarkerClusterer(map, opt_markers, opt_options) {
NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options);
this.markers_ = new PropMap();
}
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
NgMapMarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = new PropMap();
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) {
if (!this.markers_.get(marker.key)) {
return false;
}
marker.setMap(null);
this.markers_.remove(marker.key); // Remove the marker from the list of managed markers
return true;
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringbegin', this);
if (typeof this.timerRefStatic !== 'undefined') {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
var _ms = this.markers_.values();
for (i = iFirst; i < iLast; i++) {
marker = _ms[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
// custom addition by ui-gmap
// update icon for all clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].updateIcon_();
}
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringend', this);
}
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new NgMapCluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Redraws all the clusters.
*/
NgMapMarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
this.markers_.each(function (marker) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
});
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
if (property !== 'constructor')
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
////////////////////////////////////////////////////////////////////////////////
/*
Other overrides relevant to MarkerClusterPlus
*/
////////////////////////////////////////////////////////////////////////////////
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
// ADDED FOR RETINA SUPPORT
else {
img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;";
}
// END ADD
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
//END OTHER OVERRIDES
////////////////////////////////////////////////////////////////////////////////
return NgMapMarkerClusterer;
})(MarkerClusterer);
}).call(this);
})
};
}]);
}( window,angular)); |
src/index.js | petercm/measurements-tally | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
assets/jqwidgets/demos/react/app/tree/loadondemandwithxhr/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxTree from '../../../jqwidgets-react/react_jqxtree.js';
class App extends React.Component {
componentDidMount() {
this.refs.myTree.selectItem(document.getElementById('home'));
this.refs.myTree.expandItem(document.getElementById('solutions'));
this.refs.myTree.on('expand', (event) => {
let label = this.refs.myTree.getItem(event.args.element).label;
let element = event.args.element;
let loader = false;
let loaderItem = null;
let children = element.getElementsByTagName('ul')[0].children;
for (let i = 0; i < children.length; i++) {
let item = this.refs.myTree.getItem(children[i]);
if (item && item.label == 'Loading...') {
loaderItem = item;
loader = true;
break;
}
}
if (loader) {
let innerItemRequest = new XMLHttpRequest();
innerItemRequest.open('GET', loaderItem.value, false);
innerItemRequest.setRequestHeader('Content-Type', 'text/json');
innerItemRequest.send(null);
let items = JSON.parse(innerItemRequest.response);
this.refs.myTree.addTo(items, element);
this.refs.myTree.removeItem(loaderItem.element);
}
});
}
render () {
let source = null;
let treeRequest = new XMLHttpRequest();
let url = 'fileroot.htm';
let async = false;
treeRequest.open('GET', url, async);
treeRequest.setRequestHeader('Content-Type', 'text/json');
treeRequest.send(null);
let jsonDataText = treeRequest.response;
if (jsonDataText != undefined) {
source = JSON.parse(jsonDataText);
}
return (
<JqxTree ref='myTree'
source={source} width={200} height={300}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/parser/shared/modules/features/Checklist/Requirement.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import InformationIcon from 'interface/icons/Information';
import { formatNumber, formatPercentage, formatThousands } from 'common/format';
import Tooltip, { TooltipElement } from 'common/Tooltip';
import colorForPerformance from 'common/colorForPerformance';
import performanceForThresholds from './helpers/performanceForThresholds';
import { RuleContext } from './Rule';
class Requirement extends React.PureComponent {
static propTypes = {
name: PropTypes.node.isRequired,
thresholds: PropTypes.object.isRequired,
tooltip: PropTypes.node,
valueTooltip: PropTypes.node,
setPerformance: PropTypes.func,
prefix: PropTypes.node,
suffix: PropTypes.node,
};
constructor(props) {
super(props);
props.setPerformance(this.performance);
}
get performance() {
return performanceForThresholds(this.props.thresholds);
}
formatThresholdsActual(thresholds) {
switch (thresholds.style) {
case 'percentage':
return `${formatPercentage(thresholds.actual)}%`;
case 'number':
return `${formatNumber(thresholds.actual)}`;
case 'thousands':
return `${formatThousands(thresholds.actual)}`;
case 'decimal':
return `${thresholds.actual.toFixed(2)}`;
case 'boolean':
return thresholds.actual ? 'Yes' : 'No';
case 'seconds':
return `${thresholds.actual.toFixed(2)}s`;
case 'absolute':
return `${thresholds.actual}`;
default:
throw new Error(`Unknown style: ${thresholds.style}`);
}
}
render() {
const { name, thresholds, tooltip, valueTooltip, prefix, suffix } = this.props;
const performance = this.performance;
const actual = (
<>
{prefix} {this.formatThresholdsActual(thresholds)} {thresholds.max !== undefined && `/ ${thresholds.max}`} {suffix}
</>
);
return (
<div className="col-md-6">
<div className="flex">
<div className="flex-main">
{name}
</div>
{tooltip && (
<div
className="flex-sub"
style={{ marginLeft: 10 }}
>
<Tooltip content={tooltip}>
<div>
<InformationIcon />
</div>
</Tooltip>
</div>
)}
<div className="flex-sub content-middle text-muted" style={{ minWidth: 55, marginLeft: 5, marginRight: 10 }}>
<div className="text-right" style={{ width: '100%' }}>
{valueTooltip ? <TooltipElement content={valueTooltip}>{actual}</TooltipElement> : actual}
</div>
</div>
<div className="flex-sub content-middle" style={{ width: 50 }}>
<div className="performance-bar-container">
<div
className="performance-bar small"
style={{
width: `${performance * 100}%`,
transition: 'background-color 800ms',
backgroundColor: colorForPerformance(performance),
}}
/>
</div>
</div>
</div>
</div>
);
}
}
export default props => (
<RuleContext.Consumer>
{setPerformance => (
<Requirement
{...props}
setPerformance={setPerformance}
/>
)}
</RuleContext.Consumer>
);
|
Examples/UIExplorer/UIExplorerList.ios.js | tsdl2013/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 {
AppRegistry,
Settings,
StyleSheet,
} = React;
var { TestModule } = React.addons;
import type { NavigationContext } from 'NavigationContext';
var UIExplorerListBase = require('./UIExplorerListBase');
var COMPONENTS = [
require('./ActivityIndicatorIOSExample'),
require('./DatePickerIOSExample'),
require('./ImageExample'),
require('./LayoutEventsExample'),
require('./ListViewExample'),
require('./ListViewGridLayoutExample'),
require('./ListViewPagingExample'),
require('./MapViewExample'),
require('./ModalExample'),
require('./Navigator/NavigatorExample'),
require('./NavigatorIOSColorsExample'),
require('./NavigatorIOSExample'),
require('./PickerIOSExample'),
require('./ProgressViewIOSExample'),
require('./ScrollViewExample'),
require('./SegmentedControlIOSExample'),
require('./SliderIOSExample'),
require('./SwitchIOSExample'),
require('./TabBarIOSExample'),
require('./TextExample.ios'),
require('./TextInputExample.ios'),
require('./TouchableExample'),
require('./ViewExample'),
require('./WebViewExample'),
];
var APIS = [
require('./AccessibilityIOSExample'),
require('./ActionSheetIOSExample'),
require('./AdSupportIOSExample'),
require('./AlertIOSExample'),
require('./AnimatedExample'),
require('./AnimatedGratuitousApp/AnExApp'),
require('./AppStateIOSExample'),
require('./AsyncStorageExample'),
require('./BorderExample'),
require('./CameraRollExample.ios'),
require('./GeolocationExample'),
require('./LayoutExample'),
require('./NetInfoExample'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),
require('./StatusBarIOSExample'),
require('./TimerExample'),
require('./VibrationIOSExample'),
require('./XHRExample.ios'),
require('./ImageEditingExample'),
];
// Register suitable examples for snapshot tests
COMPONENTS.concat(APIS).forEach((Example) => {
if (Example.displayName) {
var Snapshotter = React.createClass({
componentDidMount: function() {
// View is still blank after first RAF :\
global.requestAnimationFrame(() =>
global.requestAnimationFrame(() => TestModule.verifySnapshot(
TestModule.markTestPassed
)
));
},
render: function() {
var Renderable = UIExplorerListBase.makeRenderable(Example);
return <Renderable />;
},
});
AppRegistry.registerComponent(Example.displayName, () => Snapshotter);
}
});
type Props = {
navigator: {
navigationContext: NavigationContext,
push: (route: {title: string, component: ReactClass<any,any,any>}) => void,
},
onExternalExampleRequested: Function,
};
class UIExplorerList extends React.Component {
props: Props;
render() {
return (
<UIExplorerListBase
components={COMPONENTS}
apis={APIS}
searchText={Settings.get('searchText')}
renderAdditionalView={this.renderAdditionalView.bind(this)}
search={this.search.bind(this)}
onPressRow={this.onPressRow.bind(this)}
/>
);
}
renderAdditionalView(renderRow: Function, renderTextInput: Function): React.Component {
return renderTextInput(styles.searchTextInput);
}
search(text: mixed) {
Settings.set({searchText: text});
}
_openExample(example: any) {
if (example.external) {
this.props.onExternalExampleRequested(example);
return;
}
var Component = UIExplorerListBase.makeRenderable(example);
this.props.navigator.push({
title: Component.title,
component: Component,
});
}
onPressRow(example: any) {
this._openExample(example);
}
}
var styles = StyleSheet.create({
searchTextInput: {
height: 30,
},
});
module.exports = UIExplorerList;
|
src/components/RandomSticker.js | aalselius/Test | import React, { Component } from 'react';
import Image from './Image.js';
import Button from './Button.js';
import InfoText from './InfoText.js';
import Header from './Header.js';
class RandomSticker extends Component {
constructor() {
super();
this.state = {
imageUrl: '',
url:'',
inputType: '',
imageNumber: 0,
json:'',
images:[],
text: 'cat',
loaded: false,
}
}
componentDidMount() {
this.url = "http://api.giphy.com/v1/stickers/random?api_key=dc6zaTOxFJmzC";
console.log(this.url);
fetch(this.url)
.then((data) => {
return data.json();
})
.then((json) => {
console.log(json);
this.setState({json:json});
this.setState({imageUrl:this.state.json.data.fixed_height_downsampled_url});
this.setState({loaded: true});
})
;
}
newPicture = () => {
this.setState({url: "http://api.giphy.com/v1/stickers/random?api_key=dc6zaTOxFJmzC"});
console.log(this.url);
fetch(this.url)
.then((data) => {
return data.json();
})
.then((json) => {
console.log(json);
this.setState({json:json});
this.setState({imageUrl:this.state.json.data.fixed_height_downsampled_url});
})
;
}
render() {
return (
<div className="pageContainer">
<Header headerText="Random Sticker" headerClass="sideHeader"/>
{this.state.loaded ? (
<div className="imageContainer imageContainer2">
<Image url={this.state.imageUrl}/>
<Button newPicture = {this.newPicture} buttonText="New picture" />
<InfoText infoText="I don't take responsibility for giphys shown on this site. There is no filter on the random giphys."/>
</div>
) : (
<div className="imageContainer"><i className="fa fa-spinner" aria-hidden="true"></i></div>
)}
</div>
);
}
}
export default RandomSticker; |
docs/app/Examples/modules/Embed/Variations/index.js | koenvg/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const EmbedVariationsExamples = () => (
<ExampleSection title='Variations'>
<ComponentExample
title='Aspect Ratio'
description='An embed can specify an alternative aspect ratio.'
examplePath='modules/Embed/Variations/EmbedExampleAspectRatio'
/>
</ExampleSection>
)
export default EmbedVariationsExamples
|
src/web/containers/LoginPage/tests/index.js | lukemarsh/hq | import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';
import { LoginPage } from '../index';
describe('<LoginPage />', () => {
it('should render the page', () => {
const renderedComponent = shallow(
<LoginPage />
);
expect(renderedComponent.children.length).toEqual(1);
});
});
|
src/Parser/Monk/Mistweaver/Modules/Talents/SpiritOfTheCrane.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import Wrapper from 'common/Wrapper';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const SOTC_MANA_PER_SECOND_RETURN_MINOR = 640;
const SOTC_MANA_PER_SECOND_RETURN_AVERAGE = SOTC_MANA_PER_SECOND_RETURN_MINOR - 100;
const SOTC_MANA_PER_SECOND_RETURN_MAJOR = SOTC_MANA_PER_SECOND_RETURN_MINOR - 100;
const debug = false;
class SpiritOfTheCrane extends Analyzer {
static dependencies = {
combatants: Combatants,
};
castsTp = 0;
buffTotm = 0;
castsBk = 0;
lastTotmBuffTimestamp = null;
totmOverCap = 0;
totmBuffWasted = 0;
totalTotmBuffs = 0;
manaReturnSotc = 0;
sotcWasted = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.TEACHINGS_OF_THE_MONASTERY.id) {
this.buffTotm += 1;
this.lastTotmBuffTimestamp = event.timestamp;
debug && console.log(`ToTM at ${this.buffTotm}`);
}
}
on_byPlayer_applybuffstack(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.TEACHINGS_OF_THE_MONASTERY.id) {
this.buffTotm += 1;
this.lastTotmBuffTimestamp = event.timestamp;
debug && console.log(`ToTM at ${this.buffTotm}`);
}
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (SPELLS.TEACHINGS_OF_THE_MONASTERY.id === spellId) {
debug && console.log(event.timestamp);
if ((event.timestamp - this.lastTotmBuffTimestamp) > SPELLS.TEACHINGS_OF_THE_MONASTERY.buffDur) {
this.totmBuffWasted += 1;
this.buffTotm = 0;
debug && console.log('ToTM Buff Wasted');
}
this.buffTotm = 0;
// debug && console.log('ToTM Buff Zero');
}
}
on_byPlayer_energize(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.SPIRIT_OF_THE_CRANE_BUFF.id) {
this.manaReturnSotc += event.resourceChange - event.waste;
this.sotcWasted += event.waste;
debug && console.log(`SotC Entergize: ${event.resourceChange - event.waste} Total: ${this.manaReturnSotc}`);
debug && console.log(`SotC Waste: ${event.waste} Total: ${this.sotcWasted} Timestamp: ${event.timestamp}`);
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (!this.combatants.selected.hasBuff(SPELLS.TEACHINGS_OF_THE_MONASTERY.id)) {
// console.log('No TotM Buff');
return;
}
// Need to track when you over cap Teachings stacks. There is no apply aura event fired, so manually tracking stacks.
if (spellId === SPELLS.TIGER_PALM.id && this.buffTotm === 3) {
debug && console.log(`TP Casted at 3 stacks ${event.timestamp}`);
this.lastTotmBuffTimestamp = event.timestamp;
this.totmOverCap += 1;
}
if (spellId === SPELLS.BLACKOUT_KICK.id && this.buffTotm > 0) {
if (this.combatants.selected.hasBuff(SPELLS.TEACHINGS_OF_THE_MONASTERY.id)) {
this.totalTotmBuffs += this.buffTotm;
// this.manaReturnSotc += (this.buffTotm * (baseMana * SPELLS.TEACHINGS_OF_THE_MONASTERY.manaRet));
debug && console.log(`Black Kick Casted with Totm at ${this.buffTotm} stacks`);
}
}
}
get manaReturn() {
return this.manaReturnSotc;
}
get suggestionThresholds() {
return {
actual: this.manaReturn,
isLessThan: {
minor: SOTC_MANA_PER_SECOND_RETURN_MINOR * (this.owner.fightDuration / 1000),
average: SOTC_MANA_PER_SECOND_RETURN_AVERAGE * (this.owner.fightDuration / 1000),
major: SOTC_MANA_PER_SECOND_RETURN_MAJOR * (this.owner.fightDuration / 1000),
},
style: 'number',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(
<Wrapper>
You are not utilizing your <SpellLink id={SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id} /> talent as effectively as you could. Make sure you are using any available downtime to use <SpellLink id={SPELLS.TIGER_PALM.id} /> and <SpellLink id={SPELLS.BLACKOUT_KICK.id} /> to take advantage of this talent.
</Wrapper>
)
.icon(SPELLS.SPIRIT_OF_THE_CRANE_TALENT.icon)
.actual(`${formatNumber(this.manaReturn)} mana returned through Spirit of the Crane`)
.recommended(`${formatNumber(recommended)} is the recommended mana return`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id} />}
value={`${formatNumber(this.manaReturnSotc)}`}
label={(
<dfn data-tip={`
You gained a raw total of ${((this.manaReturnSotc + this.sotcWasted) / 1000).toFixed(0)}k mana from SotC with ${(this.sotcWasted / 1000).toFixed(0)}k wasted.<br>
You lost ${(this.totmOverCap + this.totmBuffWasted)} Teachings of the Monestery stacks
<ul>
${this.totmOverCap > 0 ?
`<li>You overcapped Teachings ${(this.totmOverCap)} times</li>`
: ''
}
${this.totmBuffWasted > 0 ?
`<li>You let Teachings drop off ${(this.totmBuffWasted)} times</li>`
: ''
}
</ul>
`}
>
Mana Returned
</dfn>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(30);
on_finished() {
if (debug) {
console.log(`TotM Buffs Wasted:${this.totmBuffWasted}`);
console.log(`TotM Buffs Overcap:${this.totmOverCap}`);
console.log(`SotC Mana Returned:${this.manaReturnSotc}`);
console.log(`Total TotM Buffs:${this.totalTotmBuffs}`);
console.log(`SotC Waste Total: ${this.sotcWasted}`);
console.log(`SotC Total: ${this.sotcWasted + this.manaReturnSotc}`);
}
}
}
export default SpiritOfTheCrane;
|
ui/src/js/common/components/MultiLineErrorObject.js | Dica-Developer/weplantaforest | import counterpart from 'counterpart';
import React, { Component } from 'react';
export default class MultiLineErrorObject extends Component {
render() {
return (
<div>
{this.props.lines.map(function(line, i) {
return <div key={i}>{counterpart.translate(line.errorCode)}</div>;
})}
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
src/components/groups/GroupVideosView.js | mg4tv/mg4tv-web | import * as _ from 'lodash'
import React from 'react'
import {compose, withHandlers, withProps} from 'recompose'
import VideosList from '../videos/VideosList'
const enhance = compose(
withProps(({match}) => ({
groupId: match.params.groupId
})),
withHandlers(
{
onNewVideoSubmit: props => event => {
event.preventDefault()
}
}
)
)
const GroupVideosView = (
{
groups,
groupId,
onNewVideoSubmit
}
) => (
<div>
<VideosList
videoIds={
Object.keys(_.get(groups, `${groupId}.videos`, {}))
}
/>
<form onSubmit={onNewVideoSubmit}>
<input
type='submit'
value='submit'
/>
</form>
</div>
)
export default enhance(GroupVideosView)
|
src/Components/Header.js | neilD2/neilD2.github.io | import React, { Component } from 'react';
import {
Link
} from 'react-router-dom';
class Header extends Component {
render() {
return (
<header>
<div className="title">History Overflow</div>
<img className="logo"></img>
<nav>
<ul>
<li className="first">
<Link to="/">Home</Link>
</li>
<li>
<Link to="/Podcasts">Podcasts</Link>
</li>
<li>
<Link to="/Films">Films</Link>
</li>
<li>
<Link to="/Books">Books</Link>
</li>
<li>
<Link to="/Dates">Dates & Info</Link>
</li>
</ul>
</nav>
</header>
);
}
}
export default Header;
|
fixtures/blocks/src/index.js | ericyang321/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import {unstable_createRoot as createRoot} from 'react-dom';
import './index.css';
import Router from './Router';
createRoot(document.getElementById('root')).render(<Router />);
|
src/index.js | revuniversal/5e-sheets | // @flow
import React from 'react';
import { render } from 'react-dom';
import { ThemeProvider } from 'styled-components';
import App from './App';
import store from './store';
import theme from './theme';
import './index.css';
const state = store.getState();
render(
<ThemeProvider theme={theme}>
<App character={state.character} />
</ThemeProvider>,
document.getElementById('root')
);
|
jenkins-design-language/src/js/components/material-ui/svg-icons/av/web-asset.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvWebAsset = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z"/>
</SvgIcon>
);
AvWebAsset.displayName = 'AvWebAsset';
AvWebAsset.muiName = 'SvgIcon';
export default AvWebAsset;
|
packages/material-ui-icons/legacy/Battery20TwoTone.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></React.Fragment>
, 'Battery20TwoTone');
|
app/javascript/mastodon/components/load_more.js | rainyday/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadMore extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
disabled: PropTypes.bool,
visible: PropTypes.bool,
}
static defaultProps = {
visible: true,
}
render() {
const { disabled, visible } = this.props;
return (
<button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}>
<FormattedMessage id='status.load_more' defaultMessage='Load more' />
</button>
);
}
}
|
app/javascript/mastodon/features/report/components/status_check_box.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
import noop from 'lodash/noop';
import StatusContent from '../../../components/status_content';
import { MediaGallery, Video } from '../../ui/util/async-components';
import Bundle from '../../ui/components/bundle';
export default class StatusCheckBox extends React.PureComponent {
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
checked: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
disabled: PropTypes.bool,
};
render () {
const { status, checked, onToggle, disabled } = this.props;
let media = null;
if (status.get('reblog')) {
return null;
}
if (status.get('media_attachments').size > 0) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
media = (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
src={video.get('url')}
alt={video.get('description')}
width={239}
height={110}
inline
sensitive={status.get('sensitive')}
onOpenVideo={noop}
/>
)}
</Bundle>
);
} else {
media = (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />}
</Bundle>
);
}
}
return (
<div className='status-check-box'>
<div className='status-check-box__status'>
<StatusContent status={status} />
{media}
</div>
<div className='status-check-box-toggle'>
<Toggle checked={checked} onChange={onToggle} disabled={disabled} />
</div>
</div>
);
}
}
|
eGasAPP/www/lib/auth0-lock/support/design/index.js | egasJMLM/App-web | import React from 'react';
import ReactDOM from 'react-dom';
import Immutable from 'immutable';
import _ from '../../src/browser';
import Control, { store } from './control';
import * as ClientSettings from '../../src/core/client/settings';
import webAPI from '../../src/core/web_api';
const WebAPI = webAPI.constructor;
webAPI.constructor.prototype.constructor = function() {};
WebAPI.prototype.setupClient = function() {};
WebAPI.prototype.logIn = function(lockID, options, cb) {
const state = store.deref();
const args = state.getIn(["logIn", "response"]) == "success" ?
[null] :
[{description: "Wrong email or verification code.", error: "invalid_user_password"}];
setTimeout(() => cb(...args), state.get("latency"));
};
WebAPI.prototype.signOut = function() {};
WebAPI.prototype.signUp = function(lockID, options, cb) {
const state = store.deref();
const args = state.getIn(["signUp", "response"]) == "success" ?
[null] :
[{description: "Wrong email.", error: "invalid_email"}];
setTimeout(() => cb(...args), state.get("latency"));
};
WebAPI.prototype.startPasswordless = function(lockID, options, cb) {
const state = store.deref();
const args = state.getIn(["startPasswordless", "response"]) == "success" ? [null] : [{}];
setTimeout(() => cb(...args), state.get("latency"));
};
WebAPI.prototype.resetPassword = function(lockID, options, cb) {
const state = store.deref();
const args = state.getIn(["resetPassword", "response"]) == "success" ? [null] : [{}];
setTimeout(() => cb(...args), state.get("latency"));
};
WebAPI.prototype.getSSOData = function(lockID, withAD, cb) {
// TODO: consider SSO data for other connections
const ssoData = {
lastUsedConnection: {
strategy: "auth0",
name: "Username-Password-Authentication"
},
lastUsedUserID: "auth0|5676890e2a64397e7e0d773c",
lastUsedUsername: "[email protected]",
lastUsedClientID: "L9kBZOpEbLizzCGv6N8n9wNfQhbvREw0",
sessionClients: [
"L9kBZOpEbLizzCGv6N8n9wNfQhbvREw0"
],
sso: true
};
if (withAD) {
ssoData.connection = {};
}
setTimeout(() => cb(null, ssoData), 180);
}
WebAPI.prototype.getUserCountry = function(lockID, cb) {
setTimeout(() => cb(null, "AR"), 17);
}
WebAPI.prototype.parseHash = function(lockID, ...args) {
return null;
}
ClientSettings.fetchClientSettings = function(clientID, assetsUrl, cb) {
// TODO: we should have propper settings for every configuration.
const settings = {
strategies: [
{
connections: [
{
requires_username: false,
showForgot: true,
showSignup: true,
signup_url: "https://signup.com",
forgot_password_url: "https://forgotpassword.com",
name: "Username-Password-Authentication",
passwordPolicy: "fair"
}
],
name: "auth0"
},
{
connections: [
{
scope: [
"email",
"profile"
],
name: "google-oauth2"
}
],
name: "google-oauth2"
},
{
connections: [
{
name: "rolodato",
domain: "rolodato.com",
domain_aliases: [
"rolodato.com"
]
},
{
name: "ad-no-domain",
domain: null
},
],
name: "ad"
},
{
connections: [
{
name: "benjimon.com",
domain: "benjimon.com",
domain_aliases: [
"benjimon.com"
]
},
],
name: "office365"
},
{
connections: [
{
name: "evilrabbit.com",
domain: "evilrabbit.com",
domain_aliases: [
"evilrabbit.com"
]
},
],
name: "samlp"
},
{
connections: [
{
name: "auth0.com",
domain: "auth0.com",
domain_aliases: [
"auth0.com"
],
scope: [
"email",
"profile"
]
},
],
name: "google-apps",
},
{
connections: [
{
name: "auth10.com",
domain: "auth10.com",
domain_aliases: [
"auth10.com"
],
scope: [
"email",
"profile"
]
},
],
name: "google-apps",
},
{
connections: [
{
name: "exact"
}
],
name: "exact"
},
{
connections: [
{
name: "facebook"
}
],
name: "facebook"
},
{
connections: [
{
name: "fitbit"
}
],
name: "fitbit"
},
{
connections: [
{
name: "thirtysevensignals"
}
],
name: "thirtysevensignals"
},
{
connections: [
{
name: "twitter"
}
],
name: "twitter"
},
{
connections: [
{
name: "windowslive"
}
],
name: "windowslive"
},
{
connections: [
{
name: "wordpress"
}
],
name: "wordpress"
},
{
connections: [
{
name: "github"
}
],
name: "github"
},
{
connections: [
{
name: "email"
}
],
name: "email"
},
{
connections: [
{
name: "sms"
}
],
name: "sms"
}
],
hasAllowedOrigins: true,
callback: window.location.href,
authorize: "https://authorize.com",
subscription: "free",
tenant: "example",
id: "L9kBZOpEbLizzCGv6N8n9wNfQhbvREw0"
};
setTimeout(() => cb(null, Immutable.fromJS(settings)), 180);
}
ReactDOM.render(React.createElement(Control), document.getElementById("control-container"));
|
examples/demo/Form/index.js | NE-LOAN-FED/NE-Component | /**
* Created by kisnows on 2016/12/26.
*/
import React from 'react'
import {
Form,
Input,
Select,
CheckBox,
CellInput,
Cells,
Cell,
Icon,
Modal,
Alert,
VerifyButton,
Toast,
Button
} from '../../../lib'
import Logger from '../../../src/_utils/log'
import lang from '../../utils/lang'
import validate from '../../utils/validate'
import { removeBlack, formatterToBankCard, formatterToPhone } from '../../utils/formatter'
import DatePicker from '../../../src/DatePicker'
const logger = new Logger('DEBUG', 'FormDemo')
class FormDemo extends React.Component {
constructor() {
super()
this.state = {
showInput: true,
name: {
value: '抹桥'
},
phone: {
value: '13333333333'
},
verifyCode: {
value: 3303
},
gender: {},
is: {
value: true
},
card: {},
msg: '',
isComplete: false,
showToast: false
}
}
componentWillMount() {
logger.log('WillMount', this.state)
}
componentDidMount() {
logger.log('DidMount', this.state)
}
componentWillReceiveProps() {
logger.log('componentWillReceiveProps')
}
componentWillUpdate(nextProps, nextState) {
logger.log('WillUpdate', nextState)
}
componentDidUpdate() {
logger.log('DidUpdate', this.state)
}
componentWillUnmount() {
clearTimeout(this.timer)
}
handleSubmit = (isValidate, state, pureData) => {
if (!isValidate) {
this.setState({
showToast: true,
msg: state.errorMsgList[0]
})
} else {
this.setState({
showToast: true,
msg: '正在提交'
})
}
logger.log(`form submit, isValidate:${isValidate},`, 'state:', state, 'pureData:', pureData)
}
handleChange = (formData) => {
logger.log('form change', formData)
this.setState({
...formData.data,
isComplete: formData.isComplete
})
}
handleFieldChange = (FieldData) => {
logger.log('FieldChange', FieldData)
switch (FieldData.name) {
case 'card':
this.setState({
showToast: false,
msg: '测试'
})
break
}
}
closeToast = () => {
this.setState({
showToast: false
})
}
render() {
const { showInput, msg, showToast, isComplete } = this.state
const genderData = [{
name: '男',
value: 0
}, {
name: '女',
value: 1
}]
return (
<section className='page-form-demo'>
<div className='page--header'>
<h1 className='page-title'>Form</h1>
<p className='page--desc'>表单组件,包括 Form, Input, Select, Checkbox。<br /> Form 组件包含了填写校验,错误提示等功能。</p>
</div>
<Toast content={msg}
show={showToast}
onClose={this.closeToast}
/>
<Form
onSubmit={this.handleSubmit}
onChange={this.handleChange}
// onFieldChange={this.handleFieldChange}
>
<Cell.Tip>Input</Cell.Tip>
<Cells>
<Cell warning={this.state.name.isError}>
<Cell.Header>Name</Cell.Header>
<Input type='text'
name='name'
errorMsg={lang.nameErrorMsg}
validate={validate.name}
value={this.state.name.value}
data-index='1'
/>
</Cell>
<Cell warning={this.state.phone.isError}>
<Cell.Header>Phone</Cell.Header>
<Input type='tel'
name='phone'
validate={validate.phone}
errorMsg={lang.phoneErrorMsg}
value={this.state.phone.value}
placeholder='phone'
/>
</Cell>
<Cell warning={this.state.card.isError}>
<Cell.Header>Card</Cell.Header>
<Input type='tel'
name='card'
validate={validate.card}
errorMsg={lang.card}
value={this.state.card.value}
formatterOnBlur={formatterToBankCard}
parser={removeBlack}
/>
</Cell>
<Cell warning={this.state.verifyCode.isError}>
<Cell.Header>Verify Code</Cell.Header>
<Input type='number'
name='verifyCode'
errorMsg={lang.smsCodeErrorMsg}
validate={/\d{4}/}
value={this.state.verifyCode.value}
/>
<Cell.Footer><VerifyButton /></Cell.Footer>
</Cell>
</Cells>
<Cell.Tip>Select</Cell.Tip>
{
showInput ? <Cells>
<Cell warning={this.state.gender.isError}>
<Cell.Header>Gender</Cell.Header>
<Select name='gender'
placeholder={'测试测试'}
placeholderName={'waysSelect'}
data={genderData}
value={this.state.gender.value}
/>
</Cell>
</Cells> : null
}
<Cell.Tip>CheckBox</Cell.Tip>
<Cells>
<Cell htmlFor='is'>
<Cell.Body>Is yourself?</Cell.Body>
<Cell.Footer><CheckBox name='is' id='is' value={this.state.is.value} /></Cell.Footer>
</Cell>
</Cells>
<Button type='submit' disabled={!isComplete}>提交</Button>
</Form>
</section>
)
}
}
export default FormDemo
|
ajax/libs/yui/3.8.0pr1/datatable-body/datatable-body.js | nolsherry/cdnjs | YUI.add('datatable-body', function (Y, NAME) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object;
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or ammended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {HTML}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {HTML}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `host` property of
the configuration object passed to the constructor.
@property host
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//host: null,
/**
HTML templates used to create the `<tbody>` containing the table rows.
@property TBODY_TEMPLATE
@type {HTML}
@default '<tbody class="{className}">{content}</tbody>'
@since 3.6.0
**/
TBODY_TEMPLATE: '<tbody class="{className}"></tbody>',
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.taregt, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.tbodyNode,
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (Y.instanceOf(seed, Y.Node)) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
// TODO this should be a static object map
switch (shift) {
case 'above' : shift = [-1, 0]; break;
case 'below' : shift = [1, 0]; break;
case 'next' : shift = [0, 1]; break;
case 'previous': shift = [0, -1]; break;
}
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Returns the generated CSS classname based on the input. If the `host`
attribute is configured, it will attempt to relay to its `getClassName`
or use its static `NAME` property as a string base.
If `host` is absent or has neither method nor `NAME`, a CSS classname
will be generated using this class's `NAME`.
@method getClassName
@param {String} token* Any number of token strings to assemble the
classname from.
@return {String}
@protected
@since 3.5.0
**/
getClassName: function () {
var host = this.host,
args;
if (host && host.getClassName) {
return host.getClassName.apply(host, arguments);
} else {
args = toArray(arguments);
args.unshift(this.constructor.NAME);
return Y.ClassNameManager.getClassName
.apply(Y.ClassNameManager, args);
}
},
/**
Returns the Model associated to the row Node or id provided. Passing the
Node or id for a descendant of the row also works.
If no Model can be found, `null` is returned.
@method getRecord
@param {String|Node} seed Row Node or `id`, or one for a descendant of a row
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.tbodyNode,
row = null,
record;
if (tbody) {
if (isString(seed)) {
seed = tbody.one('#' + seed);
}
if (Y.instanceOf(seed, Y.Node)) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.tbodyNode,
row = null;
if (tbody) {
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
row = isNumber(id) ?
tbody.get('children').item(id) :
tbody.one('#' + id);
}
return row;
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` and `modelList` attributes.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` attribute (see
`_createRowTemplate`)
2. An HTML string is built up by concatening the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@return {BodyView} The instance
@chainable
@since 3.5.0
**/
render: function () {
var table = this.get('container'),
data = this.get('modelList'),
columns = this.get('columns'),
tbody = this.tbodyNode ||
(this.tbodyNode = this._createTBodyNode());
// Needed for mutation
this._createRowTemplate(columns);
if (data) {
tbody.setHTML(this._createDataHTML(columns));
this._applyNodeFormatters(tbody, columns);
}
if (tbody.get('parentNode') !== table) {
table.appendChild(tbody);
}
this.bindUI();
return this;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function (e) {
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
//var type = e.type.slice(e.type.lastIndexOf(':') + 1);
// TODO: Isolate changes
this.render();
},
/**
Handles replacement of the modelList.
Rerenders the `<tbody>` contents.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.6.0
**/
_afterModelListChange: function (e) {
var handles = this._eventHandles;
if (handles.dataChange) {
handles.dataChange.detach();
delete handles.dataChange;
this.bindUI();
}
if (this.tbodyNode) {
this.render();
}
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} columns The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, columns) {
var host = this.host,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = columns.length; i < len; ++i) {
if (columns[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = columns[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the host (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles,
modelList = this.get('modelList'),
changeEvent = modelList.model.NAME + ':change';
if (!handles.columnsChange) {
handles.columnsChange = this.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (modelList && !handles.dataChange) {
handles.dataChange = modelList.after(
['add', 'remove', 'reset', changeEvent],
bind('_afterDataChange', this));
}
},
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} columns The column configurations to customize the
generated cell content or class names
@return {HTML} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (columns) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index, columns);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@param {Object[]} columns The column configurations
@return {HTML} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index, columns) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
host = this.host || this,
i, len, col, token, value, formatterData;
for (i = 0, len = columns.length; i < len; ++i) {
col = columns[i];
value = data[col.key];
token = col._id || col.key;
values[token + '-className'] = '';
if (col.formatter) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
if (typeof col.formatter === 'string') {
if (value !== undefined) {
// TODO: look for known formatters by string name
value = fromTemplate(col.formatter, formatterData);
}
} else {
// Formatters can either return a value
value = col.formatter.call(host, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
}
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
}
return fromTemplate(this._rowTemplate, values);
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} columns Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (columns) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues;
for (i = 0, len = columns.length; i < len; ++i) {
col = columns[i];
key = col.key;
token = col._id || key;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Creates the `<tbody>` node that will store the data rows.
@method _createTBodyNode
@return {Node}
@protected
@since 3.6.0
**/
_createTBodyNode: function () {
return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {
className: this.getClassName('data')
}));
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `host` - The object to serve as source of truth for column info and
for generating class names
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
this.host = config.host;
this._eventHandles = {
modelListChange: this.after('modelListChange',
bind('_afterModelListChange', this))
};
this._idMap = {};
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {HTML}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
});
}, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
|
ajax/libs/forerunnerdb/1.3.462/fdb-core+views.min.js | tholu/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":31,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":30}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":29}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},f.prototype.match=function(a,b){var c,d,f,g=new e,h=[],i=0;for(c=g.parseArr(this._index,{verbose:!0}),d=g.parseArr(a,{ignore:/\$/,verbose:!0}),f=0;f<c.length;f++)d[f]===c[f]&&(i++,h.push(d[f]));return{matchedKeys:h,totalKeyCount:d.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":26,"./Shared":29}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"deferredCalls"),d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),d.synthesize(n.prototype,"capped"),d.synthesize(n.prototype,"cappedSize"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=J._resolveDynamicQuery(m[n].query,e[x])),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,
err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}if(this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[b].capped(a.capped),this._collection[b].cappedSize(a.size)}return this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":29}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":25,"./Shared":29}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":4,"./Path":26,"./Shared":29}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":26,"./Shared":29}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":29}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":24,"./Shared":29}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":25,"./Serialiser":28}],17:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),
d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":25}],19:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":25}],23:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":26,"./Shared":29}],25:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":29}],27:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":29}],28:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],29:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.462",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],31:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},l.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},l.prototype.primaryKey=function(){return this.publicData().primaryKey()},l.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":27,"./Shared":29}]},{},[1]); |
src/components/Head.js | rhostem/blog | import React from 'react'
import Helmet from 'react-helmet'
import { GlobalStyle } from '../styles/globalStyle'
export default function Head({ children }) {
return (
<>
<Helmet>
<link rel="stylesheet" href="/fonts/nanum-square/font.css" />
<link
href="https://fonts.googleapis.com/css?family=Roboto:100,400,700"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/themes/algolia-min.css"
integrity="sha256-HB49n/BZjuqiCtQQf49OdZn63XuKFaxcIHWf0HNKte8="
crossorigin="anonymous"
/>
<script defer src="/js/rollbar.js" />
{children}
</Helmet>
<GlobalStyle />
</>
)
}
|
packages/react-codemod/test/class-test.js | demohi/react | 'use strict';
var React = require('React');
var Relay = require('Relay');
var Image = require('Image.react');
/*
* Multiline
*/
var MyComponent = React.createClass({
getInitialState: function() {
var x = this.props.foo;
return {
heyoo: 23,
};
},
foo: function() {
this.setState({heyoo: 24});
}
});
// Class comment
var MyComponent2 = React.createClass({
getDefaultProps: function() {
return {a: 1};
},
foo: function() {
pass(this.foo);
this.forceUpdate();
}
});
var MyComponent3 = React.createClass({
statics: {
someThing: 10,
foo: function() {},
},
propTypes: {
highlightEntities: React.PropTypes.bool,
linkifyEntities: React.PropTypes.bool,
text: React.PropTypes.shape({
text: React.PropTypes.string,
ranges: React.PropTypes.array
}).isRequired
},
getDefaultProps: function() {
foo();
return {
linkifyEntities: true,
highlightEntities: false
};
},
getInitialState: function() {
this.props.foo();
return {
heyoo: 23,
};
},
_renderText: function(text) {
return <Text text={text} />;
},
_renderImageRange: function(text, range) {
var image = range.image;
if (image) {
return (
<Image
src={image.uri}
height={image.height / image.scale}
width={image.width / image.scale}
/>
);
}
},
autobindMe: function() {},
dontAutobindMe: function() {},
// Function comment
_renderRange: function(text, range) {
var self = this;
self.dontAutobindMe();
call(self.autobindMe);
var type = rage.type;
var {highlightEntities} = this.props;
if (type === 'ImageAtRange') {
return this._renderImageRange(text, range);
}
if (this.props.linkifyEntities) {
text =
<Link href={usersURI}>
{text}
</Link>;
} else {
text = <span>{text}</span>;
}
return text;
},
/* This is a comment */
render: function() {
var content = this.props.text;
return (
<BaseText
{...this.props}
textRenderer={this._renderText}
rangeRenderer={this._renderRange}
text={content.text}
/>
);
}
});
var MyComponent4 = React.createClass({
foo: callMeMaybe(),
render: function() {},
});
module.exports = Relay.createContainer(MyComponent, {
queries: {
me: Relay.graphql`this is not graphql`,
}
});
|
packages/geo/src/GeoMap.js | plouc/nivo | /*
* This file is part of the nivo project.
*
* Copyright 2016-present, Raphaël Benitte.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Fragment, useCallback, memo } from 'react'
import { SvgWrapper, withContainer, useDimensions, useTheme } from '@nivo/core'
import { useTooltip } from '@nivo/tooltip'
import { GeoMapPropTypes, GeoMapDefaultProps } from './props'
import GeoGraticule from './GeoGraticule'
import GeoMapFeature from './GeoMapFeature'
import { useGeoMap } from './hooks'
const GeoMap = memo(props => {
const {
width,
height,
margin: partialMargin,
features,
layers,
projectionType,
projectionScale,
projectionTranslation,
projectionRotation,
fillColor,
borderWidth,
borderColor,
enableGraticule,
graticuleLineWidth,
graticuleLineColor,
isInteractive,
onClick,
tooltip: Tooltip,
role,
} = props
const { margin, outerWidth, outerHeight } = useDimensions(width, height, partialMargin)
const { graticule, path, getFillColor, getBorderWidth, getBorderColor } = useGeoMap({
width,
height,
projectionType,
projectionScale,
projectionTranslation,
projectionRotation,
fillColor,
borderWidth,
borderColor,
})
const theme = useTheme()
const { showTooltipFromEvent, hideTooltip } = useTooltip()
const handleClick = useCallback(
(feature, event) => isInteractive && onClick && onClick(feature, event),
[isInteractive, onClick]
)
const handleMouseEnter = useCallback(
(feature, event) =>
isInteractive && Tooltip && showTooltipFromEvent(<Tooltip feature={feature} />, event),
[isInteractive, showTooltipFromEvent, Tooltip]
)
const handleMouseMove = useCallback(
(feature, event) =>
isInteractive && Tooltip && showTooltipFromEvent(<Tooltip feature={feature} />, event),
[isInteractive, showTooltipFromEvent, Tooltip]
)
const handleMouseLeave = useCallback(
() => isInteractive && hideTooltip(),
[isInteractive, hideTooltip]
)
return (
<SvgWrapper
width={outerWidth}
height={outerHeight}
margin={margin}
theme={theme}
role={role}
>
{layers.map((layer, i) => {
if (layer === 'graticule') {
if (enableGraticule !== true) return null
return (
<GeoGraticule
key="graticule"
path={path}
graticule={graticule}
lineWidth={graticuleLineWidth}
lineColor={graticuleLineColor}
/>
)
}
if (layer === 'features') {
return (
<Fragment key="features">
{features.map(feature => (
<GeoMapFeature
key={feature.id}
feature={feature}
path={path}
fillColor={getFillColor(feature)}
borderWidth={getBorderWidth(feature)}
borderColor={getBorderColor(feature)}
onMouseEnter={handleMouseEnter}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={handleClick}
/>
))}
</Fragment>
)
}
return <Fragment key={i}>{layer(props)}</Fragment>
})}
</SvgWrapper>
)
})
GeoMap.displayName = 'GeoMap'
GeoMap.propTypes = GeoMapPropTypes
GeoMap.defaultProps = GeoMapDefaultProps
export default withContainer(GeoMap)
|
client/components/basic/UTCClock.js | Sing-Li/Rocket.Chat | import React from 'react';
import { useTimezoneTime } from '../../hooks/useTimezoneTime';
import { useTranslation } from '../../contexts/TranslationContext';
const useUTCClock = (utcOffset) => {
const time = useTimezoneTime(utcOffset, 10000);
return `${ time } (UTC ${ utcOffset })`;
};
export const UTCClock = React.memo(({ utcOffset }) => useUTCClock(utcOffset));
export const LocalTime = React.memo(({ utcOffset }) => {
const t = useTranslation();
const time = useUTCClock(utcOffset);
return t('Local_Time_time', { time });
});
|
webpack.config.js | lakshmikanthadn/bookMyShow | var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.less$/,
loader: "style!css!less"
}]
}
};
|
packages/veritone-widgets/src/widgets/Table/index.js | veritone/veritone-sdk | import React from 'react';
import { func, arrayOf, bool, shape, object } from 'prop-types';
import {
Table as TableComponent,
PaginatedTable,
Column,
MenuColumn
} from 'veritone-react-common';
import { omit } from 'lodash';
import widget from '../../shared/widget';
class Table extends React.Component {
static propTypes = {
data: arrayOf(object).isRequired,
columns: arrayOf(
shape({
transform: func,
menu: bool,
onSelectItem: func
})
),
paginate: bool
};
static defaultProps = {
paginate: false
};
getRowData = i => {
return this.props.data[i];
};
render() {
const TableComp = this.props.paginate ? PaginatedTable : TableComponent;
const tableProps = omit(this.props, ['data', 'columns', 'paginate']);
const tableColumns = this.props.columns.map(column => {
if (column.menu) {
return (
<MenuColumn
key={column.dataKey}
{...omit(column, ['transform', 'menu'])}
/>
);
}
return (
<Column
{...omit(column, ['menu', 'onSelectItem', 'transform'])}
cellRenderer={column.transform}
key={column.dataKey}
/>
);
});
return (
<TableComp
rowGetter={this.getRowData}
rowCount={this.props.data.length}
{...tableProps}
>
{tableColumns}
</TableComp>
);
}
}
const TableWidget = widget(Table);
export { TableWidget };
|
ajax/libs/babel-core/5.1.10/browser-polyfill.js | sympmarc/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";if(global._babelPolyfill){throw new Error("only one instance of babel/polyfill is allowed")}global._babelPolyfill=true;require("core-js/shim");require("regenerator/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":72,"regenerator/runtime":73}],2:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function(IS_INCLUDES){return function(el){var O=$.toObject(this),length=$.toLength(O.length),index=$.toIndex(arguments[1],length),value;if(IS_INCLUDES&&el!=el)while(length>index){value=O[index++];if(value!=value)return true}else for(;length>index;index++)if(IS_INCLUDES||index in O){if(O[index]===el)return IS_INCLUDES||index}return!IS_INCLUDES&&-1}}},{"./$":16}],3:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx");module.exports=function(TYPE){var IS_MAP=TYPE==1,IS_FILTER=TYPE==2,IS_SOME=TYPE==3,IS_EVERY=TYPE==4,IS_FIND_INDEX=TYPE==6,NO_HOLES=TYPE==5||IS_FIND_INDEX;return function(callbackfn){var O=Object($.assertDefined(this)),self=$.ES5Object(O),f=ctx(callbackfn,arguments[1],3),length=$.toLength(self.length),index=0,result=IS_MAP?Array(length):IS_FILTER?[]:undefined,val,res;for(;length>index;index++)if(NO_HOLES||index in self){val=self[index];res=f(val,index,O);if(TYPE){if(IS_MAP)result[index]=res;else if(res)switch(TYPE){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(IS_EVERY)return false}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:result}}},{"./$":16,"./$.ctx":10}],4:[function(require,module,exports){var $=require("./$");function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}assert.def=$.assertDefined;assert.fn=function(it){if(!$.isFunction(it))throw TypeError(it+" is not a function!");return it};assert.obj=function(it){if(!$.isObject(it))throw TypeError(it+" is not an object!");return it};assert.inst=function(it,Constructor,name){if(!(it instanceof Constructor))throw TypeError(name+": use the 'new' operator!");return it};module.exports=assert},{"./$":16}],5:[function(require,module,exports){var $=require("./$");module.exports=Object.assign||function assign(target,source){var T=Object($.assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=$.ES5Object(arguments[i++]),keys=$.getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T}},{"./$":16}],6:[function(require,module,exports){var $=require("./$"),TAG=require("./$.wks")("toStringTag"),toString={}.toString;function cof(it){return toString.call(it).slice(8,-1)}cof.classof=function(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[TAG])=="string"?T:cof(O)};cof.set=function(it,tag,stat){if(it&&!$.has(it=stat?it:it.prototype,TAG))$.hide(it,TAG,tag)};module.exports=cof},{"./$":16,"./$.wks":27}],7:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),safe=require("./$.uid").safe,assert=require("./$.assert"),$iter=require("./$.iter"),has=$.has,set=$.set,isObject=$.isObject,hide=$.hide,step=$iter.step,isFrozen=Object.isFrozen||$.core.Object.isFrozen,ID=safe("id"),O1=safe("O1"),LAST=safe("last"),FIRST=safe("first"),ITER=safe("iter"),SIZE=$.DESC?safe("size"):"size",id=0;function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,ID)){if(!create)return"E";hide(it,ID,++id)}return"O"+it[ID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(iterable){var that=assert.inst(this,C,NAME);set(that,O1,$.create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);if(iterable!=undefined)$iter.forOf(iterable,IS_MAP,that[ADDER],that)}$.mix(C.prototype,{clear:function clear(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function forEach(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function has(key){return!!getEntry(this,key)}});if($.DESC)$.setDesc(C.prototype,"size",{get:function(){return assert.def(this[SIZE])}});return C},def:function(that,key,value){var entry=getEntry(that,key),prev,index;if(entry){entry.v=value}else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that},getEntry:getEntry,getIterConstructor:function(){return function(iterated,kind){set(this,ITER,{o:iterated,k:kind})}},next:function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return step(1)}if(kind=="key")return step(0,entry.k);if(kind=="value")return step(0,entry.v);return step(0,[entry.k,entry.v])}}},{"./$":16,"./$.assert":4,"./$.ctx":10,"./$.iter":15,"./$.uid":25}],8:[function(require,module,exports){"use strict";var $=require("./$"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.iter").forOf,_has=$.has,isObject=$.isObject,hide=$.hide,isFrozen=Object.isFrozen||$.core.Object.isFrozen,id=0,ID=safe("id"),WEAK=safe("weak"),LEAK=safe("leak"),method=require("./$.array-methods"),find=method(5),findIndex=method(6);function findFrozen(store,key){return find.call(store.array,function(it){return it[0]===key})}function leakStore(that){return that[LEAK]||hide(that,LEAK,{array:[],get:function(key){var entry=findFrozen(this,key);if(entry)return entry[1]},has:function(key){return!!findFrozen(this,key)},set:function(key,value){var entry=findFrozen(this,key);if(entry)entry[1]=value;else this.array.push([key,value])},"delete":function(key){var index=findIndex.call(this.array,function(it){return it[0]===key});if(~index)this.array.splice(index,1);return!!~index}})[LEAK]}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(iterable){$.set(assert.inst(this,C,NAME),ID,id++);if(iterable!=undefined)forOf(iterable,IS_MAP,this[ADDER],this)}$.mix(C.prototype,{"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])&&delete key[WEAK][this[ID]]},has:function has(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])}});return C},def:function(that,key,value){if(isFrozen(assert.obj(key))){leakStore(that).set(key,value)}else{_has(key,WEAK)||hide(key,WEAK,{});key[WEAK][that[ID]]=value}return that},leakStore:leakStore,WEAK:WEAK,ID:ID}},{"./$":16,"./$.array-methods":3,"./$.assert":4,"./$.iter":15,"./$.uid":25}],9:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),$iter=require("./$.iter"),assertInstance=require("./$.assert").inst;module.exports=function(NAME,methods,common,IS_MAP,isWeak){var Base=$.g[NAME],C=Base,ADDER=IS_MAP?"set":"add",proto=C&&C.prototype,O={};function fixMethod(KEY,CHAIN){var method=proto[KEY];if($.FW)proto[KEY]=function(a,b){var result=method.call(this,a===0?0:a,b);return CHAIN?this:result}}if(!$.isFunction(C)||!(isWeak||!$iter.BUGGY&&proto.forEach&&proto.entries)){C=common.getConstructor(NAME,IS_MAP,ADDER);$.mix(C.prototype,methods)}else{var inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!require("./$.iter-detect")(function(iter){new C(iter)})){C=function(iterable){assertInstance(this,C,NAME);var that=new Base;if(iterable!=undefined)$iter.forOf(iterable,IS_MAP,that[ADDER],that);return that};C.prototype=proto;if($.FW)proto.constructor=C}isWeak||inst.forEach(function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixMethod("delete");fixMethod("has");IS_MAP&&fixMethod("get")}if(buggyZero||chain!==inst)fixMethod(ADDER,true)}require("./$.cof").set(C,NAME);require("./$.species")(C);O[NAME]=C;$def($def.G+$def.W+$def.F*(C!=Base),O);if(!isWeak)$iter.std(C,NAME,common.getIterConstructor(),common.next,IS_MAP?"key+value":"value",!IS_MAP,true);return C}},{"./$":16,"./$.assert":4,"./$.cof":6,"./$.def":11,"./$.iter":15,"./$.iter-detect":14,"./$.species":22}],10:[function(require,module,exports){var assertFunction=require("./$.assert").fn;module.exports=function(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}},{"./$.assert":4}],11:[function(require,module,exports){var $=require("./$"),global=$.g,core=$.core,isFunction=$.isFunction;function ctx(fn,that){return function(){return fn.apply(that,arguments)}}global.core=core;$def.F=1;$def.G=2;$def.S=4;$def.P=8;$def.B=16;$def.W=32;function $def(type,name,source){var key,own,out,exp,isGlobal=type&$def.G,target=isGlobal?global:type&$def.S?global[name]:(global[name]||{}).prototype,exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&$def.F)&&target&&key in target;out=(own?target:source)[key];if(type&$def.B&&own)exp=ctx(out,global);else exp=type&$def.P&&isFunction(out)?ctx(Function.call,out):out;if(target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&$.hide(target,key,out)}if(exports[key]!=out)$.hide(exports,key,exp)}}module.exports=$def},{"./$":16}],12:[function(require,module,exports){module.exports=function($){$.FW=true;$.path=$.g;return $}},{}],13:[function(require,module,exports){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]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}},{}],14:[function(require,module,exports){var SYMBOL_ITERATOR=require("./$.wks")("iterator"),SAFE_CLOSING=false;try{var riter=[7][SYMBOL_ITERATOR]();riter["return"]=function(){SAFE_CLOSING=true};Array.from(riter,function(){throw 2})}catch(e){}module.exports=function(exec){if(!SAFE_CLOSING)return false;var safe=false;try{var arr=[7],iter=arr[SYMBOL_ITERATOR]();iter.next=function(){safe=true};arr[SYMBOL_ITERATOR]=function(){return iter};exec(arr)}catch(e){}return safe}},{"./$.wks":27}],15:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),$def=require("./$.def"),assertObject=require("./$.assert").obj,SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",Iterators={},IteratorPrototype={};var BUGGY="keys"in[]&&!("next"in[].keys());setIterator(IteratorPrototype,$.that);function setIterator(O,value){$.hide(O,SYMBOL_ITERATOR,value);if(FF_ITERATOR in[])$.hide(O,FF_ITERATOR,value)}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor.prototype,iter=proto[SYMBOL_ITERATOR]||proto[FF_ITERATOR]||DEFAULT&&proto[DEFAULT]||value;if($.FW)setIterator(proto,iter);if(iter!==value){var iterProto=$.getProto(iter.call(new Constructor));cof.set(iterProto,NAME+" Iterator",true);if($.FW)$.has(proto,FF_ITERATOR)&&setIterator(iterProto,$.that)}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=$.that;return iter}function getIterator(it){var Symbol=$.g.Symbol,ext=it[Symbol&&Symbol.iterator||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[cof.classof(it)];return assertObject(getIter.call(it))}function closeIterator(iterator){var ret=iterator["return"];if(ret!==undefined)assertObject(ret.call(iterator))}function stepCall(iterator,fn,value,entries){try{return entries?fn(assertObject(value)[0],value[1]):fn(value)}catch(e){closeIterator(iterator);throw e}}var $iter=module.exports={BUGGY:BUGGY,Iterators:Iterators,prototype:IteratorPrototype,step:function(done,value){return{value:value,done:!!done}},stepCall:stepCall,close:closeIterator,is:function(it){var O=Object(it),Symbol=$.g.Symbol,SYM=Symbol&&Symbol.iterator||FF_ITERATOR;return SYM in O||SYMBOL_ITERATOR in O||$.has(Iterators,cof.classof(O))},get:getIterator,set:setIterator,create:function(Constructor,NAME,next,proto){Constructor.prototype=$.create(proto||$iter.prototype,{next:$.desc(1,next)});cof.set(Constructor,NAME+" Iterator")},define:defineIterator,std:function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCE){function createIter(kind){return function(){return new Constructor(this,kind)}}$iter.create(Constructor,NAME,next);var entries=createIter("key+value"),values=createIter("value"),proto=Base.prototype,methods,key;if(DEFAULT=="value")values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){methods={entries:entries,keys:IS_SET?values:createIter("key"),values:values};$def($def.P+$def.F*BUGGY,NAME,methods);if(FORCE)for(key in methods){if(!(key in proto))$.hide(proto,key,methods[key])}}},forOf:function(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done){if(stepCall(iterator,f,step.value,entries)===false){return closeIterator(iterator)}}}}},{"./$":16,"./$.assert":4,"./$.cof":6,"./$.ctx":10,"./$.def":11,"./$.wks":27}],16:[function(require,module,exports){"use strict";var global=typeof self!="undefined"?self:Function("return this")(),core={},defineProperty=Object.defineProperty,hasOwnProperty={}.hasOwnProperty,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min;var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}();var hide=createDefiner(1);function toInteger(it){return isNaN(it=+it)?0:(it>0?floor:ceil)(it)}function desc(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return $.setDesc(object,key,desc(bitmap,value))}:simpleSet}function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}function assertDefined(it){if(it==undefined)throw TypeError("Can't call method on "+it);return it}var $=module.exports=require("./$.fw")({g:global,core:core,html:global.document&&document.documentElement,isObject:isObject,isFunction:isFunction,it:function(it){return it},that:function(){return this},toInteger:toInteger,toLength:function(it){return it>0?min(toInteger(it),9007199254740991):0},toIndex:function(index,length){index=toInteger(index);return index<0?max(index+length,0):min(index,length)},has:function(it,key){return hasOwnProperty.call(it,key)},create:Object.create,getProto:Object.getPrototypeOf,DESC:DESC,desc:desc,getDesc:Object.getOwnPropertyDescriptor,setDesc:defineProperty,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:assertDefined,ES5Object:Object,toObject:function(it){return $.ES5Object(assertDefined(it))},hide:hide,def:createDefiner(0),set:global.Symbol?simpleSet:hide,mix:function(target,src){for(var key in src)hide(target,key,src[key]);return target},each:[].forEach});if(typeof __e!="undefined")__e=core;if(typeof __g!="undefined")__g=global},{"./$.fw":12}],17:[function(require,module,exports){var $=require("./$");module.exports=function(object,el){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}},{"./$":16}],18:[function(require,module,exports){var $=require("./$"),assertObject=require("./$.assert").obj;module.exports=function ownKeys(it){assertObject(it);return $.getSymbols?$.getNames(it).concat($.getSymbols(it)):$.getNames(it)}},{"./$":16,"./$.assert":4}],19:[function(require,module,exports){"use strict";var $=require("./$"),invoke=require("./$.invoke"),assertFunction=require("./$.assert").fn;module.exports=function(){var fn=assertFunction(this),length=arguments.length,pargs=Array(length),i=0,_=$.path._,holder=false;while(length>i)if((pargs[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,j=0,k=0,args;if(!holder&&!_length)return invoke(fn,pargs,that);args=pargs.slice();if(holder)for(;length>j;j++)if(args[j]===_)args[j]=arguments[k++];while(_length>k)args.push(arguments[k++]);return invoke(fn,args,that)}}},{"./$":16,"./$.assert":4,"./$.invoke":13}],20:[function(require,module,exports){"use strict";module.exports=function(regExp,replace,isStatic){var replacer=replace===Object(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}},{}],21:[function(require,module,exports){var $=require("./$"),assert=require("./$.assert");function check(O,proto){assert.obj(O);assert(proto===null||$.isObject(proto),proto,": can't set as prototype!")}module.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(buggy,set){try{set=require("./$.ctx")(Function.call,$.getDesc(Object.prototype,"__proto__").set,2);set({},[])}catch(e){buggy=true}return function setPrototypeOf(O,proto){check(O,proto);if(buggy)O.__proto__=proto;else set(O,proto);return O}}():undefined),check:check}},{"./$":16,"./$.assert":4,"./$.ctx":10}],22:[function(require,module,exports){var $=require("./$");module.exports=function(C){if($.DESC&&$.FW)$.setDesc(C,require("./$.wks")("species"),{configurable:true,get:$.that})}},{"./$":16,"./$.wks":27}],23:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function(TO_STRING){return function(pos){var s=String($.assertDefined(this)),i=$.toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return TO_STRING?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?TO_STRING?s.charAt(i):a:TO_STRING?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}},{"./$":16}],24:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),invoke=require("./$.invoke"),global=$.g,isFunction=$.isFunction,html=$.html,document=global.document,process=global.process,setTask=global.setImmediate,clearTask=global.clearImmediate,postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port;function run(){var id=+this;if($.has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run.call(event.data)}if(!isFunction(setTask)||!isFunction(clearTask)){setTask=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearTask=function(id){delete queue[id]};if(cof(process)=="process"){defer=function(id){process.nextTick(ctx(run,id,1))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document.createElement("script")){defer=function(id){html.appendChild(document.createElement("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run.call(id)}}}else{defer=function(id){setTimeout(ctx(run,id,1),0)}}}module.exports={set:setTask,clear:clearTask}},{"./$":16,"./$.cof":6,"./$.ctx":10,"./$.invoke":13}],25:[function(require,module,exports){var sid=0;function uid(key){return"Symbol("+key+")_"+(++sid+Math.random()).toString(36)}uid.safe=require("./$").g.Symbol||uid;module.exports=uid},{"./$":16}],26:[function(require,module,exports){var $=require("./$"),UNSCOPABLES=require("./$.wks")("unscopables");if($.FW&&!(UNSCOPABLES in[]))$.hide(Array.prototype,UNSCOPABLES,{});module.exports=function(key){if($.FW)[][UNSCOPABLES][key]=true}},{"./$":16,"./$.wks":27}],27:[function(require,module,exports){var global=require("./$").g,store={};module.exports=function(name){return store[name]||(store[name]=global.Symbol&&global.Symbol[name]||require("./$.uid").safe("Symbol."+name))}},{"./$":16,"./$.uid":25}],28:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),invoke=require("./$.invoke"),arrayMethod=require("./$.array-methods"),IE_PROTO=require("./$.uid").safe("__proto__"),assert=require("./$.assert"),assertObject=assert.obj,ObjectProto=Object.prototype,A=[],slice=A.slice,indexOf=A.indexOf,classof=cof.classof,defineProperties=Object.defineProperties,has=$.has,defineProperty=$.setDesc,getOwnDescriptor=$.getDesc,isFunction=$.isFunction,toObject=$.toObject,toLength=$.toLength,IE8_DOM_DEFINE=false;if(!$.DESC){try{IE8_DOM_DEFINE=defineProperty(document.createElement("div"),"x",{get:function(){return 8}}).x==8}catch(e){}$.setDesc=function(O,P,Attributes){if(IE8_DOM_DEFINE)try{return defineProperty(O,P,Attributes)}catch(e){}if("get"in Attributes||"set"in Attributes)throw TypeError("Accessors not supported!");if("value"in Attributes)assertObject(O)[P]=Attributes.value;return O};$.getDesc=function(O,P){if(IE8_DOM_DEFINE)try{return getOwnDescriptor(O,P)}catch(e){}if(has(O,P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O,P),O[P])};defineProperties=function(O,Properties){assertObject(O);var keys=$.getKeys(Properties),length=keys.length,i=0,P;while(length>i)$.setDesc(O,P=keys[i++],Properties[P]);return O}}$def($def.S+$def.F*!$.DESC,"Object",{getOwnPropertyDescriptor:$.getDesc,defineProperty:$.setDesc,defineProperties:defineProperties});var keys1=("constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,"+"toLocaleString,toString,valueOf").split(","),keys2=keys1.concat("length","prototype"),keysLen1=keys1.length;var createDict=function(){var iframe=document.createElement("iframe"),i=keysLen1,gt=">",iframeDocument;iframe.style.display="none";$.html.appendChild(iframe);iframe.src="javascript:";iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write("<script>document.F=Object</script"+gt);iframeDocument.close();createDict=iframeDocument.F;while(i--)delete createDict.prototype[keys1[i]];return createDict()};function createGetKeys(names,length){return function(object){var O=toObject(object),i=0,result=[],key;for(key in O)if(key!=IE_PROTO)has(O,key)&&result.push(key);while(length>i)if(has(O,key=names[i++])){~indexOf.call(result,key)||result.push(key)}return result}}function isPrimitive(it){return!$.isObject(it)}function Empty(){}$def($def.S,"Object",{getPrototypeOf:$.getProto=$.getProto||function(O){O=Object(assert.def(O));if(has(O,IE_PROTO))return O[IE_PROTO];if(isFunction(O.constructor)&&O instanceof O.constructor){return O.constructor.prototype}return O instanceof Object?ObjectProto:null},getOwnPropertyNames:$.getNames=$.getNames||createGetKeys(keys2,keys2.length,true),create:$.create=$.create||function(O,Properties){var result;if(O!==null){Empty.prototype=assertObject(O);result=new Empty;Empty.prototype=null;result[IE_PROTO]=O}else result=createDict();return Properties===undefined?result:defineProperties(result,Properties)},keys:$.getKeys=$.getKeys||createGetKeys(keys1,keysLen1,false),seal:$.it,freeze:$.it,preventExtensions:$.it,isSealed:isPrimitive,isFrozen:isPrimitive,isExtensible:$.isObject});$def($def.P,"Function",{bind:function(that){var fn=assert.fn(this),partArgs=slice.call(arguments,1);function bound(){var args=partArgs.concat(slice.call(arguments));return invoke(fn,args,this instanceof bound?$.create(fn.prototype):that)}if(fn.prototype)bound.prototype=fn.prototype;return bound}});function arrayMethodFix(fn){return function(){return fn.apply($.ES5Object(this),arguments)}}if(!(0 in Object("z")&&"z"[0]=="z")){$.ES5Object=function(it){return cof(it)=="String"?it.split(""):Object(it)}}$def($def.P+$def.F*($.ES5Object!=Object),"Array",{slice:arrayMethodFix(slice),join:arrayMethodFix(A.join)});$def($def.S,"Array",{isArray:function(arg){return cof(arg)=="Array"}});function createArrayReduce(isRight){return function(callbackfn,memo){assert.fn(callbackfn);var O=toObject(this),length=toLength(O.length),index=isRight?length-1:0,i=isRight?-1:1;if(arguments.length<2)for(;;){if(index in O){memo=O[index];index+=i;break}index+=i;assert(isRight?index>=0:length>index,"Reduce of empty array with no initial value")}for(;isRight?index>=0:length>index;index+=i)if(index in O){memo=callbackfn(memo,O[index],index,this)}return memo}}$def($def.P,"Array",{forEach:$.each=$.each||arrayMethod(0),map:arrayMethod(1),filter:arrayMethod(2),some:arrayMethod(3),every:arrayMethod(4),reduce:createArrayReduce(false),reduceRight:createArrayReduce(true),indexOf:indexOf=indexOf||require("./$.array-includes")(false),lastIndexOf:function(el,fromIndex){var O=toObject(this),length=toLength(O.length),index=length-1;if(arguments.length>1)index=Math.min(index,$.toInteger(fromIndex));if(index<0)index=toLength(length+index);for(;index>=0;index--)if(index in O)if(O[index]===el)return index;return-1}});$def($def.P,"String",{trim:require("./$.replacer")(/^\s*([\s\S]*\S)?\s*$/,"$1")});$def($def.S,"Date",{now:function(){return+new Date}});function lz(num){return num>9?num:"0"+num}$def($def.P,"Date",{toISOString:function(){if(!isFinite(this))throw RangeError("Invalid time value");var d=this,y=d.getUTCFullYear(),m=d.getUTCMilliseconds(),s=y<0?"-":y>9999?"+":"";return s+("00000"+Math.abs(y)).slice(s?-6:-4)+"-"+lz(d.getUTCMonth()+1)+"-"+lz(d.getUTCDate())+"T"+lz(d.getUTCHours())+":"+lz(d.getUTCMinutes())+":"+lz(d.getUTCSeconds())+"."+(m>99?m:"0"+lz(m))+"Z"}});if(classof(function(){return arguments}())=="Object")cof.classof=function(it){var tag=classof(it);return tag=="Object"&&isFunction(it.callee)?"Arguments":tag}},{"./$":16,"./$.array-includes":2,"./$.array-methods":3,"./$.assert":4,"./$.cof":6,"./$.def":11,"./$.invoke":13,"./$.replacer":20,"./$.uid":25}],29:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{copyWithin:function copyWithin(target,start){var O=Object($.assertDefined(this)),len=$.toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=Math.min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O}});require("./$.unscope")("copyWithin")},{"./$":16,"./$.def":11,"./$.unscope":26}],30:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{fill:function fill(value){var O=Object($.assertDefined(this)),length=$.toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O}});require("./$.unscope")("fill")},{"./$":16,"./$.def":11,"./$.unscope":26}],31:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{findIndex:require("./$.array-methods")(6)});require("./$.unscope")("findIndex")},{"./$.array-methods":3,"./$.def":11,"./$.unscope":26}],32:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{find:require("./$.array-methods")(5)});require("./$.unscope")("find")},{"./$.array-methods":3,"./$.def":11,"./$.unscope":26}],33:[function(require,module,exports){var $=require("./$"),ctx=require("./$.ctx"),$def=require("./$.def"),$iter=require("./$.iter"),stepCall=$iter.stepCall;$def($def.S+$def.F*!require("./$.iter-detect")(function(iter){Array.from(iter)}),"Array",{from:function from(arrayLike){var O=Object($.assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,step,iterator;if($iter.is(O)){iterator=$iter.get(O);result=new(typeof this=="function"?this:Array);for(;!(step=iterator.next()).done;index++){result[index]=mapping?stepCall(iterator,f,[step.value,index],true):step.value}}else{result=new(typeof this=="function"?this:Array)(length=$.toLength(O.length));for(;length>index;index++){result[index]=mapping?f(O[index],index):O[index]}}result.length=index;return result}})},{"./$":16,"./$.ctx":10,"./$.def":11,"./$.iter":15,"./$.iter-detect":14}],34:[function(require,module,exports){var $=require("./$"),setUnscope=require("./$.unscope"),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step,Iterators=$iter.Iterators;$iter.std(Array,"Array",function(iterated,kind){$.set(this,ITER,{o:$.toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return step(1)}if(kind=="key")return step(0,index);if(kind=="value")return step(0,O[index]);return step(0,[index,O[index]])},"value");Iterators.Arguments=Iterators.Array;setUnscope("keys");setUnscope("values");setUnscope("entries")},{"./$":16,"./$.iter":15,"./$.uid":25,"./$.unscope":26}],35:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Array",{of:function of(){var index=0,length=arguments.length,result=new(typeof this=="function"?this:Array)(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}})},{"./$.def":11}],36:[function(require,module,exports){require("./$.species")(Array)},{"./$.species":22}],37:[function(require,module,exports){"use strict";var $=require("./$"),NAME="name",setDesc=$.setDesc,FunctionProto=Function.prototype;NAME in FunctionProto||$.FW&&$.DESC&&setDesc(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";$.has(this,NAME)||setDesc(this,NAME,$.desc(5,name));return name},set:function(value){$.has(this,NAME)||setDesc(this,NAME,$.desc(0,value))}})},{"./$":16}],38:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Map",{get:function get(key){var entry=strong.getEntry(this,key);return entry&&entry.v},set:function set(key,value){return strong.def(this,key===0?0:key,value)}},strong,true)},{"./$.collection":9,"./$.collection-strong":7}],39:[function(require,module,exports){var Infinity=1/0,$def=require("./$.def"),E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,ceil=Math.ceil,floor=Math.floor,EPSILON=pow(2,-52),EPSILON32=pow(2,-23),MAX32=pow(2,127)*(2-EPSILON32),MIN32=pow(2,-126);function roundTiesToEven(n){return n+1/EPSILON-1/EPSILON}function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1;
}function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$def($def.S,"Math",{acosh:function acosh(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function atanh(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function cbrt(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function clz32(x){return(x>>>=0)?31-floor(log(x+.5)*Math.LOG2E):32},cosh:function cosh(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function fround(x){var $abs=abs(x),$sign=sign(x),a,result;if($abs<MIN32)return $sign*roundTiesToEven($abs/MIN32/EPSILON32)*MIN32*EPSILON32;a=(1+EPSILON32/EPSILON)*$abs;result=a-(a-$abs);if(result>MAX32||result!=result)return $sign*Infinity;return $sign*result},hypot:function hypot(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function imul(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function log1p(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function log10(x){return log(x)/Math.LN10},log2:function log2(x){return log(x)/Math.LN2},sign:sign,sinh:function sinh(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function tanh(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:function trunc(it){return(it>0?floor:ceil)(it)}})},{"./$.def":11}],40:[function(require,module,exports){"use strict";var $=require("./$"),isObject=$.isObject,isFunction=$.isFunction,NUMBER="Number",Number=$.g[NUMBER],Base=Number,proto=Number.prototype;function toPrimitive(it){var fn,val;if(isFunction(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(isFunction(fn=it.toString)&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to number")}function toNumber(it){if(isObject(it))it=toPrimitive(it);if(typeof it=="string"&&it.length>2&&it.charCodeAt(0)==48){var binary=false;switch(it.charCodeAt(1)){case 66:case 98:binary=true;case 79:case 111:return parseInt(it.slice(2),binary?2:8)}}return+it}if($.FW&&!(Number("0o1")&&Number("0b1"))){Number=function Number(it){return this instanceof Number?new Base(toNumber(it)):toNumber(it)};$.each.call($.DESC?$.getNames(Base):("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,"+"EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,"+"MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger").split(","),function(key){if($.has(Base,key)&&!$.has(Number,key)){$.setDesc(Number,key,$.getDesc(Base,key))}});Number.prototype=proto;proto.constructor=Number;$.hide($.g,NUMBER,Number)}},{"./$":16}],41:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),abs=Math.abs,floor=Math.floor,_isFinite=$.g.isFinite,MAX_SAFE_INTEGER=9007199254740991;function isInteger(it){return!$.isObject(it)&&_isFinite(it)&&floor(it)===it}$def($def.S,"Number",{EPSILON:Math.pow(2,-52),isFinite:function isFinite(it){return typeof it=="number"&&_isFinite(it)},isInteger:isInteger,isNaN:function isNaN(number){return number!=number},isSafeInteger:function isSafeInteger(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})},{"./$":16,"./$.def":11}],42:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{assign:require("./$.assign")})},{"./$.assign":5,"./$.def":11}],43:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{is:function is(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}})},{"./$.def":11}],44:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{setPrototypeOf:require("./$.set-proto").set})},{"./$.def":11,"./$.set-proto":21}],45:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),isObject=$.isObject,toObject=$.toObject;function wrapObjectMethod(METHOD,MODE){var fn=($.core.Object||{})[METHOD]||Object[METHOD],f=0,o={};o[METHOD]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function getOwnPropertyDescriptor(it,key){return fn(toObject(it),key)}:MODE==5?function getPrototypeOf(it){return fn(Object($.assertDefined(it)))}:function(it){return fn(toObject(it))};try{fn("z")}catch(e){f=1}$def($def.S+$def.F*f,"Object",o)}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf",5);wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")},{"./$":16,"./$.def":11}],46:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),tmp={};tmp[require("./$.wks")("toStringTag")]="z";if($.FW&&cof(tmp)!="z")$.hide(Object.prototype,"toString",function toString(){return"[object "+cof.classof(this)+"]"})},{"./$":16,"./$.cof":6,"./$.wks":27}],47:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),$def=require("./$.def"),assert=require("./$.assert"),$iter=require("./$.iter"),SPECIES=require("./$.wks")("species"),RECORD=require("./$.uid").safe("record"),forOf=$iter.forOf,PROMISE="Promise",global=$.g,process=global.process,asap=process&&process.nextTick||require("./$.task").set,P=global[PROMISE],Base=P,isFunction=$.isFunction,isObject=$.isObject,assertFunction=assert.fn,assertObject=assert.obj,test;function getConstructor(C){var S=assertObject(C)[SPECIES];return S!=undefined?S:C}function isThenable(it){var then;if(isObject(it))then=it.then;return isFunction(then)?then:false}function isUnhandled(promise){var record=promise[RECORD],chain=record.c,i=0,react;if(record.h)return false;while(chain.length>i){react=chain[i++];if(react.fail||!isUnhandled(react.P))return false}return true}function notify(record,isReject){var chain=record.c;if(isReject||chain.length)asap(function(){var promise=record.p,value=record.v,ok=record.s==1,i=0;if(isReject&&isUnhandled(promise)){setTimeout(function(){if(isUnhandled(promise)){if(cof(process)=="process"){process.emit("unhandledRejection",value,promise)}else if(global.console&&isFunction(console.error)){console.error("Unhandled promise rejection",value)}}},1e3)}else while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){if(!ok)record.h=true;ret=cb===true?value:cb(value);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(value)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function $reject(value){var record=this;if(record.d)return;record.d=true;record=record.r||record;record.v=value;record.s=2;notify(record,true)}function $resolve(value){var record=this,then,wrapper;if(record.d)return;record.d=true;record=record.r||record;try{if(then=isThenable(value)){wrapper={r:record,d:false};then.call(value,ctx($resolve,wrapper,1),ctx($reject,wrapper,1))}else{record.v=value;record.s=1;notify(record)}}catch(err){$reject.call(wrapper||{r:record,d:false},err)}}if(!(isFunction(P)&&isFunction(P.resolve)&&P.resolve(test=new P(function(){}))==test)){P=function Promise(executor){assertFunction(executor);var record={p:assert.inst(this,P,PROMISE),c:[],s:0,d:false,v:undefined,h:false};$.hide(this,RECORD,record);try{executor(ctx($resolve,record,1),ctx($reject,record,1))}catch(err){$reject.call(record,err)}};$.mix(P.prototype,{then:function then(onFulfilled,onRejected){var S=assertObject(assertObject(this).constructor)[SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false};var promise=react.P=new(S!=undefined?S:P)(function(res,rej){react.res=assertFunction(res);react.rej=assertFunction(rej)});var record=this[RECORD];record.c.push(react);record.s&¬ify(record);return promise},"catch":function(onRejected){return this.then(undefined,onRejected)}})}$def($def.G+$def.W+$def.F*(P!=Base),{Promise:P});cof.set(P,PROMISE);require("./$.species")(P);$def($def.S,PROMISE,{reject:function reject(r){return new(getConstructor(this))(function(res,rej){rej(r)})},resolve:function resolve(x){return isObject(x)&&RECORD in x&&$.getProto(x)===this.prototype?x:new(getConstructor(this))(function(res){res(x)})}});$def($def.S+$def.F*!require("./$.iter-detect")(function(iter){P.all(iter)["catch"](function(){})}),PROMISE,{all:function all(iterable){var C=getConstructor(this),values=[];return new C(function(res,rej){forOf(iterable,false,values.push,values);var remaining=values.length,results=Array(remaining);if(remaining)$.each.call(values,function(promise,index){C.resolve(promise).then(function(value){results[index]=value;--remaining||res(results)},rej)});else res(results)})},race:function race(iterable){var C=getConstructor(this);return new C(function(res,rej){forOf(iterable,false,function(promise){C.resolve(promise).then(res,rej)})})}})},{"./$":16,"./$.assert":4,"./$.cof":6,"./$.ctx":10,"./$.def":11,"./$.iter":15,"./$.iter-detect":14,"./$.species":22,"./$.task":24,"./$.uid":25,"./$.wks":27}],48:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),setProto=require("./$.set-proto"),$iter=require("./$.iter"),ITER=require("./$.uid").safe("iter"),step=$iter.step,assert=require("./$.assert"),isObject=$.isObject,getDesc=$.getDesc,setDesc=$.setDesc,getProto=$.getProto,apply=Function.apply,assertObject=assert.obj,_isExtensible=Object.isExtensible||$.it;function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);$.set(this,ITER,{o:iterated,a:keys,i:0})}$iter.create(Enumerate,"Object",function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return step(1)}while(!((key=keys[iter.i++])in iter.o));return step(0,key)});function wrap(fn){return function(it){assertObject(it);try{fn.apply(undefined,arguments);return true}catch(e){return false}}}function get(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getDesc(assertObject(target),propertyKey),proto;if(desc)return $.has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getProto(target))?get(proto,propertyKey,receiver):undefined}function set(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getDesc(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getProto(target))){return set(proto,propertyKey,V,receiver)}ownDesc=$.desc(0)}if($.has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getDesc(receiver,propertyKey)||$.desc(0);existingDescriptor.value=V;setDesc(receiver,propertyKey,existingDescriptor);return true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var reflect={apply:require("./$.ctx")(Function.call,apply,3),construct:function construct(target,argumentsList){var proto=assert.fn(arguments.length<3?target:arguments[2]).prototype,instance=$.create(isObject(proto)?proto:Object.prototype),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance},defineProperty:wrap(setDesc),deleteProperty:function deleteProperty(target,propertyKey){var desc=getDesc(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function enumerate(target){return new Enumerate(assertObject(target))},get:get,getOwnPropertyDescriptor:function getOwnPropertyDescriptor(target,propertyKey){return getDesc(assertObject(target),propertyKey)},getPrototypeOf:function getPrototypeOf(target){return getProto(assertObject(target))},has:function has(target,propertyKey){return propertyKey in target},isExtensible:function isExtensible(target){return!!_isExtensible(assertObject(target))},ownKeys:require("./$.own-keys"),preventExtensions:wrap(Object.preventExtensions||$.it),set:set};if(setProto)reflect.setPrototypeOf=function setPrototypeOf(target,proto){setProto.check(target,proto);try{setProto.set(target,proto);return true}catch(e){return false}};$def($def.G,{Reflect:{}});$def($def.S,"Reflect",reflect)},{"./$":16,"./$.assert":4,"./$.ctx":10,"./$.def":11,"./$.iter":15,"./$.own-keys":18,"./$.set-proto":21,"./$.uid":25}],49:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),RegExp=$.g.RegExp,Base=RegExp,proto=RegExp.prototype;if($.FW&&$.DESC){if(!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){RegExp=function RegExp(pattern,flags){return new Base(cof(pattern)=="RegExp"&&flags!==undefined?pattern.source:pattern,flags)};$.each.call($.getNames(Base),function(key){key in RegExp||$.setDesc(RegExp,key,{configurable:true,get:function(){return Base[key]},set:function(it){Base[key]=it}})});proto.constructor=RegExp;RegExp.prototype=proto;$.hide($.g,"RegExp",RegExp)}if(/./g.flags!="g")$.setDesc(proto,"flags",{configurable:true,get:require("./$.replacer")(/^.*\/(\w*)$/,"$1")})}require("./$.species")(RegExp)},{"./$":16,"./$.cof":6,"./$.replacer":20,"./$.species":22}],50:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Set",{add:function add(value){return strong.def(this,value=value===0?0:value,value)}},strong)},{"./$.collection":9,"./$.collection-strong":7}],51:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"String",{codePointAt:require("./$.string-at")(false)})},{"./$.def":11,"./$.string-at":23}],52:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),toLength=$.toLength;$def($def.P,"String",{endsWith:function endsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:Math.min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString}})},{"./$":16,"./$.cof":6,"./$.def":11}],53:[function(require,module,exports){var $def=require("./$.def"),toIndex=require("./$").toIndex,fromCharCode=String.fromCharCode;$def($def.S,"String",{fromCodePoint:function fromCodePoint(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")}})},{"./$":16,"./$.def":11}],54:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P,"String",{includes:function includes(searchString){if(cof(searchString)=="RegExp")throw TypeError();return!!~String($.assertDefined(this)).indexOf(searchString,arguments[1])}})},{"./$":16,"./$.cof":6,"./$.def":11}],55:[function(require,module,exports){var set=require("./$").set,at=require("./$.string-at")(true),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step;$iter.std(String,"String",function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return step(1);point=at.call(O,index);iter.i+=point.length;return step(0,point)})},{"./$":16,"./$.iter":15,"./$.string-at":23,"./$.uid":25}],56:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");$def($def.S,"String",{raw:function raw(callSite){var tpl=$.toObject(callSite.raw),len=$.toLength(tpl.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(tpl[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}})},{"./$":16,"./$.def":11}],57:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def");$def($def.P,"String",{repeat:function repeat(count){var str=String($.assertDefined(this)),res="",n=$.toInteger(count);if(n<0||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res}})},{"./$":16,"./$.def":11}],58:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P,"String",{startsWith:function startsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),index=$.toLength(Math.min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})},{"./$":16,"./$.cof":6,"./$.def":11}],59:[function(require,module,exports){"use strict";var $=require("./$"),setTag=require("./$.cof").set,uid=require("./$.uid"),$def=require("./$.def"),keyOf=require("./$.keyof"),has=$.has,hide=$.hide,getNames=$.getNames,toObject=$.toObject,Symbol=$.g.Symbol,Base=Symbol,setter=false,TAG=uid.safe("tag"),SymbolRegistry={},AllSymbols={};function wrap(tag){var sym=AllSymbols[tag]=$.set($.create(Symbol.prototype),TAG,tag);$.DESC&&setter&&$.setDesc(Object.prototype,tag,{configurable:true,set:function(value){hide(this,tag,value)}});return sym}if(!$.isFunction(Symbol)){Symbol=function Symbol(description){if(this instanceof Symbol)throw TypeError("Symbol is not a constructor");return wrap(uid(description))};hide(Symbol.prototype,"toString",function(){return this[TAG]})}$def($def.G+$def.W,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},keyFor:function keyFor(key){return keyOf(SymbolRegistry,key)},pure:uid.safe,set:$.set,useSetter:function(){setter=true},useSimple:function(){setter=false}};$.each.call(("hasInstance,isConcatSpreadable,iterator,match,replace,search,"+"species,split,toPrimitive,toStringTag,unscopables").split(","),function(it){var sym=require("./$.wks")(it);symbolStatics[it]=Symbol===Base?sym:wrap(sym)});setter=true;$def($def.S,"Symbol",symbolStatics);$def($def.S+$def.F*(Symbol!=Base),"Object",{getOwnPropertyNames:function getOwnPropertyNames(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function getOwnPropertySymbols(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}});setTag(Symbol,"Symbol");setTag(Math,"Math",true);setTag($.g.JSON,"JSON",true)},{"./$":16,"./$.cof":6,"./$.def":11,"./$.keyof":17,"./$.uid":25,"./$.wks":27}],60:[function(require,module,exports){"use strict";var $=require("./$"),weak=require("./$.collection-weak"),leakStore=weak.leakStore,ID=weak.ID,WEAK=weak.WEAK,has=$.has,isObject=$.isObject,isFrozen=Object.isFrozen||$.core.Object.isFrozen,tmp={};var WeakMap=require("./$.collection")("WeakMap",{get:function get(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[ID]]}},set:function set(key,value){return weak.def(this,key,value)}},weak,true,true);if($.FW&&(new WeakMap).set((Object.freeze||Object)(tmp),7).get(tmp)!=7){$.each.call(["delete","has","get","set"],function(key){var method=WeakMap.prototype[key];WeakMap.prototype[key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}},{"./$":16,"./$.collection":9,"./$.collection-weak":8}],61:[function(require,module,exports){"use strict";var weak=require("./$.collection-weak");require("./$.collection")("WeakSet",{add:function add(value){return weak.def(this,value,true)}},weak,false,true)},{"./$.collection":9,"./$.collection-weak":8}],62:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{includes:require("./$.array-includes")(true)});require("./$.unscope")("includes")},{"./$.array-includes":2,"./$.def":11,"./$.unscope":26}],63:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),ownKeys=require("./$.own-keys");$def($def.S,"Object",{getOwnPropertyDescriptors:function getOwnPropertyDescriptors(object){var O=$.toObject(object),result={};$.each.call(ownKeys(O),function(key){$.setDesc(result,key,$.desc(0,$.getDesc(O,key)))});return result}})},{"./$":16,"./$.def":11,"./$.own-keys":18}],64:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");function createObjectToArray(isEntries){return function(object){var O=$.toObject(object),keys=$.getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$def($def.S,"Object",{values:createObjectToArray(false),entries:createObjectToArray(true)})},{"./$":16,"./$.def":11}],65:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"RegExp",{escape:require("./$.replacer")(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})},{"./$.def":11,"./$.replacer":20}],66:[function(require,module,exports){var $def=require("./$.def"),forOf=require("./$.iter").forOf;$def($def.P,"Set",{toJSON:function(){var arr=[];forOf(this,false,arr.push,arr);return arr}})},{"./$.def":11,"./$.iter":15}],67:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"String",{at:require("./$.string-at")(true)})},{"./$.def":11,"./$.string-at":23}],68:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),$Array=$.core.Array||Array,statics={};function setStatics(keys,length){$.each.call(keys.split(","),function(key){if(length==undefined&&key in $Array)statics[key]=$Array[key];else if(key in[])statics[key]=require("./$.ctx")(Function.call,[][key],length)})}setStatics("pop,reverse,shift,keys,values,entries",1);setStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$def($def.S,"Array",statics)},{"./$":16,"./$.ctx":10,"./$.def":11}],69:[function(require,module,exports){require("./es6.array.iterator");var $=require("./$"),Iterators=require("./$.iter").Iterators,ITERATOR=require("./$.wks")("iterator"),NodeList=$.g.NodeList;if($.FW&&NodeList&&!(ITERATOR in NodeList.prototype)){$.hide(NodeList.prototype,ITERATOR,Iterators.Array)}Iterators.NodeList=Iterators.Array},{"./$":16,"./$.iter":15,"./$.wks":27,"./es6.array.iterator":34}],70:[function(require,module,exports){var $def=require("./$.def"),$task=require("./$.task");$def($def.G+$def.B,{setImmediate:$task.set,clearImmediate:$task.clear})},{"./$.def":11,"./$.task":24}],71:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),invoke=require("./$.invoke"),partial=require("./$.partial"),MSIE=!!$.g.navigator&&/MSIE .\./.test(navigator.userAgent);function wrap(set){return MSIE?function(fn,time){return set(invoke(partial,[].slice.call(arguments,2),$.isFunction(fn)?fn:Function(fn)),time)}:set}$def($def.G+$def.B+$def.F*MSIE,{setTimeout:wrap($.g.setTimeout),setInterval:wrap($.g.setInterval)})},{"./$":16,"./$.def":11,"./$.invoke":13,"./$.partial":19}],72:[function(require,module,exports){require("./modules/es5");require("./modules/es6.symbol");require("./modules/es6.object.assign");require("./modules/es6.object.is");require("./modules/es6.object.set-prototype-of");require("./modules/es6.object.to-string");require("./modules/es6.object.statics-accept-primitives");require("./modules/es6.function.name");require("./modules/es6.number.constructor");require("./modules/es6.number.statics");require("./modules/es6.math");require("./modules/es6.string.from-code-point");require("./modules/es6.string.raw");require("./modules/es6.string.iterator");require("./modules/es6.string.code-point-at");require("./modules/es6.string.ends-with");require("./modules/es6.string.includes");require("./modules/es6.string.repeat");require("./modules/es6.string.starts-with");require("./modules/es6.array.from");require("./modules/es6.array.of");require("./modules/es6.array.iterator");require("./modules/es6.array.species");require("./modules/es6.array.copy-within");require("./modules/es6.array.fill");require("./modules/es6.array.find");require("./modules/es6.array.find-index");require("./modules/es6.regexp");require("./modules/es6.promise");require("./modules/es6.map");require("./modules/es6.set");require("./modules/es6.weak-map");require("./modules/es6.weak-set");require("./modules/es6.reflect");require("./modules/es7.array.includes");require("./modules/es7.string.at");require("./modules/es7.regexp.escape");require("./modules/es7.object.get-own-property-descriptors");require("./modules/es7.object.to-array");require("./modules/es7.set.to-json");require("./modules/js.array.statics");require("./modules/web.timers");require("./modules/web.immediate");require("./modules/web.dom.iterable");module.exports=require("./modules/$").core},{"./modules/$":16,"./modules/es5":28,"./modules/es6.array.copy-within":29,"./modules/es6.array.fill":30,"./modules/es6.array.find":32,"./modules/es6.array.find-index":31,"./modules/es6.array.from":33,"./modules/es6.array.iterator":34,"./modules/es6.array.of":35,"./modules/es6.array.species":36,"./modules/es6.function.name":37,"./modules/es6.map":38,"./modules/es6.math":39,"./modules/es6.number.constructor":40,"./modules/es6.number.statics":41,"./modules/es6.object.assign":42,"./modules/es6.object.is":43,"./modules/es6.object.set-prototype-of":44,"./modules/es6.object.statics-accept-primitives":45,"./modules/es6.object.to-string":46,"./modules/es6.promise":47,"./modules/es6.reflect":48,"./modules/es6.regexp":49,"./modules/es6.set":50,"./modules/es6.string.code-point-at":51,"./modules/es6.string.ends-with":52,"./modules/es6.string.from-code-point":53,"./modules/es6.string.includes":54,"./modules/es6.string.iterator":55,"./modules/es6.string.raw":56,"./modules/es6.string.repeat":57,"./modules/es6.string.starts-with":58,"./modules/es6.symbol":59,"./modules/es6.weak-map":60,"./modules/es6.weak-set":61,"./modules/es7.array.includes":62,"./modules/es7.object.get-own-property-descriptors":63,"./modules/es7.object.to-array":64,"./modules/es7.regexp.escape":65,"./modules/es7.set.to-json":66,"./modules/es7.string.at":67,"./modules/js.array.statics":68,"./modules/web.dom.iterable":69,"./modules/web.immediate":70,"./modules/web.timers":71}],73:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){var generator=Object.create((outerFn||Generator).prototype);generator._invoke=makeInvokeMethod(innerFn,self||null,new Context(tryLocsList||[]));return generator}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator,"next");var callThrow=step.bind(generator,"throw");function step(method,arg){var record=tryCatch(generator[method],generator,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function makeInvokeMethod(innerFn,self,context){var state=GenStateSuspendedStart;return function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){if(method==="return"||method==="throw"&&delegate.iterator.throw===undefined){context.delegate=null;var returnMethod=delegate.iterator.return;if(returnMethod){var record=tryCatch(returnMethod,delegate.iterator,arg);if(record.type==="throw"){method="throw";arg=record.arg;continue}}if(method==="return"){continue}}var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;method="throw";arg=record.arg}}}}function defineGeneratorMethod(method){Gp[method]=function(arg){return this._invoke(method,arg)}}defineGeneratorMethod("next");defineGeneratorMethod("throw");defineGeneratorMethod("return");Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;
this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.next=finallyEntry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){return this.complete(entry.completion,entry.afterLoc)}}},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:typeof self==="object"?self:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]); |
ajax/libs/inferno/1.0.0-alpha3/inferno-compat.js | sashberd/cdnjs | /*!
* inferno-compat v1.0.0-alpha3
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.InfernoCompat = global.InfernoCompat || {})));
}(this, (function (exports) { 'use strict';
var Lifecycle = function Lifecycle() {
this._listeners = [];
};
Lifecycle.prototype.addListener = function addListener (callback) {
this._listeners.push(callback);
};
Lifecycle.prototype.trigger = function trigger () {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
};
var NO_OP = '$NO_OP';
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isStatefulComponent(o) {
var component = o.component;
return !isUndefined(component.prototype) && !isUndefined(component.prototype.render);
}
function isStringOrNumber(obj) {
return isString(obj) || isNumber(obj);
}
function isNullOrUndef(obj) {
return isUndefined(obj) || isNull(obj);
}
function isInvalid(obj) {
return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj);
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isAttrAnEvent(attr) {
return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3;
}
function isString(obj) {
return typeof obj === 'string';
}
function isNumber(obj) {
return typeof obj === 'number';
}
function isNull(obj) {
return obj === null;
}
function isTrue(obj) {
return obj === true;
}
function isUndefined(obj) {
return obj === undefined;
}
function isObject(o) {
return typeof o === 'object';
}
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
var EMPTY_OBJ = {};
var NodeTypes = {
ELEMENT: 1,
OPT_ELEMENT: 2,
TEXT: 3,
FRAGMENT: 4,
OPT_BLUEPRINT: 5,
COMPONENT: 6,
PLACEHOLDER: 7
};
var ValueTypes = {
CHILDREN: 1,
PROP_CLASS_NAME: 2,
PROP_STYLE: 3,
PROP_DATA: 4,
PROP_REF: 5,
PROP_SPREAD: 6,
PROP_VALUE: 7,
PROP: 8
};
var ChildrenTypes = {
NON_KEYED: 1,
KEYED: 2,
NODE: 3,
TEXT: 4,
UNKNOWN: 5
};
function convertVOptElementToVElement(optVElement) {
var bp = optVElement.bp;
var staticElement = bp.staticVElement;
var vElement = createVElement(staticElement.tag, null, null, optVElement.key, null, null);
var bp0 = bp.v0;
var staticChildren = staticElement.children;
var staticProps = staticElement.props;
if (!isNull(staticChildren)) {
vElement.children = staticChildren;
}
if (!isNull(staticProps)) {
vElement.props = staticProps;
}
if (!isNull(bp0)) {
attachOptVElementValue(vElement, optVElement, bp0, optVElement.v0, bp.d0);
var bp1 = bp.v1;
if (!isNull(bp1)) {
attachOptVElementValue(vElement, optVElement, bp1, optVElement.v1, bp.d1);
var bp2 = bp.v2;
if (!isNull(bp2)) {
attachOptVElementValue(vElement, optVElement, bp2, optVElement.v2, bp.d2);
var bp3 = bp.v3;
if (!isNull(bp3)) {
var v3 = optVElement.v3;
var d3 = bp.d3;
var bp3$1 = bp.v3;
for (var i = 0; i < bp3$1.length; i++) {
attachOptVElementValue(vElement, optVElement, bp3$1[i], v3[i], d3[i]);
}
}
}
}
}
return vElement;
}
function attachOptVElementValue(vElement, vOptElement, valueType, value, descriptor) {
switch (valueType) {
case ValueTypes.CHILDREN:
vElement.childrenType = descriptor;
if (isNullOrUndef(vElement.children)) {
vElement.children = value;
} else {
debugger;
}
break;
case ValueTypes.PROP_CLASS_NAME:
if (!vElement.props) {
vElement.props = { className: value };
} else {
debugger;
}
break;
case ValueTypes.PROP_DATA:
if (!vElement.props) {
vElement.props = {};
}
vElement.props['data-' + descriptor] = value;
break;
case ValueTypes.PROP_STYLE:
if (!vElement.props) {
vElement.props = { style: value };
} else {
debugger;
}
break;
case ValueTypes.PROP_VALUE:
if (!vElement.props) {
vElement.props = { value: value };
} else {
debugger;
}
break;
case ValueTypes.PROP:
if (!vElement.props) {
vElement.props = {};
}
vElement.props[descriptor] = value;
break;
case ValueTypes.PROP_REF:
vElement.ref = value;
break;
case ValueTypes.PROP_SPREAD:
if (!vElement.props) {
vElement.props = value;
} else {
debugger;
}
break;
}
}
function cloneVNode(vNodeToClone, props) {
var children = [], len = arguments.length - 2;
while ( len-- > 0 ) children[ len ] = arguments[ len + 2 ];
if (children.length > 0 && !isNull(children[0])) {
if (!props) {
props = {};
}
if (children.length === 1) {
children = children[0];
}
if (isUndefined(props.children)) {
props.children = children;
} else {
if (isArray(children)) {
if (isArray(props.children)) {
props.children = props.children.concat(children);
} else {
props.children = [props.children].concat(children);
}
} else {
if (isArray(props.children)) {
props.children.push(children);
} else {
props.children = [props.children];
props.children.push(children);
}
}
}
} else {
children = null;
}
var newVNode;
if (isArray(vNodeToClone)) {
newVNode = vNodeToClone.map(function (vNode) { return cloneVNode(vNode); });
} else if (isNullOrUndef(props) && isNullOrUndef(children)) {
newVNode = Object.assign({}, vNodeToClone);
} else {
if (isVComponent(vNodeToClone)) {
newVNode = createVComponent(vNodeToClone.component,
Object.assign({}, vNodeToClone.props, props),
vNodeToClone.key,
vNodeToClone.hooks,
vNodeToClone.ref
);
} else if (isVElement(vNodeToClone)) {
newVNode = createVElement(vNodeToClone.tag,
Object.assign({}, vNodeToClone.props, props),
(props && props.children) || children || vNodeToClone.children,
vNodeToClone.key,
vNodeToClone.ref,
ChildrenTypes.UNKNOWN
);
} else if (isOptVElement(vNodeToClone)) {
newVNode = cloneVNode(convertVOptElementToVElement(vNodeToClone), props, children);
}
}
newVNode.dom = null;
return newVNode;
}
function createOptBlueprint(staticVElement, v0, d0, v1, d1, v2, d2, v3, d3) {
return {
clone: null,
d0: d0,
d1: d1,
d2: d2,
d3: d3,
pools: {
nonKeyed: [],
keyed: new Map()
},
staticVElement: staticVElement,
type: NodeTypes.OPT_BLUEPRINT,
v0: v0,
v1: v1,
v2: v2,
v3: v3
};
}
function createVComponent(component, props, key, hooks, ref) {
return {
component: component,
dom: null,
hooks: hooks || null,
instance: null,
key: key,
props: props,
ref: ref || null,
type: NodeTypes.COMPONENT
};
}
function createVText(text) {
return {
dom: null,
text: text,
type: NodeTypes.TEXT
};
}
function createVElement(tag, props, children, key, ref, childrenType) {
return {
children: children,
childrenType: childrenType || ChildrenTypes.UNKNOWN,
dom: null,
key: key,
props: props,
ref: ref || null,
tag: tag,
type: NodeTypes.ELEMENT
};
}
function createStaticVElement(tag, props, children) {
return {
children: children,
props: props,
tag: tag,
type: NodeTypes.ELEMENT
};
}
function createVFragment(children, childrenType) {
return {
children: children,
childrenType: childrenType || ChildrenTypes.UNKNOWN,
dom: null,
pointer: null,
type: NodeTypes.FRAGMENT
};
}
function createVPlaceholder() {
return {
dom: null,
type: NodeTypes.PLACEHOLDER
};
}
function isVElement(o) {
return o.type === NodeTypes.ELEMENT;
}
function isOptVElement(o) {
return o.type === NodeTypes.OPT_ELEMENT;
}
function isVComponent(o) {
return o.type === NodeTypes.COMPONENT;
}
function isVText(o) {
return o.type === NodeTypes.TEXT;
}
function isVFragment(o) {
return o.type === NodeTypes.FRAGMENT;
}
function isVPlaceholder(o) {
return o.type === NodeTypes.PLACEHOLDER;
}
function isVNode(o) {
return !isUndefined(o.type);
}
function isUnknownChildrenType(o) {
return o === ChildrenTypes.UNKNOWN;
}
function isKeyedListChildrenType(o) {
return o === ChildrenTypes.KEYED;
}
function isNonKeyedListChildrenType(o) {
return o === ChildrenTypes.NON_KEYED;
}
function isTextChildrenType(o) {
return o === ChildrenTypes.TEXT;
}
function isNodeChildrenType(o) {
return o === ChildrenTypes.NODE;
}
var recyclingEnabled = true;
var vComponentPools = new Map();
function recycleOptVElement(optVElement, lifecycle, context, isSVG, shallowUnmount) {
var bp = optVElement.bp;
var key = optVElement.key;
var pool = key === null ? bp.pools.nonKeyed : bp.pools.keyed.get(key);
if (!isUndefined(pool)) {
var recycledOptVElement = pool.pop();
if (!isUndefined(recycledOptVElement)) {
patchOptVElement(recycledOptVElement, optVElement, null, lifecycle, context, isSVG, shallowUnmount);
return optVElement.dom;
}
}
return null;
}
function poolOptVElement(optVElement) {
var bp = optVElement.bp;
var key = optVElement.key;
var pools = bp.pools;
if (isNull(key)) {
pools.nonKeyed.push(optVElement);
} else {
var pool = pools.keyed.get(key);
if (isUndefined(pool)) {
pool = [];
pools.keyed.set(key, pool);
}
pool.push(optVElement);
}
}
function recycleVComponent(vComponent, lifecycle, context, isSVG, shallowUnmount) {
var component = vComponent.component;
var key = vComponent.key;
var pools = vComponentPools.get(component);
if (!isUndefined(pools)) {
var pool = key === null ? pools.nonKeyed : pools.keyed.get(key);
if (!isUndefined(pool)) {
var recycledVComponent = pool.pop();
if (!isUndefined(recycledVComponent)) {
var failed = patchVComponent(recycledVComponent, vComponent, null, lifecycle, context, isSVG, shallowUnmount);
if (!failed) {
return vComponent.dom;
}
}
}
}
return null;
}
function poolVComponent(vComponent) {
var component = vComponent.component;
var key = vComponent.key;
var pools = vComponentPools.get(component);
if (isUndefined(pools)) {
pools = {
nonKeyed: [],
keyed: new Map()
};
vComponentPools.set(component, pools);
}
if (isNull(key)) {
pools.nonKeyed.push(vComponent);
} else {
var pool = pools.keyed.get(key);
if (isUndefined(pool)) {
pool = [];
pools.keyed.set(key, pool);
}
pool.push(vComponent);
}
}
function unmount(input, parentDom, lifecycle, canRecycle, shallowUnmount) {
if (!isInvalid(input)) {
if (isOptVElement(input)) {
unmountOptVElement(input, parentDom, lifecycle, canRecycle, shallowUnmount);
} else if (isVComponent(input)) {
unmountVComponent(input, parentDom, lifecycle, canRecycle, shallowUnmount);
} else if (isVElement(input)) {
unmountVElement(input, parentDom, lifecycle, shallowUnmount);
} else if (isVFragment(input)) {
unmountVFragment(input, parentDom, true, lifecycle, shallowUnmount);
} else if (isVText(input)) {
unmountVText(input, parentDom);
} else if (isVPlaceholder(input)) {
unmountVPlaceholder(input, parentDom);
}
}
}
function unmountVPlaceholder(vPlaceholder, parentDom) {
if (parentDom) {
removeChild(parentDom, vPlaceholder.dom);
}
}
function unmountVText(vText, parentDom) {
if (parentDom) {
removeChild(parentDom, vText.dom);
}
}
function unmountOptVElement(optVElement, parentDom, lifecycle, canRecycle, shallowUnmount) {
var bp = optVElement.bp;
var bp0 = bp.v0;
var dom = bp.dom;
if (!shallowUnmount) {
if (!isNull(bp0)) {
unmountOptVElementValue(optVElement, bp0, optVElement.v0, lifecycle);
var bp1 = bp.v1;
if (!isNull(bp1)) {
unmountOptVElementValue(optVElement, bp1, optVElement.v1, lifecycle);
var bp2 = bp.v2;
if (!isNull(bp2)) {
unmountOptVElementValue(optVElement, bp2, optVElement.v2, lifecycle);
}
}
}
}
if (!isNull(parentDom)) {
parentDom.removeChild(optVElement.dom);
}
if (recyclingEnabled && (parentDom || canRecycle)) {
poolOptVElement(optVElement);
}
}
function unmountOptVElementValue(optVElement, valueType, value, lifecycle) {
switch (valueType) {
case ValueTypes.CHILDREN:
unmountChildren(value, lifecycle);
break;
case ValueTypes.PROP_REF:
unmountRef(value);
break;
case ValueTypes.PROP_SPREAD:
unmountProps(value, lifecycle);
break;
}
}
function unmountVFragment(vFragment, parentDom, removePointer, lifecycle, shallowUnmount) {
var children = vFragment.children;
var childrenLength = children.length;
var pointer = vFragment.pointer;
if (!shallowUnmount && childrenLength > 0) {
for (var i = 0; i < childrenLength; i++) {
var child = children[i];
if (isVFragment(child)) {
unmountVFragment(child, parentDom, true, lifecycle, false);
} else {
unmount(child, parentDom, lifecycle, false);
}
}
}
if (parentDom && removePointer) {
removeChild(parentDom, pointer);
}
}
function unmountVComponent(vComponent, parentDom, lifecycle, canRecycle, shallowUnmount) {
if (!shallowUnmount) {
var instance = vComponent.instance;
var instanceHooks = null;
var instanceChildren = null;
vComponent.unmounted = true;
if (!isNullOrUndef(instance)) {
var ref = vComponent.ref;
if (ref) {
ref(null);
}
instanceHooks = instance.hooks;
instanceChildren = instance.children;
if (instance.render !== undefined) {
instance.componentWillUnmount();
instance._unmounted = true;
componentToDOMNodeMap.delete(instance);
unmount(instance._lastInput, null, lifecycle, false);
} else {
unmount(instance, null, lifecycle, false);
}
}
var hooks = vComponent.hooks || instanceHooks;
if (!isNullOrUndef(hooks)) {
if (!isNullOrUndef(hooks.onComponentWillUnmount)) {
hooks.onComponentWillUnmount(hooks);
}
}
}
if (parentDom) {
removeChild(parentDom, vComponent.dom);
}
if (recyclingEnabled && (parentDom || canRecycle)) {
poolVComponent(vComponent);
}
}
function unmountVElement(vElement, parentDom, lifecycle, shallowUnmount) {
var hooks = vElement.hooks;
var dom = vElement.dom;
var ref = vElement.ref;
if (!shallowUnmount) {
if (ref) {
unmountRef(ref);
}
var children = vElement.children;
if (!isNullOrUndef(children)) {
unmountChildren(children, lifecycle);
}
}
if (parentDom) {
removeChild(parentDom, dom);
}
}
function unmountChildren(children, lifecycle) {
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (isObject(child)) {
unmount(child, null, lifecycle, false);
}
}
} else if (isObject(children)) {
unmount(children, null, lifecycle, false);
}
}
function unmountRef(ref) {
if (isFunction(ref)) {
ref(null);
} else {
if ("development" !== 'production') {
throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
}
throwError();
}
}
function unmountProps(props, lifecycle) {
for (var prop in props) {
var value = props[prop];
if (prop === 'ref') {
unmountRef(value);
}
}
}
function replaceLastChildAndUnmount(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount) {
replaceChild(parentDom, mount(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
function patch(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount) {
if (lastInput !== nextInput) {
if (isOptVElement(nextInput)) {
if (isOptVElement(lastInput)) {
patchOptVElement(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
replaceChild(parentDom, mountOptVElement(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isOptVElement(lastInput)) {
replaceLastChildAndUnmount(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVComponent(nextInput)) {
if (isVComponent(lastInput)) {
patchVComponent(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
replaceChild(parentDom, mountVComponent(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isVComponent(lastInput)) {
replaceLastChildAndUnmount(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVElement(nextInput)) {
if (isVElement(lastInput)) {
patchVElement(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
replaceChild(parentDom, mountVElement(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isVFragment(nextInput)) {
if (isVFragment(lastInput)) {
patchVFragment(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
replaceChild(parentDom, mountVFragment(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isVFragment(lastInput)) {
replaceVListWithNode(parentDom, lastInput, mount(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lifecycle, shallowUnmount);
} else if (isVElement(lastInput)) {
replaceLastChildAndUnmount(lastInput, nextInput, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVText(nextInput)) {
if (isVText(lastInput)) {
patchVText(lastInput, nextInput, false, shallowUnmount);
} else {
replaceChild(parentDom, mountVText(nextInput, null), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isVText(lastInput)) {
replaceChild(parentDom, mount(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
} else if (isVPlaceholder(nextInput)) {
if (isVPlaceholder(lastInput)) {
patchVPlaceholder(lastInput, nextInput);
} else {
replaceChild(parentDom, mountVPlaceholder(nextInput, null), lastInput.dom);
unmount(lastInput, null, lifecycle, false, shallowUnmount);
}
} else if (isVPlaceholder(lastInput)) {
replaceChild(parentDom, mount(nextInput, null, lifecycle, context, isSVG, shallowUnmount), lastInput.dom);
} else {
if ("development" !== 'production') {
throwError('bad input argument called on patch(). Input argument may need normalising.');
}
throwError();
}
}
}
function patchVElement(lastVElement, nextVElement, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var nextTag = nextVElement.tag;
var lastTag = lastVElement.tag;
if (nextTag === 'svg') {
isSVG = true;
}
if (lastTag !== nextTag) {
replaceWithNewNode(lastVElement, nextVElement, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
var dom = lastVElement.dom;
var lastProps = lastVElement.props;
var nextProps = nextVElement.props;
var lastChildren = lastVElement.children;
var nextChildren = nextVElement.children;
nextVElement.dom = dom;
if (lastChildren !== nextChildren) {
var lastChildrenType = lastVElement.childrenType;
var nextChildrenType = nextVElement.childrenType;
if (lastChildrenType === nextChildrenType) {
patchChildren(lastChildrenType, lastChildren, nextChildren, dom, lifecycle, context, isSVG, shallowUnmount);
} else {
patchChildrenWithUnknownType(lastChildren, nextChildren, dom, lifecycle, context, isSVG, shallowUnmount);
}
}
if (lastProps !== nextProps) {
var formValue = patchProps(lastProps, nextProps, dom, shallowUnmount);
if (nextTag === 'select') {
formSelectValue(dom, formValue);
}
}
}
}
function patchOptVElement(lastOptVElement, nextOptVElement, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var dom = lastOptVElement.dom;
var lastBp = lastOptVElement.bp;
var nextBp = nextOptVElement.bp;
nextOptVElement.dom = dom;
if (lastBp !== nextBp) {
var newDom = mountOptVElement(nextOptVElement, null, lifecycle, context, isSVG, shallowUnmount);
replaceChild(parentDom, newDom, dom);
unmount(lastOptVElement, null, lifecycle, true, shallowUnmount);
} else {
var bp0 = nextBp.v0;
var tag = nextBp.staticVElement.tag;
var ignoreDiff = false;
if (tag === 'svg') {
isSVG = true;
} else if (tag === 'input') {
// input elements are problematic due to the large amount of internal state that hold
// so instead of making lots of assumptions, we instead reset common values and re-apply
// the the patching each time
resetFormInputProperties(dom);
ignoreDiff = true;
} else if (tag === 'select') {
} else if (tag === 'textarea') {
// textarea elements are like input elements, except they have sligthly less internal state to
// worry about
ignoreDiff = true;
}
if (!isNull(bp0)) {
var lastV0 = lastOptVElement.v0;
var nextV0 = nextOptVElement.v0;
var bp1 = nextBp.v1;
if (lastV0 !== nextV0 || ignoreDiff) {
patchOptVElementValue(bp0, lastV0, nextV0, nextBp.d0, dom, lifecycle, context, isSVG, shallowUnmount);
}
if (!isNull(bp1)) {
var lastV1 = lastOptVElement.v1;
var nextV1 = nextOptVElement.v1;
var bp2 = nextBp.v2;
if (lastV1 !== nextV1 || ignoreDiff) {
patchOptVElementValue(bp1, lastV1, nextV1, nextBp.d1, dom, lifecycle, context, isSVG, shallowUnmount);
}
if (!isNull(bp2)) {
var lastV2 = lastOptVElement.v2;
var nextV2 = nextOptVElement.v2;
var bp3 = nextBp.v3;
if (lastV2 !== nextV2 || ignoreDiff) {
patchOptVElementValue(bp2, lastV2, nextV2, nextBp.d2, dom, lifecycle, context, isSVG, shallowUnmount);
}
if (!isNull(bp3)) {
var d3 = nextBp.d3;
var lastV3s = lastOptVElement.v3;
var nextV3s = nextOptVElement.v3;
for (var i = 0; i < lastV3s.length; i++) {
var lastV3 = lastV3s[i];
var nextV3 = nextV3s[i];
if (lastV3 !== nextV3 || ignoreDiff) {
patchOptVElementValue(bp3[i], lastV3, nextV3, d3[i], dom, lifecycle, context, isSVG, shallowUnmount);
}
}
}
}
}
}
if (tag === 'select') {
formSelectValue(dom, getPropFromOptElement(nextOptVElement, ValueTypes.PROP_VALUE));
}
}
}
function patchOptVElementValue(valueType, lastValue, nextValue, descriptor, dom, lifecycle, context, isSVG, shallowUnmount) {
switch (valueType) {
case ValueTypes.CHILDREN:
patchChildren(descriptor, lastValue, nextValue, dom, lifecycle, context, isSVG, shallowUnmount);
break;
case ValueTypes.PROP_CLASS_NAME:
if (isNullOrUndef(nextValue)) {
dom.removeAttribute('class');
} else {
if (isSVG) {
dom.setAttribute('class', nextValue);
} else {
dom.className = nextValue;
}
}
break;
case ValueTypes.PROP_DATA:
dom.dataset[descriptor] = nextValue;
break;
case ValueTypes.PROP_STYLE:
patchStyle(lastValue, nextValue, dom);
break;
case ValueTypes.PROP_VALUE:
dom.value = isNullOrUndef(nextValue) ? '' : nextValue;
break;
case ValueTypes.PROP:
patchProp(descriptor, lastValue, nextValue, dom);
break;
case ValueTypes.SPREAD:
patchProps(lastValue, nextValue, dom, shallowUnmount);
break;
}
}
function patchChildren(childrenType, lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount) {
if (isTextChildrenType(childrenType)) {
updateTextContent(parentDom, nextChildren);
} else if (isNodeChildrenType(childrenType)) {
patch(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isKeyedListChildrenType(childrenType)) {
patchKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, null, shallowUnmount);
} else if (isNonKeyedListChildrenType(childrenType)) {
patchNonKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, null, false, shallowUnmount);
} else if (isUnknownChildrenType(childrenType)) {
patchChildrenWithUnknownType(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
if ("development" !== 'production') {
throwError('bad childrenType value specified when attempting to patchChildren.');
}
throwError();
}
}
function patchChildrenWithUnknownType(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount) {
if (isInvalid(nextChildren)) {
if (!isInvalid(lastChildren)) {
removeAllChildren(parentDom, lastChildren, lifecycle, shallowUnmount);
}
} else if (isInvalid(lastChildren)) {
if (isStringOrNumber(nextChildren)) {
setTextContent(parentDom, nextChildren);
} else if (!isInvalid(nextChildren)) {
if (isArray(nextChildren)) {
mountArrayChildrenWithoutType(nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else {
mount(nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
}
}
} else if (isVNode(lastChildren) && isVNode(nextChildren)) {
patch(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isStringOrNumber(nextChildren)) {
if (isStringOrNumber(lastChildren)) {
updateTextContent(parentDom, nextChildren);
} else {
setTextContent(parentDom, nextChildren);
}
} else if (isStringOrNumber(lastChildren)) {
var child = normalise(lastChildren);
child.dom = parentDom.firstChild;
patchChildrenWithUnknownType(child, nextChildren, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isArray(nextChildren)) {
if (isArray(lastChildren)) {
nextChildren.complex = lastChildren.complex;
if (isKeyed(lastChildren, nextChildren)) {
patchKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, null, shallowUnmount);
} else {
patchNonKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, null, true, shallowUnmount);
}
} else {
patchNonKeyedChildren([lastChildren], nextChildren, parentDom, lifecycle, context, isSVG, null, true, shallowUnmount);
}
} else if (isArray(lastChildren)) {
patchNonKeyedChildren(lastChildren, [nextChildren], parentDom, lifecycle, context, isSVG, null, true, shallowUnmount);
} else {
if ("development" !== 'production') {
throwError('bad input argument called on patchChildrenWithUnknownType(). Input argument may need normalising.');
}
throwError();
}
}
function patchVComponent(lastVComponent, nextVComponent, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var lastComponent = lastVComponent.component;
var nextComponent = nextVComponent.component;
var nextProps = nextVComponent.props || {};
if (lastComponent !== nextComponent) {
if (isStatefulComponent(nextVComponent)) {
var lastInstance = lastVComponent.instance;
var nextInstance = createStatefulComponentInstance(nextComponent, nextProps, context, isSVG);
// we use || lastInstance because stateless components store their lastInstance
var lastInput = lastInstance._lastInput || lastInstance;
var nextInput = nextInstance._lastInput;
var ref = nextVComponent.ref;
nextInstance._vComponent = nextVComponent;
nextVComponent.instance = nextInstance;
patch(lastInput, nextInput, parentDom, lifecycle, nextInstance._childContext, isSVG, true);
mountStatefulComponentCallbacks(ref, nextInstance, lifecycle);
nextVComponent.dom = nextInput.dom;
componentToDOMNodeMap.set(nextInstance, nextInput.dom);
} else {
var lastInput$1 = lastVComponent.instance._lastInput || lastVComponent.instance;
var nextInput$1 = createStatelessComponentInput(nextComponent, nextProps, context);
patch(lastInput$1, nextInput$1, parentDom, lifecycle, context, isSVG, true);
var dom = nextVComponent.dom = nextInput$1.dom;
nextVComponent.instance = nextInput$1;
mountStatelessComponentCallbacks(nextVComponent.hooks, dom, lifecycle);
}
unmount(lastVComponent, null, lifecycle, false, shallowUnmount);
} else {
if (isStatefulComponent(nextVComponent)) {
var instance = lastVComponent.instance;
if (instance._unmounted) {
if (isNull(parentDom)) {
return true;
}
replaceChild(parentDom, mountVComponent(nextVComponent, null, lifecycle, context, isSVG, shallowUnmount), lastVComponent.dom);
} else {
var lastProps = instance.props;
var lastState = instance.state;
var nextState = instance.state;
var childContext = instance.getChildContext();
nextVComponent.instance = instance;
instance.context = context;
if (!isNullOrUndef(childContext)) {
context = Object.assign({}, context, childContext);
}
var lastInput$2 = instance._lastInput;
var nextInput$2 = instance._updateComponent(lastState, nextState, lastProps, nextProps);
if (nextInput$2 === NO_OP) {
nextInput$2 = lastInput$2;
} else if (isInvalid(nextInput$2)) {
nextInput$2 = createVPlaceholder();
}
instance._lastInput = nextInput$2;
instance._vComponent = nextVComponent;
instance._lastInput = nextInput$2;
patch(lastInput$2, nextInput$2, parentDom, lifecycle, context, isSVG, shallowUnmount);
instance.componentDidUpdate(lastProps, lastState);
nextVComponent.dom = nextInput$2.dom;
componentToDOMNodeMap.set(instance, nextInput$2.dom);
}
} else {
var shouldUpdate = true;
var lastProps$1 = lastVComponent.props;
var nextHooks = nextVComponent.hooks;
var nextHooksDefined = !isNullOrUndef(nextHooks);
var lastInput$3 = lastVComponent.instance;
nextVComponent.dom = lastVComponent.dom;
nextVComponent.instance = lastInput$3;
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentShouldUpdate)) {
shouldUpdate = nextHooks.onComponentShouldUpdate(lastProps$1, nextProps);
}
if (shouldUpdate !== false) {
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentWillUpdate)) {
nextHooks.onComponentWillUpdate(lastProps$1, nextProps);
}
var nextInput$3 = nextComponent(nextProps, context);
if (nextInput$3 === NO_OP) {
return false;
} else if (isInvalid(nextInput$3)) {
nextInput$3 = createVPlaceholder();
}
patch(lastInput$3, nextInput$3, parentDom, lifecycle, context, isSVG, shallowUnmount);
nextVComponent.instance = nextInput$3;
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentDidUpdate)) {
nextHooks.onComponentDidUpdate(lastProps$1, nextProps);
}
}
}
}
return false;
}
function patchVText(lastVText, nextVText) {
var nextText = nextVText.text;
var dom = lastVText.dom;
nextVText.dom = dom;
if (lastVText.text !== nextText) {
dom.nodeValue = nextText;
}
}
function patchVPlaceholder(lastVPlacholder, nextVPlacholder) {
nextVPlacholder.dom = lastVPlacholder.dom;
}
function patchVFragment(lastVFragment, nextVFragment, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var lastChildren = lastVFragment.children;
var nextChildren = nextVFragment.children;
var pointer = lastVFragment.pointer;
nextVFragment.dom = lastVFragment.dom;
nextVFragment.pointer = pointer;
if (!lastChildren !== nextChildren) {
var lastChildrenType = lastVFragment.childrenType;
var nextChildrenType = nextVFragment.childrenType;
if (lastChildrenType === nextChildrenType) {
if (isKeyedListChildrenType(nextChildrenType)) {
return patchKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, nextVFragment, shallowUnmount);
} else if (isNonKeyedListChildrenType(nextChildrenType)) {
return patchNonKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, nextVFragment, false, shallowUnmount);
}
}
if (isKeyed(lastChildren, nextChildren)) {
patchKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, nextVFragment, shallowUnmount);
} else {
patchNonKeyedChildren(lastChildren, nextChildren, parentDom, lifecycle, context, isSVG, nextVFragment, true, shallowUnmount);
}
}
}
function patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, parentVList, shouldNormalise, shallowUnmount) {
var lastChildrenLength = lastChildren.length;
var nextChildrenLength = nextChildren.length;
var commonLength = lastChildrenLength > nextChildrenLength ? nextChildrenLength : lastChildrenLength;
var i = 0;
for (; i < commonLength; i++) {
var lastChild = lastChildren[i];
var nextChild = shouldNormalise ? normaliseChild(nextChildren, i) : nextChildren[i];
patch(lastChild, nextChild, dom, lifecycle, context, isSVG, shallowUnmount);
}
if (lastChildrenLength < nextChildrenLength) {
for (i = commonLength; i < nextChildrenLength; i++) {
var child = normaliseChild(nextChildren, i);
insertOrAppend(dom, mount(child, null, lifecycle, context, isSVG, shallowUnmount), parentVList && parentVList.pointer);
}
} else if (lastChildrenLength > nextChildrenLength) {
for (i = commonLength; i < lastChildrenLength; i++) {
unmount(lastChildren[i], dom, lifecycle, false, shallowUnmount);
}
}
}
function patchKeyedChildren(a, b, dom, lifecycle, context, isSVG, parentVList, shallowUnmount) {
var aLength = a.length;
var bLength = b.length;
var aEnd = aLength - 1;
var bEnd = bLength - 1;
var aStart = 0;
var bStart = 0;
var i;
var j;
var aStartNode = a[aStart];
var bStartNode = b[bStart];
var aEndNode = a[aEnd];
var bEndNode = b[bEnd];
var aNode = null;
var bNode = null;
var nextNode;
var nextPos;
var node;
if (aLength === 0) {
if (bLength !== 0) {
mountArrayChildrenWithType(b, dom, lifecycle, context, isSVG, shallowUnmount);
}
return;
} else if (bLength === 0) {
if (aLength !== 0) {
removeAllChildren(dom, a, lifecycle, shallowUnmount);
}
return;
}
// Step 1
/* eslint no-constant-condition: 0 */
outer: while (true) {
// Sync nodes with the same key at the beginning.
while (aStartNode.key === bStartNode.key) {
patch(aStartNode, bStartNode, dom, lifecycle, context, isSVG, shallowUnmount);
aStart++;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aStartNode = a[aStart];
bStartNode = b[bStart];
}
// Sync nodes with the same key at the end.
while (aEndNode.key === bEndNode.key) {
patch(aEndNode, bEndNode, dom, lifecycle, context, isSVG, shallowUnmount);
aEnd--;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aEndNode = a[aEnd];
bEndNode = b[bEnd];
}
// Move and sync nodes from right to left.
if (aEndNode.key === bStartNode.key) {
patch(aEndNode, bStartNode, dom, lifecycle, context, isSVG, shallowUnmount);
insertOrAppend(dom, bStartNode.dom, aStartNode.dom);
aEnd--;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break;
}
aEndNode = a[aEnd];
bStartNode = b[bStart];
// In a real-world scenarios there is a higher chance that next node after the move will be the same, so we
// immediately jump to the start of this prefix/suffix algo.
continue;
}
// Move and sync nodes from left to right.
if (aStartNode.key === bEndNode.key) {
patch(aStartNode, bEndNode, dom, lifecycle, context, isSVG, shallowUnmount);
nextPos = bEnd + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : parentVList && parentVList.pointer;
insertOrAppend(dom, bEndNode.dom, nextNode);
aStart++;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break;
}
aStartNode = a[aStart];
bEndNode = b[bEnd];
continue;
}
break;
}
if (aStart > aEnd) {
if (bStart <= bEnd) {
nextPos = bEnd + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : parentVList && parentVList.pointer;
while (bStart <= bEnd) {
insertOrAppend(dom, mount(b[bStart++], null, lifecycle, context, isSVG, shallowUnmount), nextNode);
}
}
} else if (bStart > bEnd) {
while (aStart <= aEnd) {
unmount(a[aStart++], dom, lifecycle, false, shallowUnmount);
}
} else {
aLength = aEnd - aStart + 1;
bLength = bEnd - bStart + 1;
var aNullable = a;
var sources = new Array(bLength);
// Mark all nodes as inserted.
for (i = 0; i < bLength; i++) {
sources[i] = -1;
}
var moved = false;
var pos = 0;
var patched = 0;
if ((bLength <= 4) || (aLength * bLength <= 16)) {
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLength) {
for (j = bStart; j <= bEnd; j++) {
bNode = b[j];
if (aNode.key === bNode.key) {
sources[j - bStart] = i;
if (pos > j) {
moved = true;
} else {
pos = j;
}
patch(aNode, bNode, dom, lifecycle, context, isSVG, shallowUnmount);
patched++;
aNullable[i] = null;
break;
}
}
}
}
} else {
var keyIndex = new Map();
for (i = bStart; i <= bEnd; i++) {
node = b[i];
keyIndex.set(node.key, i);
}
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLength) {
j = keyIndex.get(aNode.key);
if (!isUndefined(j)) {
bNode = b[j];
sources[j - bStart] = i;
if (pos > j) {
moved = true;
} else {
pos = j;
}
patch(aNode, bNode, dom, lifecycle, context, isSVG, shallowUnmount);
patched++;
aNullable[i] = null;
}
}
}
}
if (aLength === a.length && patched === 0) {
removeAllChildren(dom, a, lifecycle);
while (bStart < bLength) {
insertOrAppend(dom, mount(b[bStart++], null, lifecycle, context, isSVG, shallowUnmount), null);
}
} else {
i = aLength - patched;
while (i > 0) {
aNode = aNullable[aStart++];
if (!isNull(aNode)) {
unmount(aNode, dom, lifecycle, false, shallowUnmount);
i--;
}
}
if (moved) {
var seq = lis_algorithm(sources);
j = seq.length - 1;
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : parentVList && parentVList.pointer;
insertOrAppend(dom, mount(node, dom, lifecycle, context, isSVG, shallowUnmount), nextNode);
} else {
if (j < 0 || i !== seq[j]) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : parentVList && parentVList.pointer;
insertOrAppend(dom, node.dom, nextNode);
} else {
j--;
}
}
}
} else if (patched !== bLength) {
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : parentVList && parentVList.pointer;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG, shallowUnmount), nextNode);
}
}
}
}
}
}
// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
function lis_algorithm(a) {
var p = a.slice(0);
var result = [];
result.push(0);
var i;
var j;
var u;
var v;
var c;
for (i = 0; i < a.length; i++) {
if (a[i] === -1) {
continue;
}
j = result[result.length - 1];
if (a[j] < a[i]) {
p[i] = j;
result.push(i);
continue;
}
u = 0;
v = result.length - 1;
while (u < v) {
c = ((u + v) / 2) | 0;
if (a[result[c]] < a[i]) {
u = c + 1;
} else {
v = c;
}
}
if (a[i] < a[result[u]]) {
if (u > 0) {
p[i] = result[u - 1];
}
result[u] = i;
}
}
u = result.length;
v = result[u - 1];
while (u-- > 0) {
result[u] = v;
v = p[v];
}
return result;
}
// returns true if a property has been applied that can't be cloned via elem.cloneNode()
function patchProp(prop, lastValue, nextValue, dom) {
if (strictProps[prop]) {
dom[prop] = isNullOrUndef(nextValue) ? '' : nextValue;
} else if (booleanProps[prop]) {
dom[prop] = nextValue ? true : false;
} else {
if (lastValue !== nextValue) {
if (isNullOrUndef(nextValue)) {
dom.removeAttribute(prop);
return false;
}
if (prop === 'className') {
dom.className = nextValue;
return false;
} else if (prop === 'style') {
patchStyle(lastValue, nextValue, dom);
} else if (prop === 'defaultChecked') {
if (isNull(lastValue)) {
dom.addAttribute('checked');
}
return false;
} else if (prop === 'defaultValue') {
if (isNull(lastValue)) {
dom.setAttribute('value', nextValue);
}
return false;
} else if (isAttrAnEvent(prop)) {
dom[prop.toLowerCase()] = nextValue;
} else if (prop === 'dangerouslySetInnerHTML') {
var lastHtml = lastValue && lastValue.__html;
var nextHtml = nextValue && nextValue.__html;
if (isNullOrUndef(nextHtml)) {
if ("development" !== 'production') {
throwError('dangerouslySetInnerHTML requires an object with a __html propety containing the innerHTML content.');
}
throwError();
}
if (lastHtml !== nextHtml) {
dom.innerHTML = nextHtml;
}
} else if (prop !== 'childrenType' && prop !== 'ref' && prop !== 'key') {
var ns = namespaces[prop];
if (ns) {
dom.setAttributeNS(ns, prop, nextValue);
} else {
dom.setAttribute(prop, nextValue);
}
return false;
}
}
}
return true;
}
function patchProps(lastProps, nextProps, dom, shallowUnmount) {
lastProps = lastProps || {};
nextProps = nextProps || {};
var formValue;
for (var prop in nextProps) {
var nextValue = nextProps[prop];
var lastValue = lastProps[prop];
if (prop === 'value') {
formValue = nextValue;
}
if (isNullOrUndef(nextValue)) {
removeProp(prop, dom);
} else {
patchProp(prop, lastValue, nextValue, dom);
}
}
for (var prop$1 in lastProps) {
if (isNullOrUndef(nextProps[prop$1])) {
removeProp(prop$1, dom);
}
}
return formValue;
}
function patchStyle(lastAttrValue, nextAttrValue, dom) {
if (isString(nextAttrValue)) {
dom.style.cssText = nextAttrValue;
} else if (isNullOrUndef(lastAttrValue)) {
if (!isNullOrUndef(nextAttrValue)) {
var styleKeys = Object.keys(nextAttrValue);
for (var i = 0; i < styleKeys.length; i++) {
var style = styleKeys[i];
var value = nextAttrValue[style];
if (isNumber(value) && !isUnitlessNumber[style]) {
dom.style[style] = value + 'px';
} else {
dom.style[style] = value;
}
}
}
} else if (isNullOrUndef(nextAttrValue)) {
dom.removeAttribute('style');
} else {
var styleKeys$1 = Object.keys(nextAttrValue);
for (var i$1 = 0; i$1 < styleKeys$1.length; i$1++) {
var style$1 = styleKeys$1[i$1];
var value$1 = nextAttrValue[style$1];
if (isNumber(value$1) && !isUnitlessNumber[style$1]) {
dom.style[style$1] = value$1 + 'px';
} else {
dom.style[style$1] = value$1;
}
}
var lastStyleKeys = Object.keys(lastAttrValue);
for (var i$2 = 0; i$2 < lastStyleKeys.length; i$2++) {
var style$2 = lastStyleKeys[i$2];
if (isNullOrUndef(nextAttrValue[style$2])) {
dom.style[style$2] = '';
}
}
}
}
function removeProp(prop, dom) {
if (prop === 'className') {
dom.removeAttribute('class');
} else if (prop === 'value') {
dom.value = '';
} else {
dom.removeAttribute(prop);
}
}
function constructDefaults(string, object, value) {
/* eslint no-return-assign: 0 */
string.split(',').forEach(function (i) { return object[i] = value; });
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var svgNS = 'http://www.w3.org/2000/svg';
var strictProps = {};
var booleanProps = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
function createStatefulComponentInstance(Component, props, context, isSVG) {
var instance = new Component(props, context);
instance._patch = patch;
instance._componentToDOMNodeMap = componentToDOMNodeMap;
var childContext = instance.getChildContext();
if (!isNullOrUndef(childContext)) {
instance._childContext = Object.assign({}, context, childContext);
} else {
instance._childContext = context;
}
instance._unmounted = false;
instance._pendingSetState = true;
instance._isSVG = isSVG;
instance.componentWillMount();
var input = instance.render();
if (isInvalid(input)) {
input = createVPlaceholder();
}
instance._pendingSetState = false;
instance._lastInput = input;
return instance;
}
function createStatelessComponentInput(component, props, context) {
var input = component(props, context);
if (isInvalid(input)) {
input = createVPlaceholder();
}
return input;
}
function setTextContent(dom, text) {
if (text !== '') {
dom.textContent = text;
} else {
dom.appendChild(document.createTextNode(''));
}
}
function updateTextContent(dom, text) {
dom.firstChild.nodeValue = text;
}
function appendChild(parentDom, dom) {
parentDom.appendChild(dom);
}
function insertOrAppend(parentDom, newNode, nextNode) {
if (isNullOrUndef(nextNode)) {
appendChild(parentDom, newNode);
} else {
parentDom.insertBefore(newNode, nextNode);
}
}
function replaceVListWithNode(parentDom, vList, dom, lifecycle, shallowUnmount) {
var pointer = vList.pointer;
unmountVFragment(vList, parentDom, false, lifecycle, shallowUnmount);
replaceChild(parentDom, dom, pointer);
}
function getPropFromOptElement(optVElement, valueType) {
var bp = optVElement.bp;
// TODO check "prop" and "spread"
if (!isNull(bp.v0)) {
if (bp.v0 === valueType) {
return optVElement.v0;
}
if (!isNull(bp.v1)) {
if (bp.v1 === valueType) {
return optVElement.v1;
}
if (!isNull(bp.v2)) {
if (bp.v2 === valueType) {
return optVElement.v2;
}
}
}
}
}
function documentCreateElement(tag, isSVG) {
var dom;
if (isSVG === true) {
dom = document.createElementNS(svgNS, tag);
} else {
dom = document.createElement(tag);
}
return dom;
}
function replaceWithNewNode(lastNode, nextNode, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var lastInstance = null;
var instanceLastNode = lastNode._lastInput;
if (!isNullOrUndef(instanceLastNode)) {
lastInstance = lastNode;
lastNode = instanceLastNode;
}
unmount(lastNode, null, lifecycle, true, shallowUnmount);
var dom = mount(nextNode, null, lifecycle, context, isSVG, shallowUnmount);
nextNode.dom = dom;
replaceChild(parentDom, dom, lastNode.dom);
if (lastInstance !== null) {
lastInstance._lasInput = nextNode;
}
}
function replaceChild(parentDom, nextDom, lastDom) {
parentDom.replaceChild(nextDom, lastDom);
}
function normalise(object) {
if (isStringOrNumber(object)) {
return createVText(object);
} else if (isInvalid(object)) {
return createVPlaceholder();
} else if (isArray(object)) {
return createVFragment(object);
} else if (isVNode(object) && object.dom) {
return cloneVNode(object);
}
return object;
}
function normaliseChild(children, i) {
var child = children[i];
return children[i] = normalise(child);
}
function removeChild(parentDom, dom) {
parentDom.removeChild(dom);
}
// TODO: for node we need to check if document is valid
function getActiveNode() {
return document.activeElement;
}
function removeAllChildren(dom, children, lifecycle, shallowUnmount) {
dom.textContent = '';
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (!isInvalid(child)) {
unmount(child, null, lifecycle, true, shallowUnmount);
}
}
}
function resetActiveNode(activeNode) {
if (activeNode !== null && activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function isKeyed(lastChildren, nextChildren) {
if (lastChildren.complex) {
return false;
}
return nextChildren.length && !isNullOrUndef(nextChildren[0]) && !isNullOrUndef(nextChildren[0].key)
&& lastChildren.length && !isNullOrUndef(lastChildren[0]) && !isNullOrUndef(lastChildren[0].key);
}
function formSelectValueFindOptions(dom, value, isMap) {
var child = dom.firstChild;
while (child) {
var tagName = child.tagName;
if (tagName === 'OPTION') {
if ((!isMap && child.value === value) || (isMap && value.get(child.value))) {
child.selected = true;
} else {
child.selected = false;
}
} else if (tagName === 'OPTGROUP') {
formSelectValueFindOptions(child, value, isMap);
}
child = child.nextSibling;
}
}
function formSelectValue(dom, value) {
var isMap = false;
if (!isNullOrUndef(value)) {
if (isArray(value)) {
// Map vs Object v using reduce here for perf?
value = value.reduce(function (o, v) { return o.set(v, true); }, new Map());
isMap = true;
} else {
// convert to string
value = value + '';
}
formSelectValueFindOptions(dom, value, isMap);
}
}
function resetFormInputProperties(dom) {
if (dom.checked) {
dom.checked = false;
}
if (dom.disabled) {
dom.disabled = false;
}
}
function mount(input, parentDom, lifecycle, context, isSVG, shallowUnmount) {
if (isOptVElement(input)) {
return mountOptVElement(input, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVComponent(input)) {
return mountVComponent(input, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVElement(input)) {
return mountVElement(input, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVText(input)) {
return mountVText(input, parentDom);
} else if (isVFragment(input)) {
return mountVFragment(input, parentDom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVPlaceholder(input)) {
return mountVPlaceholder(input, parentDom);
} else {
if ("development" !== 'production') {
throwError('bad input argument called on mount(). Input argument may need normalising.');
}
throwError();
}
}
function mountVPlaceholder(vPlaceholder, parentDom) {
var dom = document.createTextNode('');
vPlaceholder.dom = dom;
if (parentDom) {
appendChild(parentDom, dom);
}
return dom;
}
function mountVElement(vElement, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var tag = vElement.tag;
if (!isString(tag)) {
if ("development" !== 'production') {
throwError('expects VElement to have a string as the tag name');
}
throwError();
}
if (tag === 'svg') {
isSVG = true;
}
var dom = documentCreateElement(tag, isSVG);
var children = vElement.children;
var props = vElement.props;
var ref = vElement.ref;
var hasProps = !isNullOrUndef(props);
var formValue;
vElement.dom = dom;
if (!isNullOrUndef(ref)) {
mountRef(dom, ref, lifecycle);
}
if (hasProps) {
formValue = mountProps(vElement, props, dom, lifecycle, context, isSVG, false, shallowUnmount);
}
if (!isNullOrUndef(children)) {
mountChildren(vElement.childrenType, children, dom, lifecycle, context, isSVG, shallowUnmount);
}
if (tag === 'select' && formValue) {
formSelectValue(dom, formValue);
}
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
return dom;
}
function mountVFragment(vFragment, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var children = vFragment.children;
var pointer = document.createTextNode('');
var dom = document.createDocumentFragment();
var childrenType = vFragment.childrenType;
if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG, shallowUnmount);
} else if (isUnknownChildrenType(childrenType)) {
mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG, shallowUnmount);
}
vFragment.pointer = pointer;
vFragment.dom = dom;
appendChild(dom, pointer);
if (parentDom) {
appendChild(parentDom, dom);
}
return dom;
}
function createStaticVElementClone(bp, isSVG) {
var stat = bp.staticVElement;
var tag = stat.tag;
var dom = documentCreateElement(tag, isSVG);
var children = stat.children;
if (!isNull(children)) {
mountChildrenWithUnknownType(children, dom, null, null, isSVG, false);
}
var props = stat.props;
if (!isNull(props)) {
for (var prop in props) {
patchProp(prop, null, props[prop], dom);
}
}
bp.clone = dom;
return dom.cloneNode(true);
}
function mountVText(vText, parentDom) {
var dom = document.createTextNode(vText.text);
vText.dom = dom;
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
return dom;
}
function mountOptVElement(optVElement, parentDom, lifecycle, context, isSVG, shallowUnmount) {
var bp = optVElement.bp;
var dom = null;
if (recyclingEnabled) {
dom = recycleOptVElement(optVElement, lifecycle, context, isSVG, shallowUnmount);
}
var tag = bp.staticVElement.tag;
if (isNull(dom)) {
if (isSVG || tag === 'svg') {
isSVG = true;
}
dom = (bp.clone && bp.clone.cloneNode(true)) || createStaticVElementClone(bp, isSVG);
optVElement.dom = dom;
var bp0 = bp.v0;
if (!isNull(bp0)) {
mountOptVElementValue(optVElement, bp0, optVElement.v0, bp.d0, dom, lifecycle, context, isSVG, shallowUnmount);
var bp1 = bp.v1;
if (!isNull(bp1)) {
mountOptVElementValue(optVElement, bp1, optVElement.v1, bp.d1, dom, lifecycle, context, isSVG, shallowUnmount);
var bp2 = bp.v2;
if (!isNull(bp2)) {
mountOptVElementValue(optVElement, bp2, optVElement.v2, bp.d2, dom, lifecycle, context, isSVG, shallowUnmount);
var bp3 = bp.v3;
if (!isNull(bp3)) {
var v3 = optVElement.v3;
var d3 = bp.d3;
var bp3$1 = bp.v3;
for (var i = 0; i < bp3$1.length; i++) {
mountOptVElementValue(optVElement, bp3$1[i], v3[i], d3[i], dom, lifecycle, context, isSVG, shallowUnmount);
}
}
}
}
}
if (tag === 'select') {
formSelectValue(dom, getPropFromOptElement(optVElement, ValueTypes.PROP_VALUE));
}
}
if (!isNull(parentDom)) {
parentDom.appendChild(dom);
}
return dom;
}
function mountOptVElementValue(optVElement, valueType, value, descriptor, dom, lifecycle, context, isSVG, shallowUnmount) {
switch (valueType) {
case ValueTypes.CHILDREN:
mountChildren(descriptor, value, dom, lifecycle, context, isSVG, shallowUnmount);
break;
case ValueTypes.PROP_CLASS_NAME:
if (!isNullOrUndef(value)) {
if (isSVG) {
dom.setAttribute('class', value);
} else {
dom.className = value;
}
}
break;
case ValueTypes.PROP_DATA:
dom.dataset[descriptor] = value;
break;
case ValueTypes.PROP_STYLE:
patchStyle(null, value, dom);
break;
case ValueTypes.PROP_VALUE:
dom.value = isNullOrUndef(value) ? '' : value;
break;
case ValueTypes.PROP:
patchProp(descriptor, null, value, dom);
break;
case ValueTypes.PROP_REF:
mountRef(dom, value, lifecycle);
break;
case ValueTypes.PROP_SPREAD:
mountProps(optVElement, value, dom, lifecycle, context, isSVG, true, shallowUnmount);
break;
}
}
function mountChildren(childrenType, children, dom, lifecycle, context, isSVG, shallowUnmount) {
if (isTextChildrenType(childrenType)) {
setTextContent(dom, children);
} else if (isNodeChildrenType(childrenType)) {
mount(children, dom, lifecycle, context, isSVG, shallowUnmount);
} else if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG, shallowUnmount);
} else if (isUnknownChildrenType(childrenType)) {
mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG, shallowUnmount);
} else {
if ("development" !== 'production') {
throwError('bad childrenType value specified when attempting to mountChildren.');
}
throwError();
}
}
function mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG, shallowUnmount) {
for (var i = 0; i < children.length; i++) {
mount(children[i], dom, lifecycle, context, isSVG, shallowUnmount);
}
}
function mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG, shallowUnmount) {
if (isArray(children)) {
mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG, shallowUnmount);
} else if (isStringOrNumber(children)) {
setTextContent(dom, children);
} else if (!isInvalid(children)) {
mount(children, dom, lifecycle, context, isSVG, shallowUnmount);
}
}
function mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG, shallowUnmount) {
children.complex = false;
for (var i = 0; i < children.length; i++) {
var child = normaliseChild(children, i);
if (isVText(child)) {
mountVText(child, dom);
children.complex = true;
} else if (isVPlaceholder(child)) {
mountVPlaceholder(child, dom);
children.complex = true;
} else if (isVFragment(child)) {
mountVFragment(child, dom, lifecycle, context, isSVG, shallowUnmount);
children.complex = true;
} else {
mount(child, dom, lifecycle, context, isSVG, shallowUnmount);
}
}
}
function mountVComponent(vComponent, parentDom, lifecycle, context, isSVG, shallowUnmount) {
if (recyclingEnabled) {
var dom$1 = recycleVComponent(vComponent, lifecycle, context, isSVG, shallowUnmount);
if (!isNull(dom$1)) {
if (!isNull(parentDom)) {
appendChild(parentDom, dom$1);
}
return dom$1;
}
}
var component = vComponent.component;
var props = vComponent.props || EMPTY_OBJ;
var hooks = vComponent.hooks;
var ref = vComponent.ref;
var dom;
if (isStatefulComponent(vComponent)) {
if (hooks) {
if ("development" !== 'production') {
throwError('"hooks" are not supported on stateful components.');
}
throwError();
}
var instance = createStatefulComponentInstance(component, props, context, isSVG);
var input = instance._lastInput;
instance._vComponent = vComponent;
vComponent.dom = dom = mount(input, null, lifecycle, instance._childContext, false, shallowUnmount);
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
mountStatefulComponentCallbacks(ref, instance, lifecycle);
componentToDOMNodeMap.set(instance, dom);
vComponent.instance = instance;
} else {
if (ref) {
if ("development" !== 'production') {
throwError('"refs" are not supported on stateless components.');
}
throwError();
}
var input$1 = createStatelessComponentInput(component, props, context);
vComponent.dom = dom = mount(input$1, null, lifecycle, context, null, false, shallowUnmount);
vComponent.instance = input$1;
mountStatelessComponentCallbacks(hooks, dom, lifecycle);
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
}
return dom;
}
function mountStatefulComponentCallbacks(ref, instance, lifecycle) {
if (ref) {
if (isFunction(ref)) {
lifecycle.addListener(function () { return ref(instance); });
} else {
if ("development" !== 'production') {
throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
}
throwError();
}
}
if (!isNull(instance.componentDidMount)) {
lifecycle.addListener(function () {
instance.componentDidMount();
});
}
}
function mountStatelessComponentCallbacks(hooks, dom, lifecycle) {
if (!isNullOrUndef(hooks)) {
if (!isNullOrUndef(hooks.onComponentWillMount)) {
hooks.onComponentWillMount(props);
}
if (!isNullOrUndef(hooks.onComponentDidMount)) {
lifecycle.addListener(function () { return hooks.onComponentDidMount(dom, props); });
}
}
}
function mountProps(vNode, props, dom, lifecycle, context, isSVG, isSpread, shallowUnmount) {
var formValue;
for (var prop in props) {
var value = props[prop];
if (prop === 'value') {
formValue = value;
}
if (prop === 'key') {
vNode.key = value;
} else if (prop === 'ref') {
mountRef(dom, value, lifecycle);
} else if (prop === 'children') {
if (isSpread) {
mountChildrenWithUnknownType(value, dom, lifecycle, context, isSVG, shallowUnmount);
} else if (isVElement(vNode)) {
vNode.children = value;
}
} else {
patchProp(prop, null, value, dom);
}
}
return formValue;
}
function mountRef(dom, value, lifecycle) {
if (isFunction(value)) {
lifecycle.addListener(function () { return value(dom); });
} else {
if ("development" !== 'production') {
throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
}
throwError();
}
}
function normaliseChildNodes(dom) {
var rawChildNodes = dom.childNodes;
var length = rawChildNodes.length;
var i = 0;
while (i < length) {
var rawChild = rawChildNodes[i];
if (rawChild.nodeType === 8) {
if (rawChild.data === '!') {
var placeholder = document.createTextNode('');
dom.replaceChild(placeholder, rawChild);
i++;
} else {
dom.removeChild(rawChild);
length--;
}
} else {
i++;
}
}
}
function hydrateVComponent(vComponent, dom, lifecycle, context) {
var component = vComponent.component;
var props = vComponent.props;
var hooks = vComponent.hooks;
var ref = vComponent.ref;
vComponent.dom = dom;
if (isStatefulComponent(vComponent)) {
var isSVG = dom.namespaceURI === svgNS;
var instance = createStatefulComponentInstance(component, props, context, isSVG);
var input = instance._lastInput;
instance._vComponent = vComponent;
hydrate(input, dom, lifecycle, context);
mountStatefulComponentCallbacks(ref, instance, lifecycle);
componentToDOMNodeMap.set(instance, dom);
vComponent.instance = instance;
} else {
var input$1 = createStatelessComponentInput(component, props, context);
hydrate(input$1, dom, lifecycle, context);
vComponent.instance = input$1;
vComponent.dom = input$1.dom;
mountStatelessComponentCallbacks(hooks, dom, lifecycle);
}
}
function hydrateVElement(vElement, dom, lifecycle, context) {
var tag = vElement.tag;
if (!isString(tag)) {
if ("development" !== 'production') {
throwError('expects VElement to have a string as the tag name');
}
throwError();
}
var children = vElement.children;
var props = vElement.props;
var ref = vElement.ref;
vElement.dom = dom;
if (children) {
hydrateChildren(vElement.childrenType, children, dom, lifecycle, context);
}
}
function hydrateArrayChildrenWithType(children, dom, lifecycle, context, isSVG) {
for (var i = 0; i < children.length; i++) {
debugger;
}
}
function hydrateChildrenWithUnknownType(children, dom, lifecycle, context) {
var domNodes = Array.prototype.slice.call(dom.childNodes);
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = normaliseChild(children, i);
if (isObject(child)) {
hydrate(child, domNodes[i], lifecycle, context);
}
}
} else if (isObject(children)) {
hydrate(children, dom.firstChild, lifecycle, context);
}
}
function hydrateChildren(childrenType, children, dom, lifecycle, context) {
if (isNodeChildrenType(childrenType)) {
hydrate(children, dom, lifecycle, context);
} else if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
hydrateArrayChildrenWithType(childrem, dom, lifecycle, context);
} else if (isUnknownChildrenType(childrenType)) {
hydrateChildrenWithUnknownType(children, dom);
} else if (!isTextChildrenType(childrenType)) {
if ("development" !== 'production') {
throwError('Bad childrenType value specified when attempting to hydrateChildren.');
}
throwError();
}
}
function hydrateOptVElement(optVElement, dom, lifecycle, context) {
var bp = optVElement.bp;
var bp0 = bp.v0;
optVElement.dom = dom;
if (!isNull(bp0)) {
hydrateOptVElementValue(optVElement, bp0, optVElement.v0, bp.d0, dom, context);
var bp1 = bp.v1;
if (!isNull(bp1)) {
hydrateOptVElementValue(optVElement, bp1, optVElement.v1, bp.d1, dom, context);
var bp2 = bp.v2;
if (!isNull(bp2)) {
hydrateOptVElementValue(optVElement, bp2, optVElement.v2, bp.d2, dom, context);
var bp3 = bp.v3;
if (!isNull(bp3)) {
var v3 = optVElement.v3;
var d3 = bp.d3;
var bp3$1 = bp.v3;
for (var i = 0; i < bp3$1.length; i++) {
hydrateOptVElementValue(optVElement, bp3$1[i], v3[i], d3[i], dom, context);
}
}
}
}
}
}
function hydrateVText(vText, dom) {
vText.dom = dom;
}
function hydrateVFragment(vFragment, currentDom, lifecycle, context) {
var children = vFragment.children;
var parentDom = currentDom.parentNode;
var pointer = vFragment.pointer = document.createTextNode('');
for (var i = 0; i < children.length; i++) {
var child = normaliseChild(children, i);
var childDom = currentDom;
if (isObject(child)) {
hydrate(child, childDom, lifecycle, context);
}
currentDom = currentDom.nextSibling;
}
parentDom.insertBefore(pointer, currentDom);
}
function hydrateOptVElementValue(optVElement, valueType, value, descriptor, dom, lifecycle, context) {
switch (valueType) {
case ValueTypes.CHILDREN:
hydrateChildren(descriptor, value, dom, lifecycle, context);
break;
case ValueTypes.PROP_SPREAD:
debugger;
break;
}
}
function hydrate(input, dom, lifecycle, context) {
normaliseChildNodes(dom);
if (isOptVElement(input)) {
hydrateOptVElement(input, dom, lifecycle, context);
} else if (isVComponent(input)) {
hydrateVComponent(input, dom, lifecycle, context);
} else if (isVElement(input)) {
hydrateVElement(input, dom, lifecycle, context);
} else if (isVFragment(input)) {
hydrateVFragment(input, dom, lifecycle, context);
} else if (isVText(input)) {
hydrateVText(input, dom);
} else if (isVPlaceholder(input)) {
debugger;
} else {
if ("development" !== 'production') {
throwError('bad input argument called on hydrate(). Input argument may need normalising.');
}
throwError();
}
}
function hydrateRoot(input, parentDom, lifecycle) {
if (parentDom && parentDom.nodeType === 1) {
var rootNode = parentDom.querySelector('[data-infernoroot]');
if (rootNode && rootNode.parentNode === parentDom) {
rootNode.removeAttribute('data-infernoroot');
hydrate(input, rootNode, lifecycle, {});
return true;
}
}
return false;
}
var roots = new Map();
var componentToDOMNodeMap = new Map();
function findDOMNode(domNode) {
return componentToDOMNodeMap.get(domNode) || null;
}
var documetBody = isBrowser ? document.body : null;
function render(input, parentDom) {
var root = roots.get(parentDom);
var lifecycle = new Lifecycle();
if (documetBody === parentDom) {
if ("development" !== 'production') {
throwError('you cannot render() to the "document.body". Use an empty element as a container instead.');
}
throwError();
}
if (input === NO_OP) {
return;
}
if (isUndefined(root)) {
if (!isInvalid(input)) {
if (input.dom) {
input = cloneVNode(input);
}
if (!hydrateRoot(input, parentDom, lifecycle)) {
mountChildrenWithUnknownType(input, parentDom, lifecycle, {}, false, false);
}
lifecycle.trigger();
roots.set(parentDom, { input: input });
}
} else {
var activeNode = getActiveNode();
if (isNullOrUndef(input)) {
unmount(root.input, parentDom, lifecycle, true);
roots.delete(parentDom);
} else {
if (input.dom) {
input = cloneVNode(input);
}
patchChildrenWithUnknownType(root.input, input, parentDom, lifecycle, {}, false, false);
}
lifecycle.trigger();
root.input = input;
resetActiveNode(activeNode);
}
}
var elementHooks = {
onCreated: true,
onAttached: true,
onWillUpdate: true,
onDidUpdate: true,
onWillDetach: true
};
var componentHooks = {
onComponentWillMount: true,
onComponentDidMount: true,
onComponentWillUnmount: true,
onComponentShouldUpdate: true,
onComponentWillUpdate: true,
onComponentDidUpdate: true
};
function createElement(name, props) {
var _children = [], len = arguments.length - 2;
while ( len-- > 0 ) _children[ len ] = arguments[ len + 2 ];
if (isInvalid(name) || isObject(name)) {
throw new Error('Inferno Error: createElement() name paramater cannot be undefined, null, false or true, It must be a string, class or function.');
}
var children = _children;
var vNode;
if (_children) {
if (_children.length === 1) {
children = _children[0];
} else if (_children.length === 0) {
children = undefined;
}
}
if (isString(name)) {
var hooks;
vNode = createVElement(name);
for (var prop in props) {
if (prop === 'key') {
vNode.key = props.key;
delete props.key;
} else if (elementHooks[prop]) {
if (!hooks) {
hooks = {};
}
hooks[prop] = props[prop];
delete props[prop];
} else if (isAttrAnEvent(prop)) {
var lowerCase = prop.toLowerCase();
if (lowerCase !== prop) {
props[prop.toLowerCase()] = props[prop];
delete props[prop];
}
}
}
vNode.props = props;
if (!isUndefined(children)) {
vNode.children = children;
}
if (hooks) {
vNode.hooks = hooks;
}
} else {
var hooks$1;
vNode = createVComponent(name);
if (!isUndefined(children)) {
if (!props) {
props = {};
}
props.children = children;
}
for (var prop$1 in props) {
if (componentHooks[prop$1]) {
if (!hooks$1) {
hooks$1 = {};
}
hooks$1[prop$1] = props[prop$1];
} else if (prop$1 === 'key') {
vNode.key = props.key;
delete props.key;
}
}
vNode.props = props;
if (hooks$1) {
vNode.hooks = hooks$1;
}
}
return vNode;
}
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode$1() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode$1(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
component.state = Object.assign({}, component.state, component._pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if ((!component._deferSetState || force) && !component._blockRender) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var prevState = component.state;
var nextState = Object.assign({}, prevState, pendingState);
var props = component.props;
component._pendingState = {};
var nextInput = component._updateComponent(prevState, nextState, props, props, force);
if (nextInput === NO_OP) {
nextInput = component._lastInput;
} else if (isNullOrUndef(nextInput)) {
nextInput = createVPlaceholder();
}
var lastInput = component._lastInput;
var parentDom = lastInput.dom.parentNode;
var activeNode = getActiveNode$1();
var subLifecycle = new Lifecycle();
component._patch(lastInput, nextInput, parentDom, subLifecycle, component.context, component._isSVG, false);
component._lastInput = nextInput;
component._vComponent.dom = nextInput.dom;
component._componentToDOMNodeMap.set(component, nextInput.dom);
component.componentDidUpdate(props, prevState);
subLifecycle.trigger();
if (!isNullOrUndef(callback)) {
callback();
}
resetActiveNode$1(activeNode);
}
}
var Component = function Component(props, context) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockRender = false;
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._lastInput = null;
this._vComponent = null;
this._unmounted = true;
this.context = context || {};
this._childContext = null;
this._patch = null;
this._isSVG = false;
this._componentToDOMNodeMap = null;
if (!this.componentDidMount) {
this.componentDidMount = null;
}
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
} else {
if ("development" !== 'production') {
throwError('cannot update state via setState() in componentWillUpdate().');
}
throwError();
}
};
Component.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
throw new Error('You can\'t update an unmounted component!');
}
if (!isNullOrUndef(nextProps) && isNullOrUndef(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockRender = true;
this.componentWillReceiveProps(nextProps);
this._blockRender = false;
if (this._pendingSetState) {
nextState = Object.assign({}, nextState, this._pendingState);
this._pendingSetState = false;
this._pendingState = {};
}
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false || force) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
return this.render();
}
}
return NO_OP;
};
// don't autobind these methods since they already have guaranteed context.
var AUTOBIND_BLACKLIST = {
constructor: 1,
render: 1,
shouldComponentUpdate: 1,
componentWillRecieveProps: 1,
componentWillUpdate: 1,
componentDidUpdate: 1,
componentWillMount: 1,
componentDidMount: 1,
componentWillUnmount: 1,
componentDidUnmount: 1
};
function F() {
}
function extend(base, props, all) {
for (var key in props) {
if (all === true || !isNullOrUndef(props[key])) {
base[key] = props[key];
}
}
return base;
}
function bindAll(ctx) {
for (var i in ctx) {
var v = ctx[i];
if (typeof v === 'function' && !v.__bound && !AUTOBIND_BLACKLIST.hasOwnProperty(i)) {
(ctx[i] = v.bind(ctx)).__bound = true;
}
}
}
function createClass(obj) {
function Cl(props) {
extend(this, obj);
Component.call(this, props);
bindAll(this);
if (this.getInitialState) {
this.state = this.getInitialState();
}
}
F.prototype = Component.prototype;
Cl.prototype = new F();
Cl.prototype.constructor = Cl;
Cl.displayName = obj.displayName || 'Component';
return Cl;
}
function escapeText(str) {
return (str + '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/');
}
function escapeAttr(str) {
return (str + '')
.replace(/&/g, '&')
.replace(/"/g, '"');
}
function toHyphenCase(str) {
return str.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase();
}
var voidElements = {
area: true,
base: true,
br: true,
col: true,
command: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
};
function isVoidElement(str) {
return !!voidElements[str];
}
function renderComponentToString(vComponent, isRoot, context) {
var Component = vComponent.component;
var props = vComponent.props;
if (isStatefulComponent(vComponent)) {
var instance = new Component(props);
var childContext = instance.getChildContext();
if (!isNullOrUndef(childContext)) {
context = Object.assign({}, context, childContext);
}
instance.context = context;
// Block setting state - we should render only once, using latest state
instance._pendingSetState = true;
instance.componentWillMount();
var node = instance.render();
instance._pendingSetState = false;
return renderInputToString(node, context, isRoot);
} else {
return renderInputToString(Component(props), context, isRoot);
}
}
function renderChildren(children, context) {
if (children && isArray(children)) {
var childrenResult = [];
var insertComment = false;
for (var i = 0; i < children.length; i++) {
var child = children[i];
var isText = isStringOrNumber(child);
var invalid = isInvalid(child);
if (isText || invalid) {
if (insertComment === true) {
if (isInvalid(child)) {
childrenResult.push('<!--!-->');
} else {
childrenResult.push('<!---->');
}
}
if (isText) {
childrenResult.push(escapeText(child));
}
insertComment = true;
} else if (isArray(child)) {
childrenResult.push('<!---->');
childrenResult.push(renderChildren(child));
childrenResult.push('<!--!-->');
insertComment = true;
} else {
insertComment = false;
childrenResult.push(renderInputToString(child, context, false));
}
}
return childrenResult.join('');
} else if (!isInvalid(children)) {
if (isStringOrNumber(children)) {
return escapeText(children);
} else {
return renderInputToString(children, context, false) || '';
}
}
return '';
}
function renderStyleToString(style) {
if (isStringOrNumber(style)) {
return style;
} else {
var styles = [];
var keys = Object.keys(style);
for (var i = 0; i < keys.length; i++) {
var styleName = keys[i];
var value = style[styleName];
var px = isNumber(value) && !isUnitlessNumber[styleName] ? 'px' : '';
if (!isNullOrUndef(value)) {
styles.push(((toHyphenCase(styleName)) + ":" + (escapeAttr(value)) + px + ";"));
}
}
return styles.join();
}
}
function renderVElementToString(vElement, isRoot, context) {
var tag = vElement.tag;
var outputProps = [];
var props = vElement.props;
var propsKeys = (props && Object.keys(props)) || [];
var html = '';
for (var i = 0; i < propsKeys.length; i++) {
var prop = propsKeys[i];
var value = props[prop];
if (prop === 'dangerouslySetInnerHTML') {
html = value.__html;
} else if (prop === 'style') {
outputProps.push('style="' + renderStyleToString(props.style) + '"');
} else if (prop === 'className') {
outputProps.push('class="' + value + '"');
} else {
if (isStringOrNumber(value)) {
outputProps.push(escapeAttr(prop) + '="' + escapeAttr(value) + '"');
} else if (isTrue(value)) {
outputProps.push(escapeAttr(prop));
}
}
}
if (isRoot) {
outputProps.push('data-infernoroot');
}
if (isVoidElement(tag)) {
return ("<" + tag + (outputProps.length > 0 ? ' ' + outputProps.join(' ') : '') + ">");
} else {
return ("<" + tag + (outputProps.length > 0 ? ' ' + outputProps.join(' ') : '') + ">" + (html || renderChildren(vElement.children, context)) + "</" + tag + ">");
}
}
function renderOptVElementToString(optVElement, isRoot, context) {
return renderInputToString(convertVOptElementToVElement(optVElement), context, isRoot);
}
function renderInputToString(input, context, isRoot) {
if (!isInvalid(input)) {
if (isOptVElement(input)) {
return renderOptVElementToString(input, isRoot, context);
} else if (isVElement(input)) {
return renderVElementToString(input, isRoot, context);
} else if (isVComponent(input)) {
return renderComponentToString(input, isRoot, context);
}
}
throw Error('Inferno Error: Bad input argument called on renderInputToString(). Input argument may need normalising.');
}
function renderToString(input) {
return renderInputToString(input, null, false);
}
function renderToStaticMarkup(input) {
return renderInputToString(input, null, true);
}
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var index$1 = createCommonjsModule(function (module, exports) {
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define('PropTypes', ['exports', 'module'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.PropTypes = mod.exports;
}
})(commonjsGlobal, function (exports, module) {
'use strict';
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var ReactElement = {};
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
var ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
var emptyFunction = {
thatReturns: function thatReturns(what) {
return function () {
return what;
};
}
};
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
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) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
var preciseType = getPreciseType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + 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 + ']');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` 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 locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + 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);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
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) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + 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') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + 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);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.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 {
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 getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
return 'object';
}
return propType;
}
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;
}
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
});
});
function unmountComponentAtNode(container) {
render(null, container);
return true;
}
function cloneElement(element, props) {
var children = [], len = arguments.length - 2;
while ( len-- > 0 ) children[ len ] = arguments[ len + 2 ];
return createElement.apply(
void 0, [ element.tag,
Object.assign({},
element.attrs || {},
props || {},
element.className ? { className: element.className } : {},
element.style ? { style: element.style } : {},
element.key ? { key: element.key } : {},
element.hooks || {},
element.events || {}
) ].concat( children )
);
}
var ARR = [];
var Children = {
map: function map(children, fn, ctx) {
children = Children.toArray(children);
if (ctx && ctx!==children) fn = fn.bind(ctx);
return children.map(fn);
},
forEach: function forEach(children, fn, ctx) {
children = Children.toArray(children);
if (ctx && ctx!==children) fn = fn.bind(ctx);
children.forEach(fn);
},
count: function count(children) {
children = Children.toArray(children);
return children.length;
},
only: function only(children) {
children = Children.toArray(children);
if (children.length!==1) throw new Error('Children.only() expects only one child.');
return children[0];
},
toArray: function toArray(children) {
return Array.isArray && Array.isArray(children) ? children : ARR.concat(children);
}
};
Component.prototype.isReactComponent = {};
var index = {
render: render,
createElement: createElement,
Component: Component,
unmountComponentAtNode: unmountComponentAtNode,
cloneElement: cloneElement,
PropTypes: index$1,
createClass: createClass,
findDOMNode: findDOMNode,
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup,
createVElement: createVElement,
createStaticVElement: createStaticVElement,
createOptBlueprint: createOptBlueprint,
createVComponent: createVComponent,
ValueTypes: ValueTypes,
ChildrenTypes: ChildrenTypes,
NodeTypes: NodeTypes,
Children: Children
};
exports.render = render;
exports.createElement = createElement;
exports.Component = Component;
exports.unmountComponentAtNode = unmountComponentAtNode;
exports.cloneElement = cloneElement;
exports.PropTypes = index$1;
exports.createClass = createClass;
exports.findDOMNode = findDOMNode;
exports.renderToString = renderToString;
exports.renderToStaticMarkup = renderToStaticMarkup;
exports.createVElement = createVElement;
exports.createStaticVElement = createStaticVElement;
exports.createOptBlueprint = createOptBlueprint;
exports.createVComponent = createVComponent;
exports.ValueTypes = ValueTypes;
exports.ChildrenTypes = ChildrenTypes;
exports.NodeTypes = NodeTypes;
exports.Children = Children;
exports['default'] = index;
Object.defineProperty(exports, '__esModule', { value: true });
}))); |
src/components/listen/soundPlayerContainer.js | cannoneyed/tmm-glare | import React from 'react'
import { stopAllOther, addToPlayedStore } from './utils/audioStore.js'
import { connect } from 'react-redux'
import * as listenActions from 'src/core/listen'
import { getNextUnlockedTrack } from 'src/core/selectors/listen'
let { PropTypes, Component } = React
class SoundPlayerContainer extends Component {
constructor(props, context) {
super(props, context)
}
componentDidMount() {
const { soundCloudAudio } = this.props
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
soundCloudAudio.on('playing', this.onAudioStarted)
soundCloudAudio.on('timeupdate', this.setCurrentTime)
soundCloudAudio.on('loadedmetadata', this.setDuration)
soundCloudAudio.on('seeking', this.onSeekingTrack)
soundCloudAudio.on('seeked', this.onSeekedTrack)
soundCloudAudio.on('pause', this.onAudioPaused)
soundCloudAudio.on('ended', this.onAudioEnded)
}
componentWillReceiveProps(nextProps) {
const {
resolveUrl,
setPlaylist,
soundCloudAudio,
} = this.props
const playedBefore = this.props.playing
function restartIfPlayed() {
if (playedBefore) {
soundCloudAudio.play()
}
}
if (resolveUrl !== nextProps.resolveUrl) {
soundCloudAudio.stop()
soundCloudAudio.resolve(nextProps.resolveUrl, (data) => {
setPlaylist(data)
restartIfPlayed()
})
}
}
componentWillUnmount() {
this.props.soundCloudAudio.unbindAll()
}
onSeekingTrack = () => {
const { setSeeking } = this.props
setSeeking(true)
}
onSeekedTrack = () => {
const { setSeeking } = this.props
setSeeking(false)
}
onAudioStarted = () => {
const { soundCloudAudio, setPlaying } = this.props
setPlaying(true)
stopAllOther(soundCloudAudio.playing)
addToPlayedStore(soundCloudAudio)
}
onAudioPaused = () => {
const { setPlaying } = this.props
setPlaying(false)
}
onAudioEnded = () => {
let {
activeIndex,
getNextUnlockedTrack,
playTrackAtIndex,
setPlaying,
} = this.props
const nextUnlockedTrack = getNextUnlockedTrack(activeIndex)
if (nextUnlockedTrack === null) {
setPlaying(false)
} else {
playTrackAtIndex(nextUnlockedTrack)
}
}
setCurrentTime = () => {
const { soundCloudAudio, setTime } = this.props
setTime(soundCloudAudio.audio.currentTime)
}
setDuration = () => {
const { soundCloudAudio, setDuration } = this.props
setDuration(soundCloudAudio.audio.duration)
}
wrapChild = (child) => {
const { soundCloudAudio } = this.props
const newProps = Object.assign({}, {
soundCloudAudio,
}, this.props)
return React.cloneElement(child, newProps)
}
render() {
const { children } = this.props
if (!children) {
return null
}
if (!Array.isArray(children)) {
const child = children
return this.wrapChild(child)
} else {
return (
<span>
{React.Children.map(children, this.wrapChild)}
</span>
)
}
}
}
SoundPlayerContainer.propTypes = {
activeIndex: PropTypes.number.isRequired,
children: PropTypes.node,
clientId: PropTypes.string,
currentTime: PropTypes.number.isRequired,
duration: PropTypes.number.isRequired,
getNextUnlockedTrack: PropTypes.func.isRequired,
playTrackAtIndex: PropTypes.func.isRequired,
playing: PropTypes.bool.isRequired,
playlist: PropTypes.object,
resolveUrl: PropTypes.string,
seeking: PropTypes.bool.isRequired,
setDuration: PropTypes.func.isRequired,
setPlaying: PropTypes.func.isRequired,
setPlaylist: PropTypes.func.isRequired,
setSeeking: PropTypes.func.isRequired,
setTime: PropTypes.func.isRequired,
soundCloudAudio: PropTypes.object,
streamUrl: PropTypes.string,
}
export default connect(state => ({
...state.listen,
getNextUnlockedTrack: getNextUnlockedTrack(state),
}), listenActions)(SoundPlayerContainer)
|
src/views/Data/index.js | jtmckay/TQL | import React from 'react'
import * as styles from 'styles'
import DataGrid from 'components/DataGrid'
export default function DataView (props) {
return <DataGrid
body={[[1]]}
styles={{
body: {
edit: {
borderRadius: 2,
boxShadow: '0px 0px 3px 2px #CCC'
},
td: {
width: 200,
borderRadius: 2,
boxShadow: '0px 0px 3px 2px #CCC'
}
}
}}
highlightInitialColor={styles.lightGreen}
highlightColor={styles.extraLightGreen}
/>
}
|
blueocean-material-icons/src/js/components/svg-icons/av/mic-none.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvMicNone = (props) => (
<SvgIcon {...props}>
<path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1.2-9.1c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2l-.01 6.2c0 .66-.53 1.2-1.19 1.2-.66 0-1.2-.54-1.2-1.2V4.9zm6.5 6.1c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/>
</SvgIcon>
);
AvMicNone.displayName = 'AvMicNone';
AvMicNone.muiName = 'SvgIcon';
export default AvMicNone;
|
ajax/libs/yui/3.8.1/scrollview-base/scrollview-base-debug.js | MEXXIO/cdnjs | YUI.add('scrollview-base', function (Y, NAME) {
/**
* The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators
*
* @module scrollview
* @submodule scrollview-base
*/
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});
|
src/layouts/CoreLayout/CoreLayout.js | Lily418/Realtime-News-Client | import React from 'react'
import Header from '../../components/Header'
import './CoreLayout.scss'
import '../../styles/core.scss'
export const CoreLayout = ({ children }) => (
<div className='container text-center'>
<Header />
<div className='core-layout__viewport'>
{children}
</div>
</div>
)
CoreLayout.propTypes = {
children : React.PropTypes.element.isRequired
}
export default CoreLayout
|
jekyll-strapi-tutorial/api/plugins/content-type-builder/admin/src/components/InputCheckboxWithNestedInputs/index.js | strapi/strapi-examples | /**
*
* InputCheckboxWithNestedInputs
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { isEmpty, map, findIndex } from 'lodash';
import { FormattedMessage } from 'react-intl';
import Input from 'components/InputsIndex';
import styles from './styles.scss';
class InputCheckboxWithNestedInputs extends React.Component { // eslint-disable-line react/prefer-stateless-function
handleChange = () => {
const target = {
type: 'checkbox',
value: !this.props.value[this.props.data.name.split('.')[1]],
name: this.props.data.name,
};
this.props.onChange({ target });
if (!target.value) {
const valueToRemove = {
target: {
name: `${this.props.data.name}Value`,
type: 'number',
value: '',
},
};
this.props.onChange(valueToRemove);
}
}
renderNestedInput = () => {
if (this.props.value[this.props.data.name.split('.')[1]]) {
return (
<div className={styles.nestedInputContainer} style={{ marginBottom: '-19px' }}>
{map(this.props.data.items, (item, key) => {
const errorIndex = findIndex(this.props.errors, ['name', item.name]);
const errors = errorIndex !== -1 ? this.props.errors[errorIndex].errors : [];
return (
<Input
key={key}
type={item.type}
onChange={this.props.onChange}
name={item.name}
value={this.props.value[item.name.split('.')[1]]}
validations={item.validations}
label={item.label}
errors={errors}
didCheckErrors={this.props.didCheckErrors}
pluginId="content-type-builder"
/>
);
})}
</div>
);
}
return <div />;
}
render() {
const spacer = !this.props.data.inputDescription ? <div /> : <div style={{ marginBottom: '.5rem'}}></div>;
const title = !isEmpty(this.props.data.title) ? <div className={styles.inputTitle}><FormattedMessage id={this.props.data.title} /></div> : '';
return (
<div className={`${styles.inputCheckboxWithNestedInputs} col-md-12`}>
<div className="form-check" style={{ zIndex: '9999' }}>
{title}
<FormattedMessage id={this.props.data.label.id}>
{(message) => (
<label className={`${styles.checkboxLabel} form-check-label`} htmlFor={this.props.data.name} style={{ cursor: 'pointer' }}>
<input
className="form-check-input"
defaultChecked={this.props.value[this.props.data.name.split('.')[1]]}
id={this.props.data.name}
name={this.props.data.name}
onChange={this.handleChange}
type="checkbox"
/>
{message}
</label>
)}
</FormattedMessage>
<div className={styles.descriptionContainer}>
<small>{this.props.data.inputDescription}</small>
</div>
</div>
{spacer}
{this.renderNestedInput()}
</div>
);
}
}
InputCheckboxWithNestedInputs.propTypes = {
data: PropTypes.object.isRequired,
didCheckErrors: PropTypes.bool,
errors: PropTypes.array,
onChange: PropTypes.func.isRequired,
value: PropTypes.object,
};
InputCheckboxWithNestedInputs.defaultProps = {
didCheckErrors: false,
errors: [],
value: {},
};
export default InputCheckboxWithNestedInputs;
|
ajax/libs/algoliasearch/3.19.1/algoliasearch.jquery.js | dlueth/cdnjs | /*! algoliasearch 3.19.1 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.ALGOLIA_MIGRATION_LAYER=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = function load (src, opts, cb) {
var head = document.head || document.getElementsByTagName('head')[0]
var script = document.createElement('script')
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = opts || {}
cb = cb || function() {}
script.type = opts.type || 'text/javascript'
script.charset = opts.charset || 'utf8';
script.async = 'async' in opts ? !!opts.async : true
script.src = src
if (opts.attrs) {
setAttributes(script, opts.attrs)
}
if (opts.text) {
script.text = '' + opts.text
}
var onend = 'onload' in script ? stdOnEnd : ieOnEnd
onend(script, cb)
// some good legacy browsers (firefox) fail the 'in' detection above
// so as a fallback we always set onload
// old IE will ignore this and new IE will set onload
if (!script.onload) {
stdOnEnd(script, cb);
}
head.appendChild(script)
}
function setAttributes(script, attrs) {
for (var attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
}
function stdOnEnd (script, cb) {
script.onload = function () {
this.onerror = this.onload = null
cb(null, script)
}
script.onerror = function () {
// this.onload = null here is necessary
// because even IE9 works not like others
this.onerror = this.onload = null
cb(new Error('Failed to load ' + this.src), script)
}
}
function ieOnEnd (script, cb) {
script.onreadystatechange = function () {
if (this.readyState != 'complete' && this.readyState != 'loaded') return
this.onreadystatechange = null
cb(null, script) // there is no way to catch loading errors in IE8
}
}
},{}],2:[function(require,module,exports){
'use strict';
// this module helps finding if the current page is using
// the cdn.jsdelivr.net/algoliasearch/latest/$BUILDNAME.min.js version
module.exports = isUsingLatest;
function isUsingLatest(buildName) {
var toFind = new RegExp('cdn\\.jsdelivr\\.net/algoliasearch/latest/' +
buildName.replace('.', '\\.') + // algoliasearch, algoliasearch.angular
'(?:\\.min)?\\.js$'); // [.min].js
var scripts = document.getElementsByTagName('script');
var found = false;
for (var currentScript = 0, nbScripts = scripts.length; currentScript < nbScripts; currentScript++) {
if (scripts[currentScript].src && toFind.test(scripts[currentScript].src)) {
found = true;
break;
}
}
return found;
}
},{}],3:[function(require,module,exports){
'use strict';
module.exports = loadV2;
function loadV2(buildName) {
var loadScript = require(1);
var v2ScriptUrl = '//cdn.jsdelivr.net/algoliasearch/2/' + buildName + '.min.js';
var message = '-- AlgoliaSearch `latest` warning --\n' +
'Warning, you are using the `latest` version string from jsDelivr to load the AlgoliaSearch library.\n' +
'Using `latest` is no more recommended, you should load //cdn.jsdelivr.net/algoliasearch/2/algoliasearch.min.js\n\n' +
'Also, we updated the AlgoliaSearch JavaScript client to V3. If you want to upgrade,\n' +
'please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
'-- /AlgoliaSearch `latest` warning --';
if (window.console) {
if (window.console.warn) {
window.console.warn(message);
} else if (window.console.log) {
window.console.log(message);
}
}
// If current script loaded asynchronously,
// it will load the script with DOMElement
// otherwise, it will load the script with document.write
try {
// why \x3c? http://stackoverflow.com/a/236106/147079
document.write('\x3Cscript>window.ALGOLIA_SUPPORTS_DOCWRITE = true\x3C/script>');
if (window.ALGOLIA_SUPPORTS_DOCWRITE === true) {
document.write('\x3Cscript src="' + v2ScriptUrl + '">\x3C/script>');
scriptLoaded('document.write')();
} else {
loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
}
} catch (e) {
loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
}
}
function scriptLoaded(method) {
return function log() {
var message = 'AlgoliaSearch: loaded V2 script using ' + method;
if (window.console && window.console.log) {
window.console.log(message);
}
};
}
},{"1":1}],4:[function(require,module,exports){
'use strict';
/* eslint no-unused-vars: [2, {"vars": "local"}] */
module.exports = oldGlobals;
// put old window.AlgoliaSearch.. into window. again so that
// users upgrading to V3 without changing their code, will be warned
function oldGlobals() {
var message = '-- AlgoliaSearch V2 => V3 error --\n' +
'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\n' +
'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
'-- /AlgoliaSearch V2 => V3 error --';
window.AlgoliaSearch = function() {
throw new Error(message);
};
window.AlgoliaSearchHelper = function() {
throw new Error(message);
};
window.AlgoliaExplainResults = function() {
throw new Error(message);
};
}
},{}],5:[function(require,module,exports){
'use strict';
// This script will be browserified and prepended to the normal build
// directly in window, not wrapped in any module definition
// To avoid cases where we are loaded with /latest/ along with
migrationLayer("algoliasearch.jquery");
// Now onto the V2 related code:
// If the client is using /latest/$BUILDNAME.min.js, load V2 of the library
//
// Otherwise, setup a migration layer that will throw on old constructors like
// new AlgoliaSearch().
// So that users upgrading from v2 to v3 will have a clear information
// message on what to do if they did not read the migration guide
function migrationLayer(buildName) {
var isUsingLatest = require(2);
var loadV2 = require(3);
var oldGlobals = require(4);
if (isUsingLatest(buildName)) {
loadV2(buildName);
} else {
oldGlobals();
}
}
},{"2":2,"3":3,"4":4}]},{},[5])(5)
});(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.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; };
},{}],2:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require(3);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if ('env' in (typeof process === 'undefined' ? {} : process)) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require(1))
},{"1":1,"3":3}],3:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require(4);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"4":4}],4:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],5:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 3.2.1
*/
(function() {
"use strict";
function lib$es6$promise$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function lib$es6$promise$utils$$isFunction(x) {
return typeof x === 'function';
}
function lib$es6$promise$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var lib$es6$promise$utils$$_isArray;
if (!Array.isArray) {
lib$es6$promise$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
lib$es6$promise$utils$$_isArray = Array.isArray;
}
var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
var lib$es6$promise$asap$$len = 0;
var lib$es6$promise$asap$$vertxNext;
var lib$es6$promise$asap$$customSchedulerFn;
var lib$es6$promise$asap$$asap = function asap(callback, arg) {
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
lib$es6$promise$asap$$len += 2;
if (lib$es6$promise$asap$$len === 2) {
// If len is 2, 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.
if (lib$es6$promise$asap$$customSchedulerFn) {
lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
} else {
lib$es6$promise$asap$$scheduleFlush();
}
}
}
function lib$es6$promise$asap$$setScheduler(scheduleFn) {
lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
}
function lib$es6$promise$asap$$setAsap(asapFn) {
lib$es6$promise$asap$$asap = asapFn;
}
var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function lib$es6$promise$asap$$useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function() {
process.nextTick(lib$es6$promise$asap$$flush);
};
}
// vertx
function lib$es6$promise$asap$$useVertxTimer() {
return function() {
lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
};
}
function lib$es6$promise$asap$$useMutationObserver() {
var iterations = 0;
var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function lib$es6$promise$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = lib$es6$promise$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function lib$es6$promise$asap$$useSetTimeout() {
return function() {
setTimeout(lib$es6$promise$asap$$flush, 1);
};
}
var lib$es6$promise$asap$$queue = new Array(1000);
function lib$es6$promise$asap$$flush() {
for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
var callback = lib$es6$promise$asap$$queue[i];
var arg = lib$es6$promise$asap$$queue[i+1];
callback(arg);
lib$es6$promise$asap$$queue[i] = undefined;
lib$es6$promise$asap$$queue[i+1] = undefined;
}
lib$es6$promise$asap$$len = 0;
}
function lib$es6$promise$asap$$attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
return lib$es6$promise$asap$$useVertxTimer();
} catch(e) {
return lib$es6$promise$asap$$useSetTimeout();
}
}
var lib$es6$promise$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (lib$es6$promise$asap$$isNode) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
} else if (lib$es6$promise$asap$$BrowserMutationObserver) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
} else if (lib$es6$promise$asap$$isWorker) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
} else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
} else {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
}
function lib$es6$promise$then$$then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(lib$es6$promise$$internal$$noop);
if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) {
lib$es6$promise$$internal$$makePromise(child);
}
var state = parent._state;
if (state) {
var callback = arguments[state - 1];
lib$es6$promise$asap$$asap(function(){
lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result);
});
} else {
lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
var lib$es6$promise$then$$default = lib$es6$promise$then$$then;
function lib$es6$promise$promise$resolve$$resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$resolve(promise, object);
return promise;
}
var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16);
function lib$es6$promise$$internal$$noop() {}
var lib$es6$promise$$internal$$PENDING = void 0;
var lib$es6$promise$$internal$$FULFILLED = 1;
var lib$es6$promise$$internal$$REJECTED = 2;
var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function lib$es6$promise$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function lib$es6$promise$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
return lib$es6$promise$$internal$$GET_THEN_ERROR;
}
}
function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
lib$es6$promise$asap$$asap(function(promise) {
var sealed = false;
var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
lib$es6$promise$$internal$$resolve(promise, value);
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
lib$es6$promise$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
lib$es6$promise$$internal$$reject(promise, error);
}
}, promise);
}
function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, thenable._result);
} else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, thenable._result);
} else {
lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}, function(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
}
}
function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) {
if (maybeThenable.constructor === promise.constructor &&
then === lib$es6$promise$then$$default &&
constructor.resolve === lib$es6$promise$promise$resolve$$default) {
lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
} else if (lib$es6$promise$utils$$isFunction(then)) {
lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
}
}
}
function lib$es6$promise$$internal$$resolve(promise, value) {
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
} else if (lib$es6$promise$utils$$objectOrFunction(value)) {
lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value));
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}
function lib$es6$promise$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
lib$es6$promise$$internal$$publish(promise);
}
function lib$es6$promise$$internal$$fulfill(promise, value) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._result = value;
promise._state = lib$es6$promise$$internal$$FULFILLED;
if (promise._subscribers.length !== 0) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
}
}
function lib$es6$promise$$internal$$reject(promise, reason) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._state = lib$es6$promise$$internal$$REJECTED;
promise._result = reason;
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
}
function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
}
}
function lib$es6$promise$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function lib$es6$promise$$internal$$ErrorObject() {
this.error = null;
}
var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
}
}
function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = lib$es6$promise$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = lib$es6$promise$$internal$$tryCatch(callback, detail);
if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
lib$es6$promise$$internal$$resolve(promise, value);
} else if (failed) {
lib$es6$promise$$internal$$reject(promise, error);
} else if (settled === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, value);
} else if (settled === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
}
}
function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
lib$es6$promise$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
} catch(e) {
lib$es6$promise$$internal$$reject(promise, e);
}
}
var lib$es6$promise$$internal$$id = 0;
function lib$es6$promise$$internal$$nextId() {
return lib$es6$promise$$internal$$id++;
}
function lib$es6$promise$$internal$$makePromise(promise) {
promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function lib$es6$promise$promise$all$$all(entries) {
return new lib$es6$promise$enumerator$$default(this, entries).promise;
}
var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
function lib$es6$promise$promise$race$$race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!lib$es6$promise$utils$$isArray(entries)) {
return new Constructor(function(resolve, reject) {
reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function(resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
function lib$es6$promise$promise$reject$$reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$reject(promise, reason);
return promise;
}
var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
function lib$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function lib$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function lib$es6$promise$promise$$Promise(resolver) {
this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (lib$es6$promise$$internal$$noop !== resolver) {
typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver();
this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew();
}
}
lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
lib$es6$promise$promise$$Promise.prototype = {
constructor: lib$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: lib$es6$promise$then$$default,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(lib$es6$promise$$internal$$noop);
if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) {
lib$es6$promise$$internal$$makePromise(this.promise);
}
if (lib$es6$promise$utils$$isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
lib$es6$promise$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
lib$es6$promise$$internal$$fulfill(this.promise, this._result);
}
}
} else {
lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError());
}
}
function lib$es6$promise$enumerator$$validationError() {
return new Error('Array Methods must be provided an Array');
}
lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var input = this._input;
for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
var resolve = c.resolve;
if (resolve === lib$es6$promise$promise$resolve$$default) {
var then = lib$es6$promise$$internal$$getThen(entry);
if (then === lib$es6$promise$then$$default &&
entry._state !== lib$es6$promise$$internal$$PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === lib$es6$promise$promise$$default) {
var promise = new c(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function(resolve) { resolve(entry); }), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === lib$es6$promise$$internal$$PENDING) {
this._remaining--;
if (state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
lib$es6$promise$$internal$$fulfill(promise, this._result);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
});
};
function lib$es6$promise$polyfill$$polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
return;
}
local.Promise = lib$es6$promise$promise$$default;
}
var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
var lib$es6$promise$umd$$ES6Promise = {
'Promise': lib$es6$promise$promise$$default,
'polyfill': lib$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return lib$es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = lib$es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
}
lib$es6$promise$polyfill$$default();
}).call(this);
}).call(this,require(1),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],6:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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 EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// 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.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && 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);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],7:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],8:[function(require,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],9:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],10:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],11:[function(require,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = require(12);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"12":12}],12:[function(require,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],13:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],14:[function(require,module,exports){
module.exports = AlgoliaSearch;
var Index = require(16);
var deprecate = require(27);
var deprecatedMessage = require(28);
var AlgoliaSearchCore = require(15);
var inherits = require(9);
var errors = require(29);
function AlgoliaSearch() {
AlgoliaSearchCore.apply(this, arguments);
}
inherits(AlgoliaSearch, AlgoliaSearchCore);
/*
* Delete an index
*
* @param indexName the name of index to delete
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexName),
hostType: 'write',
callback: callback
});
};
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of
* srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) {
var postObj = {
operation: 'move', destination: dstIndexName
};
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy
* of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, callback) {
var postObj = {
operation: 'copy', destination: dstIndexName
};
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Return last log entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param type Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.getLogs = function(offset, length, callback) {
var clone = require(26);
var params = {};
if (typeof offset === 'object') {
// getLogs(params)
params = clone(offset);
callback = length;
} else if (arguments.length === 0 || typeof offset === 'function') {
// getLogs([cb])
callback = offset;
} else if (arguments.length === 1 || typeof length === 'function') {
// getLogs(1, [cb)]
callback = length;
params.offset = offset;
} else {
// getLogs(1, 2, [cb])
params.offset = offset;
params.length = length;
}
if (params.offset === undefined) params.offset = 0;
if (params.length === undefined) params.length = 10;
return this._jsonRequest({
method: 'GET',
url: '/1/logs?' + this._getSearchParams(params, ''),
hostType: 'read',
callback: callback
});
};
/*
* List all existing indexes (paginated)
*
* @param page The page to retrieve, starting at 0.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with index list
*/
AlgoliaSearch.prototype.listIndexes = function(page, callback) {
var params = '';
if (page === undefined || typeof page === 'function') {
callback = page;
} else {
params = '?page=' + page;
}
return this._jsonRequest({
method: 'GET',
url: '/1/indexes' + params,
hostType: 'read',
callback: callback
});
};
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearch.prototype.initIndex = function(indexName) {
return new Index(this, indexName);
};
/*
* List all existing user keys with their associated ACLs
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.listUserKeys = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys',
hostType: 'read',
callback: callback
});
};
/*
* Get ACL of a user key
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.getUserKeyACL = function(key, callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys/' + key,
hostType: 'read',
callback: callback
});
};
/*
* Delete an existing user key
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.deleteUserKey = function(key, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/keys/' + key,
hostType: 'write',
callback: callback
});
};
/*
* Add a new global API key
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.addUserKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.addUserKey = function(acls, params, callback) {
var isArray = require(10);
var usage = 'Usage: client.addUserKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.indexes = params.indexes;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this._jsonRequest({
method: 'POST',
url: '/1/keys',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Add a new global API key
* @deprecated Please use client.addUserKey()
*/
AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) {
return this.addUserKey(acls, params, callback);
}, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addUserKey()'));
/**
* Update an existing API key
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.updateUserKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.updateUserKey = function(key, acls, params, callback) {
var isArray = require(10);
var usage = 'Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.indexes = params.indexes;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this._jsonRequest({
method: 'PUT',
url: '/1/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
};
/**
* Initialize a new batch of search queries
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() {
this._batch = [];
}, deprecatedMessage('client.startQueriesBatch()', 'client.search()'));
/**
* Add a search query in the batch
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) {
this._batch.push({
indexName: indexName,
query: query,
params: args
});
}, deprecatedMessage('client.addQueryInBatch()', 'client.search()'));
/**
* Launch the batch of queries using XMLHttpRequest.
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) {
return this.search(this._batch, callback);
}, deprecatedMessage('client.sendQueriesBatch()', 'client.search()'));
/**
* Perform write operations accross multiple indexes.
*
* To reduce the amount of time spent on network round trips,
* you can create, update, or delete several objects in one call,
* using the batch endpoint (all operations are done in the given order).
*
* Available actions:
* - addObject
* - updateObject
* - partialUpdateObject
* - partialUpdateObjectNoCreate
* - deleteObject
*
* https://www.algolia.com/doc/rest_api#Indexes
* @param {Object[]} operations An array of operations to perform
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.batch([{
* action: 'addObject',
* indexName: 'clients',
* body: {
* name: 'Bill'
* }
* }, {
* action: 'udpateObject',
* indexName: 'fruits',
* body: {
* objectID: '29138',
* name: 'banana'
* }
* }], cb)
*/
AlgoliaSearch.prototype.batch = function(operations, callback) {
var isArray = require(10);
var usage = 'Usage: client.batch(operations[, callback])';
if (!isArray(operations)) {
throw new Error(usage);
}
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/*/batch',
body: {
requests: operations
},
hostType: 'write',
callback: callback
});
};
// environment specific methods
AlgoliaSearch.prototype.destroy = notImplemented;
AlgoliaSearch.prototype.enableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.disableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented;
function notImplemented() {
var message = 'Not implemented in this environment.\n' +
'If you feel this is a mistake, write to [email protected]';
throw new errors.AlgoliaSearchError(message);
}
},{"10":10,"15":15,"16":16,"26":26,"27":27,"28":28,"29":29,"9":9}],15:[function(require,module,exports){
module.exports = AlgoliaSearchCore;
var errors = require(29);
var exitPromise = require(30);
var IndexCore = require(18);
// We will always put the API KEY in the JSON body in case of too long API KEY
var MAX_API_KEY_LENGTH = 500;
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = require(2)('algoliasearch');
var clone = require(26);
var isArray = require(10);
var map = require(31);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
var defaultHosts = shuffle([
this.applicationID + '-1.algolianet.com',
this.applicationID + '-2.algolianet.com',
this.applicationID + '-3.algolianet.com'
]);
this.hosts = {
read: [],
write: []
};
this.hostIndex = {
read: 0,
write: 0
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
var timeout = opts.timeout === undefined ? 2000 : opts.timeout;
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
// no hosts given, add defaults
if (!opts.hosts) {
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.requestTimeout = timeout;
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
this._ua += ';' + algoliaAgent;
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
var requestDebug = require(2)('algoliasearch:' + initialOpts.url);
var body;
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(false);
} else {
headers = this._computeRequestHeaders();
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to [email protected] to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders();
reqOpts.timeout = client.requestTimeout * (tries + 1);
client.hostIndex[initialOpts.hostType] = 0;
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client.hosts[initialOpts.hostType][client.hostIndex[initialOpts.hostType]];
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeout: reqOpts.timeout,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeout: %d',
options.method, url, options.headers, options.timeout);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
reqOpts.timeout = client.requestTimeout * (tries + 1);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeout: client.requestTimeout * (tries + 1)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(withAPIKey) {
var forEach = require(7);
var requestHeaders = {
'x-algolia-agent': this._ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = require(10);
var map = require(31);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
*
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this.requestTimeout = parseInt(milliseconds, 10);
}
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
},{"10":10,"18":18,"2":2,"26":26,"29":29,"30":30,"31":31,"7":7}],16:[function(require,module,exports){
var inherits = require(9);
var IndexCore = require(18);
var deprecate = require(27);
var deprecatedMessage = require(28);
var exitPromise = require(30);
var errors = require(29);
module.exports = Index;
function Index() {
IndexCore.apply(this, arguments);
}
inherits(Index, IndexCore);
/*
* Add an object in this index
*
* @param content contains the javascript object to add inside the index
* @param objectID (optional) an objectID you want to attribute to this object
* (if the attribute already exist the old object will be overwrite)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.addObject = function(content, objectID, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof objectID === 'function') {
callback = objectID;
objectID = undefined;
}
return this.as._jsonRequest({
method: objectID !== undefined ?
'PUT' : // update or create
'POST', // create (API generates an objectID)
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create
(objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create
body: content,
hostType: 'write',
callback: callback
});
};
/*
* Add several objects
*
* @param objects contains an array of objects to add
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.addObjects = function(objects, callback) {
var isArray = require(10);
var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'addObject',
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Update partially an object (only update attributes passed in argument)
*
* @param partialObject contains the javascript attributes to override, the
* object must contains an objectID attribute
* @param createIfNotExists (optional) if false, avoid an automatic creation of the object
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) {
if (arguments.length === 1 || typeof createIfNotExists === 'function') {
callback = createIfNotExists;
createIfNotExists = undefined;
}
var indexObj = this;
var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial';
if (createIfNotExists === false) {
url += '?createIfNotExists=false';
}
return this.as._jsonRequest({
method: 'POST',
url: url,
body: partialObject,
hostType: 'write',
callback: callback
});
};
/*
* Partially Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.partialUpdateObjects = function(objects, callback) {
var isArray = require(10);
var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'partialUpdateObject',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of object
*
* @param object contains the javascript object to save, the object must contains an objectID attribute
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObject = function(object, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID),
body: object,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObjects = function(objects, callback) {
var isArray = require(10);
var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'updateObject',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete an object from the index
*
* @param objectID the unique identifier of object to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObject = function(objectID, callback) {
if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') {
var err = new errors.AlgoliaSearchError('Cannot delete an object without an objectID');
callback = objectID;
if (typeof callback === 'function') {
return callback(err);
}
return this.as._promise.reject(err);
}
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
hostType: 'write',
callback: callback
});
};
/*
* Delete several objects from an index
*
* @param objectIDs contains an array of objectID to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObjects = function(objectIDs, callback) {
var isArray = require(10);
var map = require(31);
var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: map(objectIDs, function prepareRequest(objectID) {
return {
action: 'deleteObject',
objectID: objectID,
body: {
objectID: objectID
}
};
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete all objects matching a query
*
* @param query the query string
* @param params the optional query parameters
* @param callback (optional) the result callback called with one argument
* error: null or Error('message')
*/
Index.prototype.deleteByQuery = function(query, params, callback) {
var clone = require(26);
var map = require(31);
var indexObj = this;
var client = indexObj.as;
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = {};
} else {
params = clone(params);
}
params.attributesToRetrieve = 'objectID';
params.hitsPerPage = 1000;
params.distinct = false;
// when deleting, we should never use cache to get the
// search results
this.clearCache();
// there's a problem in how we use the promise chain,
// see how waitTask is done
var promise = this
.search(query, params)
.then(stopOrDelete);
function stopOrDelete(searchContent) {
// stop here
if (searchContent.nbHits === 0) {
// return indexObj.as._request.resolve();
return searchContent;
}
// continue and do a recursive call
var objectIDs = map(searchContent.hits, function getObjectID(object) {
return object.objectID;
});
return indexObj
.deleteObjects(objectIDs)
.then(waitTask)
.then(doDeleteByQuery);
}
function waitTask(deleteObjectsContent) {
return indexObj.waitTask(deleteObjectsContent.taskID);
}
function doDeleteByQuery() {
return indexObj.deleteByQuery(query, params);
}
if (!callback) {
return promise;
}
promise.then(success, failure);
function success() {
exitPromise(function exit() {
callback(null);
}, client._setTimeout || setTimeout);
}
function failure(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
};
/*
* Browse all content from an index using events. Basically this will do
* .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @return {EventEmitter}
* @example
* var browser = index.browseAll('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* });
*
* browser.on('result', function resultCallback(content) {
* console.log(content.hits);
* });
*
* // if any error occurs, you get it
* browser.on('error', function(err) {
* throw err;
* });
*
* // when you have browsed the whole index, you get this event
* browser.on('end', function() {
* console.log('finished');
* });
*
* // at any point if you want to stop the browsing process, you can stop it manually
* // otherwise it will go on and on
* browser.stop();
*
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
Index.prototype.browseAll = function(query, queryParameters) {
if (typeof query === 'object') {
queryParameters = query;
query = undefined;
}
var merge = require(32);
var IndexBrowser = require(17);
var browser = new IndexBrowser();
var client = this.as;
var index = this;
var params = client._getSearchParams(
merge({}, queryParameters || {}, {
query: query
}), ''
);
// start browsing
browseLoop();
function browseLoop(cursor) {
if (browser._stopped) {
return;
}
var queryString;
if (cursor !== undefined) {
queryString = 'cursor=' + encodeURIComponent(cursor);
} else {
queryString = params;
}
client._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse?' + queryString,
hostType: 'read',
callback: browseCallback
});
}
function browseCallback(err, content) {
if (browser._stopped) {
return;
}
if (err) {
browser._error(err);
return;
}
browser._result(content);
// no cursor means we are finished browsing
if (content.cursor === undefined) {
browser._end();
return;
}
browseLoop(content.cursor);
}
return browser;
};
/*
* Get a Typeahead.js adapter
* @param searchParams contains an object with query parameters (see search for details)
*/
Index.prototype.ttAdapter = function(params) {
var self = this;
return function ttAdapter(query, syncCb, asyncCb) {
var cb;
if (typeof asyncCb === 'function') {
// typeahead 0.11
cb = asyncCb;
} else {
// pre typeahead 0.11
cb = syncCb;
}
self.search(query, params, function searchDone(err, content) {
if (err) {
cb(err);
return;
}
cb(content.hits);
});
};
};
/*
* Wait the publication of a task on the server.
* All server task are asynchronous and you can check with this method that the task is published.
*
* @param taskID the id of the task returned by server
* @param callback the result callback with with two arguments:
* error: null or Error('message')
* content: the server answer that contains the list of results
*/
Index.prototype.waitTask = function(taskID, callback) {
// wait minimum 100ms before retrying
var baseDelay = 100;
// wait maximum 5s before retrying
var maxDelay = 5000;
var loop = 0;
// waitTask() must be handled differently from other methods,
// it's a recursive method using a timeout
var indexObj = this;
var client = indexObj.as;
var promise = retryLoop();
function retryLoop() {
return client._jsonRequest({
method: 'GET',
hostType: 'read',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID
}).then(function success(content) {
loop++;
var delay = baseDelay * loop * loop;
if (delay > maxDelay) {
delay = maxDelay;
}
if (content.status !== 'published') {
return client._promise.delay(delay).then(retryLoop);
}
return content;
});
}
if (!callback) {
return promise;
}
promise.then(successCb, failureCb);
function successCb(content) {
exitPromise(function exit() {
callback(null, content);
}, client._setTimeout || setTimeout);
}
function failureCb(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
};
/*
* This function deletes the index content. Settings and index specific API keys are kept untouched.
*
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occured
*/
Index.prototype.clearIndex = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear',
hostType: 'write',
callback: callback
});
};
/*
* Get settings of this index
*
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occured
*/
Index.prototype.getSettings = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?getVersion=2',
hostType: 'read',
callback: callback
});
};
Index.prototype.searchSynonyms = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
} else if (params === undefined) {
params = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search',
body: params,
hostType: 'read',
callback: callback
});
};
Index.prototype.saveSynonym = function(synonym, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) +
'?forwardToSlaves=' + (opts.forwardToSlaves ? 'true' : 'false'),
body: synonym,
hostType: 'write',
callback: callback
});
};
Index.prototype.getSynonym = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
Index.prototype.deleteSynonym = function(objectID, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) +
'?forwardToSlaves=' + (opts.forwardToSlaves ? 'true' : 'false'),
hostType: 'write',
callback: callback
});
};
Index.prototype.clearSynonyms = function(opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' +
'?forwardToSlaves=' + (opts.forwardToSlaves ? 'true' : 'false'),
hostType: 'write',
callback: callback
});
};
Index.prototype.batchSynonyms = function(synonyms, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' +
'?forwardToSlaves=' + (opts.forwardToSlaves ? 'true' : 'false') +
'&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'),
hostType: 'write',
body: synonyms,
callback: callback
});
};
/*
* Set settings for this index
*
* @param settigns the settings object that can contains :
* - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).
* - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).
* - hitsPerPage: (integer) the number of hits per page (default = 10).
* - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects.
* If set to null, all attributes are retrieved.
* - attributesToHighlight: (array of strings) default list of attributes to highlight.
* If set to null, all indexed attributes are highlighted.
* - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number
* of words to return (syntax is attributeName:nbWords).
* By default no snippet is computed. If set to null, no snippet is computed.
* - attributesToIndex: (array of strings) the list of fields you want to index.
* If set to null, all textual and numerical attributes of your objects are indexed,
* but you should update it to get optimal results.
* This parameter has two important uses:
* - Limit the attributes to index: For example if you store a binary image in base64,
* you want to store it and be able to
* retrieve it but you don't want to search in the base64 string.
* - Control part of the ranking*: (see the ranking parameter for full explanation)
* Matches in attributes at the beginning of
* the list will be considered more important than matches in attributes further down the list.
* In one attribute, matching text at the beginning of the attribute will be
* considered more important than text after, you can disable
* this behavior if you add your attribute inside `unordered(AttributeName)`,
* for example attributesToIndex: ["title", "unordered(text)"].
* - attributesForFaceting: (array of strings) The list of fields you want to use for faceting.
* All strings in the attribute selected for faceting are extracted and added as a facet.
* If set to null, no attribute is used for faceting.
* - attributeForDistinct: (string) The attribute name used for the Distinct feature.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in query with the distinct=1 parameter, all hits containing a duplicate
* value for this attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best one is kept and others are removed.
* - ranking: (array of strings) controls the way results are sorted.
* We have six available criteria:
* - typo: sort according to number of typos,
* - geo: sort according to decreassing distance when performing a geo-location based search,
* - proximity: sort according to the proximity of query words in hits,
* - attribute: sort according to the order of attributes defined by attributesToIndex,
* - exact:
* - if the user query contains one word: sort objects having an attribute
* that is exactly the query word before others.
* For example if you search for the "V" TV show, you want to find it
* with the "V" query and avoid to have all popular TV
* show starting by the v letter before it.
* - if the user query contains multiple words: sort according to the
* number of words that matched exactly (and not as a prefix).
* - custom: sort according to a user defined formula set in **customRanking** attribute.
* The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"]
* - customRanking: (array of strings) lets you specify part of the ranking.
* The syntax of this condition is an array of strings containing attributes
* prefixed by asc (ascending order) or desc (descending order) operator.
* For example `"customRanking" => ["desc(population)", "asc(name)"]`
* - queryType: Select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - highlightPreTag: (string) Specify the string that is inserted before
* the highlighted parts in the query result (default to "<em>").
* - highlightPostTag: (string) Specify the string that is inserted after
* the highlighted parts in the query result (default to "</em>").
* - optionalWords: (array of strings) Specify a list of words that should
* be considered as optional when found in the query.
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the server answer or the error message if a failure occured
*/
Index.prototype.setSettings = function(settings, opts, callback) {
if (arguments.length === 1 || typeof opts === 'function') {
callback = opts;
opts = {};
}
var forwardToSlaves = opts.forwardToSlaves || false;
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToSlaves='
+ (forwardToSlaves ? 'true' : 'false'),
hostType: 'write',
body: settings,
callback: callback
});
};
/*
* List all existing user keys associated to this index
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.listUserKeys = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
hostType: 'read',
callback: callback
});
};
/*
* Get ACL of a user key associated to this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.getUserKeyACL = function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'read',
callback: callback
});
};
/*
* Delete an existing user key associated to this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.deleteUserKey = function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'write',
callback: callback
});
};
/*
* Add a new API key to this index
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.addUserKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation}
*/
Index.prototype.addUserKey = function(acls, params, callback) {
var isArray = require(10);
var usage = 'Usage: index.addUserKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Add an existing user key associated to this index
* @deprecated use index.addUserKey()
*/
Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) {
return this.addUserKey(acls, params, callback);
}, deprecatedMessage('index.addUserKeyWithValidity()', 'index.addUserKey()'));
/**
* Update an existing API key of this index
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.updateUserKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*/
Index.prototype.updateUserKey = function(key, acls, params, callback) {
var isArray = require(10);
var usage = 'Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
};
},{"10":10,"17":17,"18":18,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"9":9}],17:[function(require,module,exports){
'use strict';
// This is the object returned by the `index.browseAll()` method
module.exports = IndexBrowser;
var inherits = require(9);
var EventEmitter = require(6).EventEmitter;
function IndexBrowser() {
}
inherits(IndexBrowser, EventEmitter);
IndexBrowser.prototype.stop = function() {
this._stopped = true;
this._clean();
};
IndexBrowser.prototype._end = function() {
this.emit('end');
this._clean();
};
IndexBrowser.prototype._error = function(err) {
this.emit('error', err);
this._clean();
};
IndexBrowser.prototype._result = function(content) {
this.emit('result', content);
};
IndexBrowser.prototype._clean = function() {
this.removeAllListeners('stop');
this.removeAllListeners('end');
this.removeAllListeners('error');
this.removeAllListeners('result');
};
},{"6":6,"9":9}],18:[function(require,module,exports){
var buildSearchMethod = require(25);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param callback the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the similar query
* @param args (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = require(32);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + params,
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(cursor),
hostType: 'read',
callback: callback
});
};
/*
* Search in facets
* https://www.algolia.com/doc/rest-api/search#search-in-a-facet
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchFacet = function(params, callback) {
var clone = require(26);
var omit = require(33);
var usage = 'Usage: index.searchFacet({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype._search = function(params, url, callback) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = require(10);
var map = require(31);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
},{"10":10,"25":25,"26":26,"31":31,"32":32,"33":33}],19:[function(require,module,exports){
(function (process){
'use strict';
// This is the jQuery Algolia Search module
// It's using $.ajax to do requests with a JSONP fallback
// jQuery promises are returned
var inherits = require(9);
var AlgoliaSearch = require(14);
var errors = require(29);
var inlineHeaders = require(23);
var jsonpRequest = require(24);
var places = require(34);
// expose original algoliasearch fn in window
window.algoliasearch = require(20);
if (process.env.NODE_ENV === 'debug') {
require(2).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(26);
var getDocumentProtocol = require(22);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchJQuery(applicationID, apiKey, opts);
}
algoliasearch.version = require(35);
algoliasearch.ua = 'Algolia for jQuery ' + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
window.__algolia = {
debug: require(2),
algoliasearch: algoliasearch
};
var $ = window.jQuery;
$.algolia = {
Client: algoliasearch,
ua: algoliasearch.ua,
version: algoliasearch.version
};
function AlgoliaSearchJQuery() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchJQuery, AlgoliaSearch);
AlgoliaSearchJQuery.prototype._request = function request(url, opts) {
return new $.Deferred(function(deferred) {
var body = opts.body;
url = inlineHeaders(url, opts.headers);
var requestHeaders = {
accept: 'application/json'
};
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
requestHeaders['content-type'] = 'application/x-www-form-urlencoded';
} else {
requestHeaders['content-type'] = 'application/json';
}
}
$.ajax(url, {
type: opts.method,
timeout: opts.timeout,
dataType: 'json',
data: body,
headers: requestHeaders,
complete: function onComplete(jqXHR, textStatus/* , error*/) {
if (textStatus === 'timeout') {
deferred.reject(new errors.RequestTimeout());
return;
}
if (jqXHR.status === 0) {
deferred.reject(
new errors.Network({
more: jqXHR
})
);
return;
}
deferred.resolve({
statusCode: jqXHR.status,
body: jqXHR.responseJSON,
responseText: jqXHR.responseText,
headers: jqXHR.getAllResponseHeaders()
});
}
});
}).promise();
};
// using IE8 or IE9 we will always end up here
// jQuery does not not fallback to XDomainRequest
AlgoliaSearchJQuery.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new $.Deferred(function wrapJsonpRequest(deferred) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
deferred.reject(err);
return;
}
deferred.resolve(content);
});
}).promise();
};
AlgoliaSearchJQuery.prototype._promise = {
reject: function reject(val) {
return new $.Deferred(function rejectDeferred(deferred) {
deferred.reject(val);
}).promise();
},
resolve: function resolve(val) {
return new $.Deferred(function resolveDeferred(deferred) {
deferred.resolve(val);
}).promise();
},
delay: function delay(ms) {
return new $.Deferred(function delayResolve(deferred) {
setTimeout(function resolveDeferred() {
deferred.resolve();
}, ms);
}).promise();
}
};
}).call(this,require(1))
},{"1":1,"14":14,"2":2,"20":20,"22":22,"23":23,"24":24,"26":26,"29":29,"34":34,"35":35,"9":9}],20:[function(require,module,exports){
'use strict';
var AlgoliaSearch = require(14);
var createAlgoliasearch = require(21);
module.exports = createAlgoliasearch(AlgoliaSearch);
},{"14":14,"21":21}],21:[function(require,module,exports){
(function (process){
'use strict';
var global = require(8);
var Promise = global.Promise || require(5).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = require(9);
var errors = require(29);
var inlineHeaders = require(23);
var jsonpRequest = require(24);
var places = require(34);
uaSuffix = uaSuffix || '';
if (process.env.NODE_ENV === 'debug') {
require(2).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(26);
var getDocumentProtocol = require(22);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = require(35);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: require(2),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
support.timeout = 'timeout' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var ontimeout;
var timedOut;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = function noop() {};
req.onload = load;
req.onerror = error;
if (support.timeout) {
// .timeout supported by both XHR and XDR,
// we do receive timeout event, tested
req.timeout = opts.timeout;
req.ontimeout = timeout;
} else {
ontimeout = setTimeout(timeout, opts.timeout);
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function load(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function error(event) {
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function timeout() {
if (!support.timeout) {
timedOut = true;
req.abort();
}
reject(new errors.RequestTimeout());
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
}).call(this,require(1))
},{"1":1,"2":2,"22":22,"23":23,"24":24,"26":26,"29":29,"34":34,"35":35,"5":5,"8":8,"9":9}],22:[function(require,module,exports){
'use strict';
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
},{}],23:[function(require,module,exports){
'use strict';
module.exports = inlineHeaders;
var encode = require(13);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
},{"13":13}],24:[function(require,module,exports){
'use strict';
module.exports = jsonpRequest;
var errors = require(29);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeout);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
},{"29":29}],25:[function(require,module,exports){
module.exports = buildSearchMethod;
var errors = require(29);
function buildSearchMethod(queryParam, url) {
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
if (arguments.length === 0 || typeof query === 'function') {
// .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// .search(args), careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
if (args !== undefined) {
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback);
};
}
},{"29":29}],26:[function(require,module,exports){
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
},{}],27:[function(require,module,exports){
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
},{}],28:[function(require,module,exports){
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
},{}],29:[function(require,module,exports){
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = require(9);
function AlgoliaSearchError(message, extraProperties) {
var forEach = require(7);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
},{"7":7,"9":9}],30:[function(require,module,exports){
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
},{}],31:[function(require,module,exports){
var foreach = require(7);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
},{"7":7}],32:[function(require,module,exports){
var foreach = require(7);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
},{"7":7}],33:[function(require,module,exports){
module.exports = function omit(obj, test) {
var keys = require(11);
var foreach = require(7);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
},{"11":11,"7":7}],34:[function(require,module,exports){
module.exports = createPlacesClient;
var buildSearchMethod = require(25);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = require(26);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
},{"25":25,"26":26}],35:[function(require,module,exports){
'use strict';
module.exports = '3.19.1';
},{}]},{},[19]);
|
support/maven-archetype/src/main/resources/archetype-resources/src/main/webapp/static/jquery/jquery-1.9.1.min.js | xiaoping2367/springside4 | /*! 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&>(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); |
docs/app/Examples/collections/Message/Variations/MessageExampleSuccess.js | shengnian/shengnian-ui-react | import React from 'react'
import { Message } from 'shengnian-ui-react'
const MessageExampleSuccess = () => (
<Message
success
header='Your user registration was successful'
content='You may now log-in with the username you have chosen'
/>
)
export default MessageExampleSuccess
|
packages/material-ui-icons/src/Pets.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="4.5" cy="9.5" r="2.5" /><circle cx="9" cy="5.5" r="2.5" /><circle cx="15" cy="5.5" r="2.5" /><circle cx="19.5" cy="9.5" r="2.5" /><path d="M17.34 14.86c-.87-1.02-1.6-1.89-2.48-2.91-.46-.54-1.05-1.08-1.75-1.32-.11-.04-.22-.07-.33-.09-.25-.04-.52-.04-.78-.04s-.53 0-.79.05c-.11.02-.22.05-.33.09-.7.24-1.28.78-1.75 1.32-.87 1.02-1.6 1.89-2.48 2.91-1.31 1.31-2.92 2.76-2.62 4.79.29 1.02 1.02 2.03 2.33 2.32.73.15 3.06-.44 5.54-.44h.18c2.48 0 4.81.58 5.54.44 1.31-.29 2.04-1.31 2.33-2.32.31-2.04-1.3-3.49-2.61-4.8z" /></React.Fragment>
, 'Pets');
|
ajax/libs/jquery.fancytree/2.5.1-0/jquery.fancytree.min.js | kentcdodds/cdnjs | /*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.5.0
* @date 2014-11-23T19:12
*/
!function(a,b,c,d){"use strict";function e(b,c){b||(c=c?": "+c:"",a.error("Fancytree assertion failed"+c))}function f(a,c){var d,e,f=b.console?b.console[a]:null;if(f)try{f.apply(b.console,c)}catch(g){for(e="",d=0;d<c.length;d++)e+=c[d];f(e)}}function g(a){return!(!a.tree||a.statusNodeType===d)}function h(b){var c,d,e,f=a.map(a.trim(b).split("."),function(a){return parseInt(a,10)}),g=a.map(Array.prototype.slice.call(arguments,1),function(a){return parseInt(a,10)});for(c=0;c<g.length;c++)if(d=f[c]||0,e=g[c]||0,d!==e)return d>e;return!0}function i(a,b,c,d,e){var f=function(){var c=b[a],f=d[a],g=b.ext[e],h=function(){return c.apply(b,arguments)};return function(){var a=b._local,c=b._super;try{return b._local=g,b._super=h,f.apply(b,arguments)}finally{b._local=a,b._super=c}}}();return f}function j(b,c,d,e){for(var f in d)"function"==typeof d[f]?"function"==typeof b[f]?b[f]=i(f,b,c,d,e):"_"===f.charAt(0)?b.ext[e][f]=i(f,b,c,d,e):a.error("Could not override tree."+f+". Use prefix '_' to create tree."+e+"._"+f):"options"!==f&&(b.ext[e][f]=d[f])}function k(b,c){return b===d?a.Deferred(function(){this.resolve()}).promise():a.Deferred(function(){this.resolveWith(b,c)}).promise()}function l(b,c){return b===d?a.Deferred(function(){this.reject()}).promise():a.Deferred(function(){this.rejectWith(b,c)}).promise()}function m(a,b){return function(){a.resolveWith(b)}}function n(b){var c=a.extend({},b.data()),d=c.json;return delete c.fancytree,d&&(delete c.json,c=a.extend(c,d)),c}function o(a){return a=a.toLowerCase(),function(b){return b.title.toLowerCase().indexOf(a)>=0}}function p(a){var b=new RegExp("^"+a,"i");return function(a){return b.test(a.title)}}function q(b,c){var d,f,g,h;for(this.parent=b,this.tree=b.tree,this.ul=null,this.li=null,this.statusNodeType=null,this._isLoading=!1,this._error=null,this.data={},d=0,f=x.length;f>d;d++)g=x[d],this[g]=c[g];c.data&&a.extend(this.data,c.data);for(g in c)y[g]||a.isFunction(c[g])||z[g]||(this.data[g]=c[g]);null==this.key?this.tree.options.defaultKey?(this.key=this.tree.options.defaultKey(this),e(this.key,"defaultKey() must return a unique key")):this.key="_"+t._nextNodeKey++:this.key=""+this.key,c.active&&(e(null===this.tree.activeNode,"only one active node allowed"),this.tree.activeNode=this),c.selected&&(this.tree.lastSelectedNode=this),this.children=null,h=c.children,h&&h.length&&this._setChildren(h),this.tree._callHook("treeRegisterNode",this.tree,!0,this)}function r(b){this.widget=b,this.$div=b.element,this.options=b.options,this.options&&a.isFunction(this.options.lazyload)&&(a.isFunction(this.options.lazyLoad)||(this.options.lazyLoad=function(){t.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."),b.options.lazyload.apply(this,arguments)})),this.options&&a.isFunction(this.options.loaderror)&&a.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."),this.ext={},this.data=n(this.$div),this._id=a.ui.fancytree._nextId++,this._ns=".fancytree-"+this._id,this.activeNode=null,this.focusNode=null,this._hasFocus=null,this.lastSelectedNode=null,this.systemFocusElement=null,this.lastQuicksearchTerm="",this.lastQuicksearchTime=0,this.statusClassPropName="span",this.ariaPropName="li",this.nodeContainerAttrName="li",this.$div.find(">ul.fancytree-container").remove();var c,d={tree:this};this.rootNode=new q(d,{title:"root",key:"root_"+this._id,children:null,expanded:!0}),this.rootNode.parent=null,c=a("<ul>",{"class":"ui-fancytree fancytree-container"}).appendTo(this.$div),this.$container=c,this.rootNode.ul=c[0],null==this.options.debugLevel&&(this.options.debugLevel=t.debugLevel),this.$container.attr("tabindex",this.options.tabbable?"0":"-1"),this.options.aria&&this.$container.attr("role","tree").attr("aria-multiselectable",!0)}if(a.ui&&a.ui.fancytree)return void a.ui.fancytree.warn("Fancytree: ignored duplicate include");e(a.ui,"Fancytree requires jQuery UI (http://jqueryui.com)");var s,t=null,u={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},v="active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),w={},x="expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),y={},z={active:!0,children:!0,data:!0,focus:!0};for(s=0;s<v.length;s++)w[v[s]]=!0;for(s=0;s<x.length;s++)y[x[s]]=!0;q.prototype={_findDirectChild:function(a){var b,c,d=this.children;if(d)if("string"==typeof a){for(b=0,c=d.length;c>b;b++)if(d[b].key===a)return d[b]}else{if("number"==typeof a)return this.children[a];if(a.parent===this)return a}return null},_setChildren:function(a){e(a&&(!this.children||0===this.children.length),"only init supported"),this.children=[];for(var b=0,c=a.length;c>b;b++)this.children.push(new q(this,a[b]))},addChildren:function(b,c){var d,f,g,h=null,i=[];for(a.isPlainObject(b)&&(b=[b]),this.children||(this.children=[]),d=0,f=b.length;f>d;d++)i.push(new q(this,b[d]));return h=i[0],null==c?this.children=this.children.concat(i):(c=this._findDirectChild(c),g=a.inArray(c,this.children),e(g>=0,"insertBefore must be an existing child"),this.children.splice.apply(this.children,[g,0].concat(i))),(!this.parent||this.parent.ul||this.tr)&&this.render(),3===this.tree.options.selectMode&&this.fixSelection3FromEndNodes(),h},addNode:function(a,b){switch((b===d||"over"===b)&&(b="child"),b){case"after":return this.getParent().addChildren(a,this.getNextSibling());case"before":return this.getParent().addChildren(a,this);case"firstChild":var c=this.children?this.children[0]:null;return this.addChildren(a,c);case"child":case"over":return this.addChildren(a)}e(!1,"Invalid mode: "+b)},appendSibling:function(a){return this.addNode(a,"after")},applyPatch:function(b){if(null===b)return this.remove(),k(this);var c,d,e,f={children:!0,expanded:!0,parent:!0};for(c in b)e=b[c],f[c]||a.isFunction(e)||(y[c]?this[c]=e:this.data[c]=e);return b.hasOwnProperty("children")&&(this.removeChildren(),b.children&&this._setChildren(b.children)),this.isVisible()&&(this.renderTitle(),this.renderStatus()),d=b.hasOwnProperty("expanded")?this.setExpanded(b.expanded):k(this)},collapseSiblings:function(){return this.tree._callHook("nodeCollapseSiblings",this)},copyTo:function(a,b,c){return a.addNode(this.toDict(!0,c),b)},countChildren:function(a){var b,c,d,e=this.children;if(!e)return 0;if(d=e.length,a!==!1)for(b=0,c=d;c>b;b++)d+=e[b].countChildren();return d},debug:function(){this.tree.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),f("log",arguments))},discard:function(){return this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."),this.resetLazy()},findAll:function(b){b=a.isFunction(b)?b:o(b);var c=[];return this.visit(function(a){b(a)&&c.push(a)}),c},findFirst:function(b){b=a.isFunction(b)?b:o(b);var c=null;return this.visit(function(a){return b(a)?(c=a,!1):void 0}),c},_changeSelectStatusAttrs:function(a){var b=!1;switch(a){case!1:b=this.selected||this.partsel,this.selected=!1,this.partsel=!1;break;case!0:b=!this.selected||!this.partsel,this.selected=!0,this.partsel=!0;break;case d:b=this.selected||!this.partsel,this.selected=!1,this.partsel=!0;break;default:e(!1,"invalid state: "+a)}return b&&this.renderStatus(),b},fixSelection3AfterClick:function(){var a=this.isSelected();this.visit(function(b){b._changeSelectStatusAttrs(a)}),this.fixSelection3FromEndNodes()},fixSelection3FromEndNodes:function(){function a(b){var c,e,f,g,h,i,j,k=b.children;if(k&&k.length){for(i=!0,j=!1,c=0,e=k.length;e>c;c++)f=k[c],g=a(f),g!==!1&&(j=!0),g!==!0&&(i=!1);h=i?!0:j?d:!1}else h=!!b.selected;return b._changeSelectStatusAttrs(h),h}e(3===this.tree.options.selectMode,"expected selectMode 3"),a(this),this.visitParents(function(a){var b,c,e,f,g=a.children,h=!0,i=!1;for(b=0,c=g.length;c>b;b++)e=g[b],(e.selected||e.partsel)&&(i=!0),e.unselectable||e.selected||(h=!1);f=h?!0:i?d:!1,a._changeSelectStatusAttrs(f)})},fromDict:function(b){for(var c in b)y[c]?this[c]=b[c]:"data"===c?a.extend(this.data,b.data):a.isFunction(b[c])||z[c]||(this.data[c]=b[c]);b.children&&(this.removeChildren(),this.addChildren(b.children)),this.renderTitle()},getChildren:function(){return this.hasChildren()===d?d:this.children},getFirstChild:function(){return this.children?this.children[0]:null},getIndex:function(){return a.inArray(this,this.parent.children)},getIndexHier:function(b){b=b||".";var c=[];return a.each(this.getParentList(!1,!0),function(a,b){c.push(b.getIndex()+1)}),c.join(b)},getKeyPath:function(a){var b=[],c=this.tree.options.keyPathSeparator;return this.visitParents(function(a){a.parent&&b.unshift(a.key)},!a),c+b.join(c)},getLastChild:function(){return this.children?this.children[this.children.length-1]:null},getLevel:function(){for(var a=0,b=this.parent;b;)a++,b=b.parent;return a},getNextSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=0,b=c.length-1;b>a;a++)if(c[a]===this)return c[a+1]}return null},getParent:function(){return this.parent},getParentList:function(a,b){for(var c=[],d=b?this:this.parent;d;)(a||d.parent)&&c.unshift(d),d=d.parent;return c},getPrevSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=1,b=c.length;b>a;a++)if(c[a]===this)return c[a-1]}return null},hasChildren:function(){return this.lazy?null==this.children?d:0===this.children.length?!1:1===this.children.length&&this.children[0].isStatusNode()?d:!0:!(!this.children||!this.children.length)},hasFocus:function(){return this.tree.hasFocus()&&this.tree.focusNode===this},info:function(){this.tree.options.debugLevel>=1&&(Array.prototype.unshift.call(arguments,this.toString()),f("info",arguments))},isActive:function(){return this.tree.activeNode===this},isChildOf:function(a){return this.parent&&this.parent===a},isDescendantOf:function(a){if(!a||a.tree!==this.tree)return!1;for(var b=this.parent;b;){if(b===a)return!0;b=b.parent}return!1},isExpanded:function(){return!!this.expanded},isFirstSibling:function(){var a=this.parent;return!a||a.children[0]===this},isFolder:function(){return!!this.folder},isLastSibling:function(){var a=this.parent;return!a||a.children[a.children.length-1]===this},isLazy:function(){return!!this.lazy},isLoaded:function(){return!this.lazy||this.hasChildren()!==d},isLoading:function(){return!!this._isLoading},isRoot:function(){return this.isRootNode()},isRootNode:function(){return this.tree.rootNode===this},isSelected:function(){return!!this.selected},isStatusNode:function(){return!!this.statusNodeType},isTopLevel:function(){return this.tree.rootNode===this.parent},isUndefined:function(){return this.hasChildren()===d},isVisible:function(){var a,b,c=this.getParentList(!1,!1);for(a=0,b=c.length;b>a;a++)if(!c[a].expanded)return!1;return!0},lazyLoad:function(a){return this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."),this.load(a)},load:function(a){var b,c,d=this;return e(this.isLazy(),"load() requires a lazy node"),a||this.isUndefined()?(this.isLoaded()&&this.resetLazy(),c=this.tree._triggerNodeEvent("lazyLoad",this),c===!1?k(this):(e("boolean"!=typeof c,"lazyLoad event must return source in data.result"),b=this.tree._callHook("nodeLoadChildren",this,c),this.expanded&&b.always(function(){d.render()}),b)):k(this)},makeVisible:function(b){var c,d=this,e=[],f=new a.Deferred,g=this.getParentList(!1,!1),h=g.length,i=!(b&&b.noAnimation===!0),j=!(b&&b.scrollIntoView===!1);for(c=h-1;c>=0;c--)e.push(g[c].setExpanded(!0,b));return a.when.apply(a,e).done(function(){j?d.scrollIntoView(i).done(function(){f.resolve()}):f.resolve()}),f.promise()},moveTo:function(b,c,f){(c===d||"over"===c)&&(c="child");var g,h=this.parent,i="child"===c?b:b.parent;if(this!==b){if(!this.parent)throw"Cannot move system root";if(i.isDescendantOf(this))throw"Cannot move a node to its own descendant";if(1===this.parent.children.length){if(this.parent===i)return;this.parent.children=this.parent.lazy?[]:null,this.parent.expanded=!1}else g=a.inArray(this,this.parent.children),e(g>=0),this.parent.children.splice(g,1);if(this.parent=i,i.hasChildren())switch(c){case"child":i.children.push(this);break;case"before":g=a.inArray(b,i.children),e(g>=0),i.children.splice(g,0,this);break;case"after":g=a.inArray(b,i.children),e(g>=0),i.children.splice(g+1,0,this);break;default:throw"Invalid mode "+c}else i.children=[this];f&&b.visit(f,!0),this.tree!==b.tree&&(this.warn("Cross-tree moveTo is experimantal!"),this.visit(function(a){a.tree=b.tree},!0)),h.isDescendantOf(i)||h.render(),i.isDescendantOf(h)||i===h||i.render()}},navigate:function(b,c){function d(d){if(d){try{d.makeVisible()}catch(e){}return a(d.span).is(":visible")?c===!1?d.setFocus():d.setActive():(d.debug("Navigate: skipping hidden node"),void d.navigate(b,c))}}var e,f,g=!0,h=a.ui.keyCode,i=null;switch(b){case h.BACKSPACE:this.parent&&this.parent.parent&&d(this.parent);break;case h.LEFT:this.expanded?(this.setExpanded(!1),d(this)):this.parent&&this.parent.parent&&d(this.parent);break;case h.RIGHT:this.expanded||!this.children&&!this.lazy?this.children&&this.children.length&&d(this.children[0]):(this.setExpanded(),d(this));break;case h.UP:for(i=this.getPrevSibling();i&&i.expanded&&i.children&&i.children.length;)i=i.children[i.children.length-1];!i&&this.parent&&this.parent.parent&&(i=this.parent),d(i);break;case h.DOWN:if(this.expanded&&this.children&&this.children.length)i=this.children[0];else for(f=this.getParentList(!1,!0),e=f.length-1;e>=0&&!(i=f[e].getNextSibling());e--);d(i);break;default:g=!1}},remove:function(){return this.parent.removeChild(this)},removeChild:function(a){return this.tree._callHook("nodeRemoveChild",this,a)},removeChildren:function(){return this.tree._callHook("nodeRemoveChildren",this)},render:function(a,b){return this.tree._callHook("nodeRender",this,a,b)},renderTitle:function(){return this.tree._callHook("nodeRenderTitle",this)},renderStatus:function(){return this.tree._callHook("nodeRenderStatus",this)},resetLazy:function(){this.removeChildren(),this.expanded=!1,this.lazy=!0,this.children=d,this.renderStatus()},scheduleAction:function(a,b){this.tree.timer&&clearTimeout(this.tree.timer),this.tree.timer=null;var c=this;switch(a){case"cancel":break;case"expand":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger expand"),c.setExpanded(!0)},b);break;case"activate":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger activate"),c.setActive(!0)},b);break;default:throw"Invalid mode "+a}},scrollIntoView:function(f,h){h!==d&&g(h)&&(this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."),h={topNode:h});var i,j,k,l,m=a.extend({effects:f===!0?{duration:200,queue:!1}:f,scrollOfs:this.tree.options.scrollOfs,scrollParent:this.tree.options.scrollParent||this.tree.$container,topNode:null},h),n=new a.Deferred,o=this,p=a(this.span).height(),q=a(m.scrollParent),r=m.scrollOfs.top||0,s=m.scrollOfs.bottom||0,t=q.height(),u=q.scrollTop(),v=q,w=q[0]===b,x=m.topNode||null,y=null;return e(a(this.span).is(":visible"),"scrollIntoView node is invisible"),w?(j=a(this.span).offset().top,i=x&&x.span?a(x.span).offset().top:0,v=a("html,body")):(e(q[0]!==c&&q[0]!==c.body,"scrollParent should be an simple element or `window`, not document or body."),l=q.offset().top,j=a(this.span).offset().top-l+u,i=x?a(x.span).offset().top-l+u:0,k=Math.max(0,q.innerHeight()-q[0].clientHeight),t-=k),u+r>j?y=j-r:j+p>u+t-s&&(y=j+p-t+s,x&&(e(x.isRoot()||a(x.span).is(":visible"),"topNode must be visible"),y>i&&(y=i-r))),null!==y?m.effects?(m.effects.complete=function(){n.resolveWith(o)},v.stop(!0).animate({scrollTop:y},m.effects)):(v[0].scrollTop=y,n.resolveWith(this)):n.resolveWith(this),n.promise()},setActive:function(a,b){return this.tree._callHook("nodeSetActive",this,a,b)},setExpanded:function(a,b){return this.tree._callHook("nodeSetExpanded",this,a,b)},setFocus:function(a){return this.tree._callHook("nodeSetFocus",this,a)},setSelected:function(a){return this.tree._callHook("nodeSetSelected",this,a)},setStatus:function(a,b,c){return this.tree._callHook("nodeSetStatus",this,a,b,c)},setTitle:function(a){this.title=a,this.renderTitle()},sortChildren:function(a,b){var c,d,e=this.children;if(e){if(a=a||function(a,b){var c=a.title.toLowerCase(),d=b.title.toLowerCase();return c===d?0:c>d?1:-1},e.sort(a),b)for(c=0,d=e.length;d>c;c++)e[c].children&&e[c].sortChildren(a,"$norender$");"$norender$"!==b&&this.render()}},toDict:function(b,c){var d,e,f,g={},h=this;if(a.each(x,function(a,b){(h[b]||h[b]===!1)&&(g[b]=h[b])}),a.isEmptyObject(this.data)||(g.data=a.extend({},this.data),a.isEmptyObject(g.data)&&delete g.data),c&&c(g),b&&this.hasChildren())for(g.children=[],d=0,e=this.children.length;e>d;d++)f=this.children[d],f.isStatusNode()||g.children.push(f.toDict(!0,c));return g},toggleExpanded:function(){return this.tree._callHook("nodeToggleExpanded",this)},toggleSelected:function(){return this.tree._callHook("nodeToggleSelected",this)},toString:function(){return"<FancytreeNode(#"+this.key+", '"+this.title+"')>"},visit:function(a,b){var c,d,e=!0,f=this.children;if(b===!0&&(e=a(this),e===!1||"skip"===e))return e;if(f)for(c=0,d=f.length;d>c&&(e=f[c].visit(a,!0),e!==!1);c++);return e},visitAndLoad:function(b,c,d){var e,f,g,h=this;return b&&c===!0&&(f=b(h),f===!1||"skip"===f)?d?f:k():h.children||h.lazy?(e=new a.Deferred,g=[],h.load().done(function(){for(var c=0,d=h.children.length;d>c;c++){if(f=h.children[c].visitAndLoad(b,!0,!0),f===!1){e.reject();break}"skip"!==f&&g.push(f)}a.when.apply(this,g).then(function(){e.resolve()})}),e.promise()):k()},visitParents:function(a,b){if(b&&a(this)===!1)return!1;for(var c=this.parent;c;){if(a(c)===!1)return!1;c=c.parent}return!0},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),f("warn",arguments)}},r.prototype={_makeHookContext:function(b,c,e){var f,g;return b.node!==d?(c&&b.originalEvent!==c&&a.error("invalid args"),f=b):b.tree?(g=b.tree,f={node:b,tree:g,widget:g.widget,options:g.widget.options,originalEvent:c}):b.widget?f={node:null,tree:b,widget:b.widget,options:b.widget.options,originalEvent:c}:a.error("invalid args"),e&&a.extend(f,e),f},_callHook:function(b,c){var d=this._makeHookContext(c),e=this[b],f=Array.prototype.slice.call(arguments,2);return a.isFunction(e)||a.error("_callHook('"+b+"') is not a function"),f.unshift(d),e.apply(this,f)},_requireExtension:function(b,c,d,f){d=!!d;var g=this._local.name,h=this.options.extensions,i=a.inArray(b,h)<a.inArray(g,h),j=c&&null==this.ext[b],k=!j&&null!=d&&d!==i;return e(g&&g!==b),j||k?(f||(j||c?(f="'"+g+"' extension requires '"+b+"'",k&&(f+=" to be registered "+(d?"before":"after")+" itself")):f="If used together, `"+b+"` must be registered "+(d?"before":"after")+" `"+g+"`"),a.error(f),!1):!0},activateKey:function(a){var b=this.getNodeByKey(a);return b?b.setActive():this.activeNode&&this.activeNode.setActive(!1),b},applyPatch:function(b){var c,d,f,g,h,i,j=b.length,k=[];for(d=0;j>d;d++)f=b[d],e(2===f.length,"patchList must be an array of length-2-arrays"),g=f[0],h=f[1],i=null===g?this.rootNode:this.getNodeByKey(g),i?(c=new a.Deferred,k.push(c),i.applyPatch(h).always(m(c,i))):this.warn("could not find node with key '"+g+"'");return a.when.apply(a,k).promise()},count:function(){return this.rootNode.countChildren()},debug:function(){this.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),f("log",arguments))},findNextNode:function(b,c){var d=null,e=c.parent.children,f=null,g=function(a,b,c){var d,e,f=a.children,h=f.length,i=f[b];if(i&&c(i)===!1)return!1;if(i&&i.children&&i.expanded&&g(i,0,c)===!1)return!1;for(d=b+1;h>d;d++)if(g(a,d,c)===!1)return!1;return e=a.parent,e?g(e,e.children.indexOf(a)+1,c):g(a,0,c)};return b="string"==typeof b?p(b):b,c=c||this.rootNode.getFirstChild(),g(c.parent,e.indexOf(c),function(e){return e===d?!1:(d=d||e,a(e.span).is(":visible")?b(e)&&(f=e,f!==c)?!1:void 0:void e.debug("quicksearch: skipping hidden node"))}),f},generateFormElements:function(b,c){var d,e=b!==!1?"ft_"+this._id+"[]":b,f=c!==!1?"ft_"+this._id+"_active":c,g="fancytree_result_"+this._id,h=a("#"+g);h.length?h.empty():h=a("<div>",{id:g}).hide().insertAfter(this.$container),e&&(d=this.getSelectedNodes(3===this.options.selectMode),a.each(d,function(b,c){h.append(a("<input>",{type:"checkbox",name:e,value:c.key,checked:!0}))})),f&&this.activeNode&&h.append(a("<input>",{type:"radio",name:f,value:this.activeNode.key,checked:!0}))},getActiveNode:function(){return this.activeNode},getFirstChild:function(){return this.rootNode.getFirstChild()},getFocusNode:function(){return this.focusNode},getNodeByKey:function(a,b){var d,e;return!b&&(d=c.getElementById(this.options.idPrefix+a))?d.ftnode?d.ftnode:null:(b=b||this.rootNode,e=null,b.visit(function(b){return b.key===a?(e=b,!1):void 0},!0),e)},getRootNode:function(){return this.rootNode},getSelectedNodes:function(a){var b=[];return this.rootNode.visit(function(c){return c.selected&&(b.push(c),a===!0)?"skip":void 0}),b},hasFocus:function(){return!!this._hasFocus},info:function(){this.options.debugLevel>=1&&(Array.prototype.unshift.call(arguments,this.toString()),f("info",arguments))},loadKeyPath:function(b,c,e){function f(a,b,d){c.call(r,b,"loading"),b.load().done(function(){r.loadKeyPath.call(r,l[a],c,b).always(m(d,r))}).fail(function(){r.warn("loadKeyPath: error loading: "+a+" (parent: "+o+")"),c.call(r,b,"error"),d.reject()})}var g,h,i,j,k,l,n,o,p,q=this.options.keyPathSeparator,r=this;for(a.isArray(b)||(b=[b]),l={},i=0;i<b.length;i++)for(o=e||this.rootNode,j=b[i],j.charAt(0)===q&&(j=j.substr(1)),p=j.split(q);p.length;){if(k=p.shift(),n=o._findDirectChild(k),!n){this.warn("loadKeyPath: key not found: "+k+" (parent: "+o+")"),c.call(this,k,"error");break}if(0===p.length){c.call(this,n,"ok");break}if(n.lazy&&n.hasChildren()===d){c.call(this,n,"loaded"),l[k]?l[k].push(p.join(q)):l[k]=[p.join(q)];break}c.call(this,n,"loaded"),o=n}g=[];for(k in l)n=o._findDirectChild(k),h=new a.Deferred,g.push(h),f(k,n,h);return a.when.apply(a,g).promise()},reactivate:function(a){var b=this.activeNode;b&&(this.activeNode=null,b.setActive(),a&&b.setFocus())},reload:function(a){return this._callHook("treeClear",this),this._callHook("treeLoad",this,a)},render:function(a,b){return this.rootNode.render(a,b)},setFocus:function(a){return this._callHook("treeSetFocus",this,a)},toDict:function(a,b){var c=this.rootNode.toDict(!0,b);return a?c:c.children},toString:function(){return"<Fancytree(#"+this._id+")>"},_triggerNodeEvent:function(a,b,c,e){var f=this._makeHookContext(b,c,e),g=this.widget._trigger(a,c,f);return g!==!1&&f.result!==d?f.result:g},_triggerTreeEvent:function(a,b){var c=this._makeHookContext(this,b),e=this.widget._trigger(a,b,c);return e!==!1&&c.result!==d?c.result:e},visit:function(a){return this.rootNode.visit(a,!1)},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),f("warn",arguments)}},a.extend(r.prototype,{nodeClick:function(a){var b,c,d=a.targetType,e=a.node;if("expander"===d)this._callHook("nodeToggleExpanded",a);else if("checkbox"===d)this._callHook("nodeToggleSelected",a),this._callHook("nodeSetFocus",a,!0);else{if(c=!1,b=!0,e.folder)switch(a.options.clickFolderMode){case 2:c=!0,b=!1;break;case 3:b=!0,c=!0}b&&(this.nodeSetFocus(a),this._callHook("nodeSetActive",a,!0)),c&&this._callHook("nodeToggleExpanded",a)}},nodeCollapseSiblings:function(a,b){var c,d,e,f=a.node;if(f.parent)for(c=f.parent.children,d=0,e=c.length;e>d;d++)c[d]!==f&&c[d].expanded&&this._callHook("nodeSetExpanded",c[d],!1,b)},nodeDblclick:function(a){"title"===a.targetType&&4===a.options.clickFolderMode&&this._callHook("nodeToggleExpanded",a),"title"===a.targetType&&a.originalEvent.preventDefault()},nodeKeydown:function(b){var c,d,e,f=b.originalEvent,g=b.node,h=b.tree,i=b.options,j=f.which,k=String.fromCharCode(j),l=!(f.altKey||f.ctrlKey||f.metaKey||f.shiftKey),m=a(f.target),n=!0,o=!(f.ctrlKey||!i.autoActivate),p=a.ui.keyCode;if(g||(this.rootNode.getFirstChild().setFocus(),g=b.node=this.focusNode,g.debug("Keydown force focus on first node")),i.quicksearch&&l&&/\w/.test(k)&&!m.is(":input:enabled"))return d=(new Date).getTime(),d-h.lastQuicksearchTime>500&&(h.lastQuicksearchTerm=""),h.lastQuicksearchTime=d,h.lastQuicksearchTerm+=k,c=h.findNextNode(h.lastQuicksearchTerm,h.getActiveNode()),c&&c.setActive(),void f.preventDefault();switch(j){case p.NUMPAD_ADD:case 187:h.nodeSetExpanded(b,!0);break;case p.NUMPAD_SUBTRACT:case 189:h.nodeSetExpanded(b,!1);break;case p.SPACE:i.checkbox?h.nodeToggleSelected(b):h.nodeSetActive(b,!0);break;case p.ENTER:h.nodeSetActive(b,!0);break;case p.BACKSPACE:case p.LEFT:case p.RIGHT:case p.UP:case p.DOWN:e=g.navigate(f.which,o);break;default:n=!1}n&&f.preventDefault()},nodeLoadChildren:function(b,c){var d,f,g,h=b.tree,i=b.node;return a.isFunction(c)&&(c=c()),c.url&&(d=a.extend({},b.options.ajax,c),d.debugDelay?(f=d.debugDelay,a.isArray(f)&&(f=f[0]+Math.random()*(f[1]-f[0])),i.debug("nodeLoadChildren waiting debug delay "+Math.round(f)+"ms"),d.debugDelay=!1,g=a.Deferred(function(b){setTimeout(function(){a.ajax(d).done(function(){b.resolveWith(this,arguments)}).fail(function(){b.rejectWith(this,arguments)})},f)})):g=a.ajax(d),c=new a.Deferred,g.done(function(d){var e,f;if("string"==typeof d&&a.error("Ajax request returned a string (did you get the JSON dataType wrong?)."),b.options.postProcess){if(f=h._triggerNodeEvent("postProcess",b,b.originalEvent,{response:d,error:null,dataType:this.dataType}),f.error)return e=a.isPlainObject(f.error)?f.error:{message:f.error},e=h._makeHookContext(i,null,e),void c.rejectWith(this,[e]);d=a.isArray(f)?f:d}else d&&d.hasOwnProperty("d")&&b.options.enableAspx&&(d="string"==typeof d.d?a.parseJSON(d.d):d.d);c.resolveWith(this,[d])}).fail(function(a,b,d){var e=h._makeHookContext(i,null,{error:a,args:Array.prototype.slice.call(arguments),message:d,details:a.status+": "+d});c.rejectWith(this,[e])})),a.isFunction(c.promise)&&(e(!i.isLoading()),h.nodeSetStatus(b,"loading"),c.done(function(){h.nodeSetStatus(b,"ok")}).fail(function(a){var c;c=a.node&&a.error&&a.message?a:h._makeHookContext(i,null,{error:a,args:Array.prototype.slice.call(arguments),message:a?a.message||a.toString():""}),h._triggerNodeEvent("loadError",c,null)!==!1&&h.nodeSetStatus(b,"error",c.message,c.details)})),a.when(c).done(function(b){var c;a.isPlainObject(b)&&(e(a.isArray(b.children),"source must contain (or be) an array of children"),e(i.isRoot(),"source may only be an object for root nodes"),c=b,b=b.children,delete c.children,a.extend(h.data,c)),e(a.isArray(b),"expected array of children"),i._setChildren(b),h._triggerNodeEvent("loadChildren",i)})},nodeLoadKeyPath:function(){},nodeRemoveChild:function(b,c){var d,f=b.node,g=b.options,h=a.extend({},b,{node:c}),i=f.children;return 1===i.length?(e(c===i[0]),this.nodeRemoveChildren(b)):(this.activeNode&&(c===this.activeNode||this.activeNode.isDescendantOf(c))&&this.activeNode.setActive(!1),this.focusNode&&(c===this.focusNode||this.focusNode.isDescendantOf(c))&&(this.focusNode=null),this.nodeRemoveMarkup(h),this.nodeRemoveChildren(h),d=a.inArray(c,i),e(d>=0),c.visit(function(a){a.parent=null},!0),this._callHook("treeRegisterNode",this,!1,c),g.removeNode&&g.removeNode.call(b.tree,{type:"removeNode"},h),void i.splice(d,1))},nodeRemoveChildMarkup:function(b){var c=b.node;c.ul&&(c.isRoot()?a(c.ul).empty():(a(c.ul).remove(),c.ul=null),c.visit(function(a){a.li=a.ul=null}))},nodeRemoveChildren:function(b){var c,d=b.tree,e=b.node,f=e.children,g=b.options;f&&(this.activeNode&&this.activeNode.isDescendantOf(e)&&this.activeNode.setActive(!1),this.focusNode&&this.focusNode.isDescendantOf(e)&&(this.focusNode=null),this.nodeRemoveChildMarkup(b),c=a.extend({},b),e.visit(function(a){a.parent=null,d._callHook("treeRegisterNode",d,!1,a),g.removeNode&&(c.node=a,g.removeNode.call(b.tree,{type:"removeNode"},c))}),e.children=e.lazy?[]:null,this.nodeRenderStatus(b))},nodeRemoveMarkup:function(b){var c=b.node;c.li&&(a(c.li).remove(),c.li=null),this.nodeRemoveChildMarkup(b)},nodeRender:function(b,d,f,g,h){var i,j,k,l,m,n,o,p=b.node,q=b.tree,r=b.options,s=r.aria,t=!1,u=p.parent,v=!u,w=p.children;if(v||u.ul){if(e(v||u.ul,"parent UL must exist"),v||(p.li&&(d||p.li.parentNode!==p.parent.ul)&&(p.li.parentNode!==p.parent.ul&&this.warn("unlink "+p+" (must be child of "+p.parent+")"),this.nodeRemoveMarkup(b)),p.li?this.nodeRenderStatus(b):(t=!0,p.li=c.createElement("li"),p.li.ftnode=p,p.key&&r.generateIds&&(p.li.id=r.idPrefix+p.key),p.span=c.createElement("span"),p.span.className="fancytree-node",s&&a(p.span).attr("aria-labelledby","ftal_"+p.key),p.li.appendChild(p.span),this.nodeRenderTitle(b),r.createNode&&r.createNode.call(q,{type:"createNode"},b)),r.renderNode&&r.renderNode.call(q,{type:"renderNode"},b)),w){if(v||p.expanded||f===!0){for(p.ul||(p.ul=c.createElement("ul"),(g===!0&&!h||!p.expanded)&&(p.ul.style.display="none"),s&&a(p.ul).attr("role","group"),p.li?p.li.appendChild(p.ul):p.tree.$div.append(p.ul)),l=0,m=w.length;m>l;l++)o=a.extend({},b,{node:w[l]}),this.nodeRender(o,d,f,!1,!0);for(i=p.ul.firstChild;i;)k=i.ftnode,k&&k.parent!==p?(p.debug("_fixParent: remove missing "+k,i),n=i.nextSibling,i.parentNode.removeChild(i),i=n):i=i.nextSibling;for(i=p.ul.firstChild,l=0,m=w.length-1;m>l;l++)j=w[l],k=i.ftnode,j!==k?p.ul.insertBefore(j.li,k.li):i=i.nextSibling}}else p.ul&&(this.warn("remove child markup for "+p),this.nodeRemoveChildMarkup(b));v||t&&u.ul.appendChild(p.li)}},nodeRenderTitle:function(a,b){var c,e,f,g,h,i,j=a.node,k=a.tree,l=a.options,m=l.aria,n=j.getLevel(),o=[],p=j.data.icon;b!==d&&(j.title=b),j.span&&(n<l.minExpandLevel?(j.lazy||(j.expanded=!0),n>1&&o.push(m?"<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>":"<span class='fancytree-expander fancytree-expander-fixed''></span>")):o.push(m?"<span role='button' class='fancytree-expander'></span>":"<span class='fancytree-expander'></span>"),l.checkbox&&j.hideCheckbox!==!0&&!j.isStatusNode()&&o.push(m?"<span role='checkbox' class='fancytree-checkbox'></span>":"<span class='fancytree-checkbox'></span>"),g=m?" role='img'":"",(p===!0||p!==!1&&l.icons!==!1)&&(p&&"string"==typeof p?(p="/"===p.charAt(0)?p:(l.imagePath||"")+p,o.push("<img src='"+p+"' class='fancytree-icon' alt='' />")):(e=l.iconClass&&l.iconClass.call(k,j,a)||j.data.iconclass||null,o.push(e?"<span "+g+" class='fancytree-custom-icon "+e+"'></span>":"<span "+g+" class='fancytree-icon'></span>"))),f="",l.renderTitle&&(f=l.renderTitle.call(k,{type:"renderTitle"},a)||""),f||(i=j.tooltip?" title='"+t.escapeHtml(j.tooltip)+"'":"",c=m?" id='ftal_"+j.key+"'":"",g=m?" role='treeitem'":"",h=l.titlesTabbable?" tabindex='0'":"",f="<span "+g+" class='fancytree-title'"+c+i+h+">"+j.title+"</span>"),o.push(f),j.span.innerHTML=o.join(""),this.nodeRenderStatus(a))},nodeRenderStatus:function(b){var c=b.node,d=b.tree,e=b.options,f=c.hasChildren(),g=c.isLastSibling(),h=e.aria,i=a(c.span).find(".fancytree-title"),j=e._classNames,k=[],l=c[d.statusClassPropName];l&&(k.push(j.node),d.activeNode===c&&k.push(j.active),d.focusNode===c?(k.push(j.focused),h&&i.attr("aria-activedescendant",!0)):h&&i.removeAttr("aria-activedescendant"),c.expanded?(k.push(j.expanded),h&&i.attr("aria-expanded",!0)):h&&i.removeAttr("aria-expanded"),c.folder&&k.push(j.folder),f!==!1&&k.push(j.hasChildren),g&&k.push(j.lastsib),c.lazy&&null==c.children&&k.push(j.lazy),c.partsel&&k.push(j.partsel),c.unselectable&&k.push(j.unselectable),c._isLoading&&k.push(j.loading),c._error&&k.push(j.error),c.selected?(k.push(j.selected),h&&i.attr("aria-selected",!0)):h&&i.attr("aria-selected",!1),c.extraClasses&&k.push(c.extraClasses),k.push(f===!1?j.combinedExpanderPrefix+"n"+(g?"l":""):j.combinedExpanderPrefix+(c.expanded?"e":"c")+(c.lazy&&null==c.children?"d":"")+(g?"l":"")),k.push(j.combinedIconPrefix+(c.expanded?"e":"c")+(c.folder?"f":"")),l.className=k.join(" "),c.li&&(c.li.className=g?j.lastsib:""))},nodeSetActive:function(b,c,d){d=d||{};var f,g=b.node,h=b.tree,i=b.options,j=d.noEvents===!0,m=g===h.activeNode;return c=c!==!1,m===c?k(g):c&&!j&&this._triggerNodeEvent("beforeActivate",g,b.originalEvent)===!1?l(g,["rejected"]):void(c?(h.activeNode&&(e(h.activeNode!==g,"node was active (inconsistency)"),f=a.extend({},b,{node:h.activeNode}),h.nodeSetActive(f,!1),e(null===h.activeNode,"deactivate was out of sync?")),i.activeVisible&&g.makeVisible({scrollIntoView:!1}),h.activeNode=g,h.nodeRenderStatus(b),h.nodeSetFocus(b),j||h._triggerNodeEvent("activate",g,b.originalEvent)):(e(h.activeNode===g,"node was not active (inconsistency)"),h.activeNode=null,this.nodeRenderStatus(b),j||b.tree._triggerNodeEvent("deactivate",g,b.originalEvent)))
},nodeSetExpanded:function(b,c,e){e=e||{};var f,g,h,i,j,m,n=b.node,o=b.tree,p=b.options,q=e.noAnimation===!0,r=e.noEvents===!0;if(c=c!==!1,n.expanded&&c||!n.expanded&&!c)return k(n);if(c&&!n.lazy&&!n.hasChildren())return k(n);if(!c&&n.getLevel()<p.minExpandLevel)return l(n,["locked"]);if(!r&&this._triggerNodeEvent("beforeExpand",n,b.originalEvent)===!1)return l(n,["rejected"]);if(q||n.isVisible()||(q=e.noAnimation=!0),g=new a.Deferred,c&&!n.expanded&&p.autoCollapse){j=n.getParentList(!1,!0),m=p.autoCollapse;try{for(p.autoCollapse=!1,h=0,i=j.length;i>h;h++)this._callHook("nodeCollapseSiblings",j[h],e)}finally{p.autoCollapse=m}}return g.done(function(){c&&p.autoScroll&&!q?n.getLastChild().scrollIntoView(!0,{topNode:n}).always(function(){r||b.tree._triggerNodeEvent(c?"expand":"collapse",b)}):r||b.tree._triggerNodeEvent(c?"expand":"collapse",b)}),f=function(d){var e,f,g,h;if(n.expanded=c,o._callHook("nodeRender",b,!1,!1,!0),n.ul)if(g="none"!==n.ul.style.display,h=!!n.expanded,g===h)n.warn("nodeSetExpanded: UL.style.display already set");else{if(p.fx&&!q)return e=p.fx.duration||200,f=p.fx.easing,void a(n.ul).animate(p.fx,e,f,function(){d()});n.ul.style.display=n.expanded||!parent?"":"none"}d()},c&&n.lazy&&n.hasChildren()===d?n.load().done(function(){g.notifyWith&&g.notifyWith(n,["loaded"]),f(function(){g.resolveWith(n)})}).fail(function(a){f(function(){g.rejectWith(n,["load failed ("+a+")"])})}):f(function(){g.resolveWith(n)}),g.promise()},nodeSetFocus:function(b,c){var d,e=b.tree,f=b.node;if(c=c!==!1,e.focusNode){if(e.focusNode===f&&c)return;d=a.extend({},b,{node:e.focusNode}),e.focusNode=null,this._triggerNodeEvent("blur",d),this._callHook("nodeRenderStatus",d)}c&&(this.hasFocus()||(f.debug("nodeSetFocus: forcing container focus"),this._callHook("treeSetFocus",b,!0,!0)),f.makeVisible({scrollIntoView:!1}),e.focusNode=f,this._triggerNodeEvent("focus",b),b.options.autoScroll&&f.scrollIntoView(),this._callHook("nodeRenderStatus",b))},nodeSetSelected:function(a,b){var c=a.node,d=a.tree,e=a.options;if(b=b!==!1,c.debug("nodeSetSelected("+b+")",a),!c.unselectable){if(c.selected&&b||!c.selected&&!b)return!!c.selected;if(this._triggerNodeEvent("beforeSelect",c,a.originalEvent)===!1)return!!c.selected;b&&1===e.selectMode?d.lastSelectedNode&&d.lastSelectedNode.setSelected(!1):3===e.selectMode&&(c.selected=b,c.fixSelection3AfterClick()),c.selected=b,this.nodeRenderStatus(a),d.lastSelectedNode=b?c:null,d._triggerNodeEvent("select",a)}},nodeSetStatus:function(b,c,d,e){function f(){var a=h.children?h.children[0]:null;if(a&&a.isStatusNode()){try{h.ul&&(h.ul.removeChild(a.li),a.li=null)}catch(b){}1===h.children.length?h.children=[]:h.children.shift()}}function g(b,c){var d=h.children?h.children[0]:null;return d&&d.isStatusNode()?(a.extend(d,b),i._callHook("nodeRenderTitle",d)):(b.key="_statusNode",h._setChildren([b]),h.children[0].statusNodeType=c,i.render()),h.children[0]}var h=b.node,i=b.tree;switch(c){case"ok":f(),h._isLoading=!1,h._error=null,h.renderStatus();break;case"loading":h.parent||g({title:i.options.strings.loading+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-wait"},c),h._isLoading=!0,h._error=null,h.renderStatus();break;case"error":g({title:i.options.strings.loadError+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-error"},c),h._isLoading=!1,h._error={message:d,details:e},h.renderStatus();break;default:a.error("invalid node status "+c)}},nodeToggleExpanded:function(a){return this.nodeSetExpanded(a,!a.node.expanded)},nodeToggleSelected:function(a){return this.nodeSetSelected(a,!a.node.selected)},treeClear:function(a){var b=a.tree;b.activeNode=null,b.focusNode=null,b.$div.find(">ul.fancytree-container").empty(),b.rootNode.children=null},treeCreate:function(){},treeDestroy:function(){},treeInit:function(a){this.treeLoad(a)},treeLoad:function(b,c){var d,e,f,g=b.tree,h=b.widget.element,i=a.extend({},b,{node:this.rootNode});if(g.rootNode.children&&this.treeClear(b),c=c||this.options.source)"string"==typeof c&&a.error("Not implemented");else switch(d=h.data("type")||"html"){case"html":e=h.find(">ul:first"),e.addClass("ui-fancytree-source ui-helper-hidden"),c=a.ui.fancytree.parseHtml(e),this.data=a.extend(this.data,n(e));break;case"json":c=a.parseJSON(h.text()),c.children&&(c.title&&(g.title=c.title),c=c.children);break;default:a.error("Invalid data-type: "+d)}return f=this.nodeLoadChildren(i,c).done(function(){g.render(),3===b.options.selectMode&&g.rootNode.fixSelection3FromEndNodes(),g._triggerTreeEvent("init",!0)}).fail(function(){g.render(),g._triggerTreeEvent("init",!1)})},treeRegisterNode:function(){},treeSetFocus:function(a,b){b=b!==!1,b!==this.hasFocus()&&(this._hasFocus=b,this.$container.toggleClass("fancytree-treefocus",b),this._triggerTreeEvent(b?"focusTree":"blurTree"))}}),a.widget("ui.fancytree",{options:{activeVisible:!0,ajax:{type:"GET",cache:!1,dataType:"json"},aria:!1,autoActivate:!0,autoCollapse:!1,autoScroll:!1,checkbox:!1,clickFolderMode:4,debugLevel:null,disabled:!1,enableAspx:!0,extensions:[],fx:{height:"toggle",duration:200},generateIds:!1,icons:!0,idPrefix:"ft_",keyboard:!0,keyPathSeparator:"/",minExpandLevel:1,quicksearch:!1,scrollOfs:{top:0,bottom:0},scrollParent:null,selectMode:2,strings:{loading:"Loading…",loadError:"Load error!"},tabbable:!0,titlesTabbable:!1,_classNames:{node:"fancytree-node",folder:"fancytree-folder",combinedExpanderPrefix:"fancytree-exp-",combinedIconPrefix:"fancytree-ico-",hasChildren:"fancytree-has-children",active:"fancytree-active",selected:"fancytree-selected",expanded:"fancytree-expanded",lazy:"fancytree-lazy",focused:"fancytree-focused",partsel:"fancytree-partsel",unselectable:"fancytree-unselectable",lastsib:"fancytree-lastsib",loading:"fancytree-loading",error:"fancytree-error"},lazyLoad:null,postProcess:null},_create:function(){this.tree=new r(this),this.$source=this.source||"json"===this.element.data("type")?this.element:this.element.find(">ul:first");var b,c,f,g=this.options.extensions,h=this.tree;for(f=0;f<g.length;f++)c=g[f],b=a.ui.fancytree._extensions[c],b||a.error("Could not apply extension '"+c+"' (it is not registered, did you forget to include it?)"),this.tree.options[c]=a.extend(!0,{},b.options,this.tree.options[c]),e(this.tree.ext[c]===d,"Extension name must not exist as Fancytree.ext attribute: '"+c+"'"),this.tree.ext[c]={},j(this.tree,h,b,c),h=b;this.tree._callHook("treeCreate",this.tree)},_init:function(){this.tree._callHook("treeInit",this.tree),this._bind()},_setOption:function(b,c){var d=!0,e=!1;switch(b){case"aria":case"checkbox":case"icons":case"minExpandLevel":case"tabbable":this.tree._callHook("treeCreate",this.tree),e=!0;break;case"source":d=!1,this.tree._callHook("treeLoad",this.tree,c)}this.tree.debug("set option "+b+"="+c+" <"+typeof c+">"),d&&a.Widget.prototype._setOption.apply(this,arguments),e&&this.tree.render(!0,!1)},destroy:function(){this._unbind(),this.tree._callHook("treeDestroy",this.tree),this.tree.$div.find(">ul.fancytree-container").remove(),this.$source&&this.$source.removeClass("ui-helper-hidden"),a.Widget.prototype.destroy.call(this)},_unbind:function(){var b=this.tree._ns;this.element.unbind(b),this.tree.$container.unbind(b),a(c).unbind(b)},_bind:function(){var a=this,b=this.options,c=this.tree,d=c._ns;this._unbind(),c.$container.on("focusin"+d+" focusout"+d,function(a){var b=t.getNode(a),d="focusin"===a.type;b?c._callHook("nodeSetFocus",b,d):c._callHook("treeSetFocus",c,d)}).on("selectstart"+d,"span.fancytree-title",function(a){a.preventDefault()}).on("keydown"+d,function(a){if(b.disabled||b.keyboard===!1)return!0;var d,e=c.focusNode,f=c._makeHookContext(e||c,a),g=c.phase;try{return c.phase="userEvent",d=e?c._triggerNodeEvent("keydown",e,a):c._triggerTreeEvent("keydown",a),"preventNav"===d?d=!0:d!==!1&&(d=c._callHook("nodeKeydown",f)),d}finally{c.phase=g}}).on("click"+d+" dblclick"+d,function(c){if(b.disabled)return!0;var d,e=t.getEventTarget(c),f=e.node,g=a.tree,h=g.phase;if(!f)return!0;d=g._makeHookContext(f,c);try{switch(g.phase="userEvent",c.type){case"click":return d.targetType=e.type,g._triggerNodeEvent("click",d,c)===!1?!1:g._callHook("nodeClick",d);case"dblclick":return d.targetType=e.type,g._triggerNodeEvent("dblclick",d,c)===!1?!1:g._callHook("nodeDblclick",d)}}finally{g.phase=h}})},getActiveNode:function(){return this.tree.activeNode},getNodeByKey:function(a){return this.tree.getNodeByKey(a)},getRootNode:function(){return this.tree.rootNode},getTree:function(){return this.tree}}),t=a.ui.fancytree,a.extend(a.ui.fancytree,{version:"2.5.0",buildType: "production",debugLevel: 1,_nextId:1,_nextNodeKey:1,_extensions:{},_FancytreeClass:r,_FancytreeNodeClass:q,jquerySupports:{positionMyOfs:h(a.ui.version,1,9)},assert:function(a,b){return e(a,b)},debounce:function(a,b,c,d){var e;return 3===arguments.length&&"boolean"!=typeof c&&(d=c,c=!1),function(){var f=arguments;d=d||this,c&&!e&&b.apply(d,f),clearTimeout(e),e=setTimeout(function(){c||b.apply(d,f),e=null},a)}},debug:function(){a.ui.fancytree.debugLevel>=2&&f("log",arguments)},error:function(){f("error",arguments)},escapeHtml:function(a){return(""+a).replace(/[&<>"'\/]/g,function(a){return u[a]})},unescapeHtml:function(a){var b=c.createElement("div");return b.innerHTML=a,0===b.childNodes.length?"":b.childNodes[0].nodeValue},getEventTargetType:function(a){return this.getEventTarget(a).type},getEventTarget:function(b){var c=b&&b.target?b.target.className:"",e={node:this.getNode(b.target),type:d};return/\bfancytree-title\b/.test(c)?e.type="title":/\bfancytree-expander\b/.test(c)?e.type=e.node.hasChildren()===!1?"prefix":"expander":/\bfancytree-checkbox\b/.test(c)||/\bfancytree-radio\b/.test(c)?e.type="checkbox":/\bfancytree-icon\b/.test(c)?e.type="icon":/\bfancytree-node\b/.test(c)?e.type="title":b&&b.target&&a(b.target).closest(".fancytree-title").length&&(e.type="title"),e},getNode:function(a){if(a instanceof q)return a;for(a.selector!==d?a=a[0]:a.originalEvent!==d&&(a=a.target);a;){if(a.ftnode)return a.ftnode;a=a.parentNode}return null},info:function(){a.ui.fancytree.debugLevel>=1&&f("info",arguments)},parseHtml:function(b){var c,e,f,g,h,i,j,k,l=b.find(">li"),m=[];return l.each(function(){var l,o=a(this),p=o.find(">span:first",this),q=p.length?null:o.find(">a:first"),r={tooltip:null,data:{}};for(p.length?r.title=p.html():q&&q.length?(r.title=q.html(),r.data.href=q.attr("href"),r.data.target=q.attr("target"),r.tooltip=q.attr("title")):(r.title=o.html(),g=r.title.search(/<ul/i),g>=0&&(r.title=r.title.substring(0,g))),r.title=a.trim(r.title),e=0,f=v.length;f>e;e++)r[v[e]]=d;for(j=this.className.split(" "),c=[],e=0,f=j.length;f>e;e++)k=j[e],w[k]?r[k]=!0:c.push(k);if(r.extraClasses=c.join(" "),h=o.attr("title"),h&&(r.tooltip=h),h=o.attr("id"),h&&(r.key=h),l=n(o),l&&!a.isEmptyObject(l)){for(e=0,f=x.length;f>e;e++)h=x[e],i=l[h],null!=i&&(delete l[h],r[h]=i);a.extend(r.data,l)}b=o.find(">ul:first"),r.children=b.length?a.ui.fancytree.parseHtml(b):r.lazy?d:null,m.push(r)}),m},registerExtension:function(b){e(null!=b.name,"extensions must have a `name` property."),e(null!=b.version,"extensions must have a `version` property."),a.ui.fancytree._extensions[b.name]=b},warn:function(){f("warn",arguments)}})}(jQuery,window,document); |
opentech/static_src/src/app/src/components/EmptyPanel/index.js | OpenTechFund/WebApp | import React from 'react'
import PropTypes from 'prop-types';
import NoteIcon from 'images/note.svg';
export default class EmptyPanel extends React.Component {
static propTypes = {
column: PropTypes.string,
}
render() {
const { column } = this.props;
return (
<div className={`listing listing__list--${column} is-blank`}>
{column === 'notes' &&
<>
<div className="listing__blank-icon">
<NoteIcon />
</div>
<p className="listing__help-text listing__help-text--standout">
There aren't any notes<br /> for this appication yet…
</p>
</>
}
{column === 'applications' &&
<p>No results found.</p>
}
</div>
)
}
}
|
src/svg-icons/navigation/arrow-upward.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationArrowUpward = (props) => (
<SvgIcon {...props}>
<path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/>
</SvgIcon>
);
NavigationArrowUpward = pure(NavigationArrowUpward);
NavigationArrowUpward.displayName = 'NavigationArrowUpward';
NavigationArrowUpward.muiName = 'SvgIcon';
export default NavigationArrowUpward;
|
ajax/libs/react-native-web/0.0.0-4fd133e73/exports/PanResponder/index.min.js | cdnjs/cdnjs | import PanResponder from"../../vendor/react-native/PanResponder";export default PanResponder; |
files/jquery/1.7.2/jquery.js | vousk/jsdelivr | /*!
* 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/compoments/PurpleSearchInput.js | purple-net/react-native-purple | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Alert,
ListView,
ScrollView,
PixelRatio,
Dimensions,
TextInput,
TouchableOpacity,
TouchableHighlight,
ActivityIndicator,
AsyncStorage,
Navigator,
} from 'react-native';
import ActionButton from 'react-native-action-button';
import Button from 'react-native-button';
import Icon from 'react-native-vector-icons/FontAwesome';
import Modal from 'react-native-modalbox';
import colors from '../config/colors';
import fonts from '../config/fonts';
import PurpleHeader from './PurpleHeader';
import PurpleItem from './PurpleItem';
export class PurpleSearchInput extends Component{
constructor(props){
super(props);
console.log(props);
this.state={
text:'',
historyItems:[],
dataSource: new ListView.DataSource({
rowHasChanged: function(row1, row2) {return row1 !== row2},
}),
loaded: false,
};
this.cacheKeyName='SearchHistory$'+props.name;
}
componentWillMount(){
console.log('componentWillMount');
AsyncStorage.getAllKeys().then((keys,err)=>{
if (err) {
console.log('读取缓存出错了'+err);
return;
}
let searchKeys=[];
Object.keys(keys).forEach((i,val)=>{
if (keys[i].indexOf(this.cacheKeyName)==0) {
searchKeys.push(keys[i]);
}
})
AsyncStorage.multiGet(searchKeys).then((result,err)=>{
if (err) {
return;
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(result),
loaded: true,
});
if (this.props.onHistoryEnd) {
this.setState({historyItems:result},()=>{
this.props.onHistoryEnd(result);
});
}else {
this.setState({historyItems:result});
}
});
});
}
onEndEditing(val){
if (val) {
this.props.onEndEditing(val);
}else {
Alert.alet('操作提示','请输入关键字');
}
}
onChangeText(val){
}
render(){
return(
<View style={[{flex:1}]}>
<TouchableOpacity style={[styles.searchInputStyle]} onPress={()=>{
this.props.root.push({
component:PurpleSearchView,
configureScene:()=>{
return Navigator.SceneConfigs.FadeAndroid;
},
params:{
root:this.props.root,
name:this.props.name,
onHistoryEnd:this.props.onHistoryEnd,
onEndEditing:this.onEndEditing.bind(this),
onChangeText:this.onChangeText.bind(this),
},
});
}}>
<View style={[styles.searchInput]}>
<Text style={[styles.searchInputText]}>{this.props.defaultValue}</Text>
</View>
<View style={[styles.searchInputBtn]}>
<Text style={[styles.searchInputBtnText]}>搜索</Text>
</View>
</TouchableOpacity>
<ScrollView style={[{flex:1}]}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<PurpleItem
rightIcon={{name:'search'}}
title={rowData[1]}
onPress={()=>{
this.setState({text:rowData[1]},()=>{
this.onEndEditing();
});
}} ></PurpleItem>}>
</ListView>
</ScrollView>
</View>
)
};
}
class PurpleSearchView extends Component{
constructor(props){
super(props);
this.state={
text:'',
dataSource: new ListView.DataSource({
rowHasChanged: function(row1, row2) {return row1 !== row2},
}),
loaded: false,
};
this.cacheKeyName='SearchHistory$'+props.name;
};
componentWillMount(){
AsyncStorage.getAllKeys().then((keys,err)=>{
if (err) {
console.log('读取缓存出错了'+err);
return;
}
let searchKeys=[];
console.log(this.cacheKeyName);
Object.keys(keys).forEach((i,val)=>{
if (keys[i].indexOf(this.cacheKeyName)==0) {
searchKeys.push(keys[i]);
}
})
AsyncStorage.multiGet(searchKeys).then((result,err)=>{
if (err) {
return;
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(result),
loaded: true,
});
if (this.onHistoryEnd) {
this.onHistoryEnd(items);
}
});
});
}
onChangeText(val){
this.setState({text:val});
}
onEndEditing(){
let val=this.state.text;
if (val=='') {
Alert.alert('操作提示','请输入关键字');
return ;
}
AsyncStorage.setItem(this.cacheKeyName+'$$'+val,val);
if (this.props.onEndEditing) {
this.refs.modalLoading.open();
this.props.onEndEditing(val,()=>{
this.refs.modalLoading.close();
},()=>{
this.refs.modalLoading.close();
});
}
}
render(){
return(
<View style={styles.container}>
<PurpleSearchHeader
root={this.props.root}
parent={this}
onChangeText={this.onChangeText.bind(this)}
onEndEditing={this.onEndEditing.bind(this)}>
</PurpleSearchHeader>
<ScrollView style={[{flex:1}]}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<PurpleItem
rightIcon={{name:'search'}}
title={rowData[1]}
onPress={()=>{
this.setState({text:rowData[1]},()=>{
this.onEndEditing();
});
}} ></PurpleItem>}>
</ListView>
</ScrollView>
<Modal style={[styles.modal, styles.modal2]}
position={"center"}
ref={"modalLoading"}
backdropPressToClose={false}
isDisabled={false}>
<ActivityIndicator
color="#ccc"
animating={true}
style={[styles.modalLoadingIcon, {transform: [{scale: 0.5}]}]}
size="large"
/>
<Text style={[styles.modalLoadingText]}>正在搜索...</Text>
</Modal>
{this.state.Loading?<PurpleLoading></PurpleLoading>:null}
{this.state.SearchHistory?<SearchHistory></SearchHistory>:null}
{this.state.SearchContent?<SearchContent></SearchContent>:null}
{this.state.SearchResult?<SearchResult data={this.state.data}></SearchResult>:null}
</View>
);
};
};
class PurpleSearchHeader extends Component{
constructor(props){
super(props);
this.state={
text:'',
keyboardType:props.keyboardType?props.keyboardType:'default'
};
}
render(){
return(
<View style={[styles.searchHeader,styles.flex]}>
<TouchableOpacity style={[styles.searchHeaderBack]} onPress={()=>{this.props.root.pop();}}>
<Icon style={[styles.searchHeaderBackIcon]} name="angle-left" color="#fff" />
</TouchableOpacity>
<TextInput ref='searchInput' style={[styles.searchHeaderTextInput]}
keyboardType={this.state.keyboardType}
autoFocus={true}
autoCapitalize={'characters'}
style={[styles.searchHeaderTextInput]}
clearButtonMode="while-editing"
placeholder="请输入提单号或者箱号"
onChangeText={this.props.onChangeText}
returnKeyType="go">
</TextInput>
<TouchableOpacity onPress={this.props.onEndEditing} style={[styles.searchHeaderSearchBtn]}>
<Text style={[styles.searchHeaderSearchBtnText]}>搜索</Text>
</TouchableOpacity>
</View>
);
}
}
class SearchHistory extends Component {
constructor(props) {
super(props);
}
render(){
return(
<View style={styles.container}>
<Text>搜索历史</Text>
</View>
);
};
}
class SearchContent extends Component{
constructor(props){
super(props);
}
render(){
return(
<View>
<Text>搜索建议</Text>
</View>
);
};
};
class SearchResult extends Component {
constructor(props) {
super(props);
this.state={
data:props.data,
};
};
render(){
return(
<ScrollView style={{marginTop:10}}>
<Text>qq</Text>
<PurpleItem></PurpleItem>
<PurpleItem></PurpleItem>
</ScrollView>
)};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF'
},
header:{
paddingTop:20,
paddingLeft:10,
height:55,
backgroundColor:'#444',
flexDirection:'row',
alignItems:'center',
},
fontFamily:{
color: '#fff',
fontFamily:'iconfont',
fontSize: 24
},
headerLeftText:{
fontSize:20,
color:'#fff'
},
headerLeftIcon:{
marginTop:5,
},
searchBar:{
flexDirection:'row',
marginTop:25,
backgroundColor:'#ccc',
},
searchBarBtn:{
width:90,
backgroundColor:'#666',
height:35,
justifyContent:'center',
alignItems:'center',
marginLeft:-5,
marginRight:5,
borderRadius:4,
},
searchBarBtnText:{
color:'#fff',
fontWeight:'bold',
fontSize:15,
justifyContent:'center',
alignItems:'center',
},
searchInputStyle:{
padding:5,
flexDirection:'row',
backgroundColor:colors.grey6,
},
searchInput:{
flex:1,
height:30,
borderWidth:1,
marginLeft:5,
marginRight:5,
marginTop:5,
marginBottom:5,
borderColor:colors.grey5,
backgroundColor:'#fff',
borderRadius:4,
},
searchInputText:{
marginTop:5,
paddingLeft:5,
justifyContent:'center',
},
searchInputBtn:{
justifyContent:'center',
alignItems:'flex-end',
marginRight:10,
paddingLeft:10,
},
searchInputBtnText:{
justifyContent:'center',
alignItems:'center',
},
searchHeader:{
paddingTop:25,
flexDirection:'row',
backgroundColor:colors.grey6,
paddingBottom:10,
borderBottomWidth:1/PixelRatio.get(),
borderBottomColor:colors.grey5,
},
searchHeaderBack:{
flexDirection:'row',
justifyContent:'center',
alignItems:'center',
paddingLeft:10,
paddingRight:10,
},
searchHeaderBackText:{
fontSize:16,
color:colors.grey2,
marginLeft:5,
},
searchHeaderBackIcon:{
marginLeft:5,
fontSize:20,
color:colors.grey2,
},
searchHeaderTextInput:{
flex:1,
height:30,
borderWidth:1,
marginLeft:5,
borderColor:colors.grey5,
backgroundColor:'#fff',
borderRadius:4,
fontSize:12,
paddingLeft:10,
},
searchHeaderSearchBtn:{
justifyContent:'center',
alignItems:'center',
marginRight:10,
paddingLeft:10,
},
searchHeaderSearchBtnText:{
justifyContent:'center',
alignItems:'center',
},
modal: {
justifyContent: 'center',
alignItems: 'center',
flexDirection:'row',
},
modal2: {
width:Dimensions.get('window').width/2,
height:50,
borderRadius:3,
},
modalLoadingIcon:{
marginLeft:-20,
},
modalLoadingText:{
}
});
module.exports = PurpleSearchInput;
|
docs/tests/useSelect.js | paypal/downshift | import React from 'react'
import {useSelect} from '../../src'
import {items, menuStyles} from '../utils'
export default function DropdownSelect() {
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({items})
return (
<div>
<label {...getLabelProps()}>Choose an element:</label>
<button data-testid='select-toggle-button' {...getToggleButtonProps()}>{selectedItem || 'Elements'}</button>
<ul {...getMenuProps()} style={menuStyles}>
{isOpen &&
items.map((item, index) => (
<li
style={
highlightedIndex === index ? {backgroundColor: '#bde4ff'} : {}
}
key={`${item}${index}`}
{...getItemProps({item, index})}
>
{item}
</li>
))}
</ul>
</div>
)
}
|
src/svg-icons/hardware/laptop-mac.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopMac = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
HardwareLaptopMac = pure(HardwareLaptopMac);
HardwareLaptopMac.displayName = 'HardwareLaptopMac';
HardwareLaptopMac.muiName = 'SvgIcon';
export default HardwareLaptopMac;
|
ajax/libs/forerunnerdb/1.3.854/fdb-core+persist.js | joeyparrish/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":29,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":8,"../lib/Shim.IE8":35}],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 {Object} data The data / document to use for lookups.
* @param {Object} options An options object.
* @param {Operation} op An optional operation instance. Pass undefined
* if not being used.
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, op, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
//regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; }
resultArr._visitedCount++;
resultArr._visitedNodes = resultArr._visitedNodes || [];
resultArr._visitedNodes.push(thisDataPathVal);
result = this.sortAsc(thisDataPathValSubStr, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":34}],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,
Condition,
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');
Condition = _dereq_('./Condition');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
* @param {Object=} val The data to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
* @param {Boolean=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
* @param {Number=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
/**
* Adds a job id to the async queue to signal to other parts
* of the application that some async work is currently being
* done.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
/**
* Removes a job id from the async queue to signal to other
* parts of the application that some async work has been
* completed. If no further async jobs exist on the queue then
* the "ready" event is emitted from this collection instance.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @param {Function=} callback A callback method to call once the
* operation has completed.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection by updating the
* lastChange timestamp on the collection's metaData. This
* only happens if the changeTimestamp option is enabled
* on the collection (it is disabled by default).
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
*/
'*': function (data) {
return this.$main.call(this, data, {});
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
*/
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Function} callback Optional callback function.
*/
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {*} callback Optional callback function.
*/
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents
* in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Inserts a new document or updates an existing document in a
* collection depending on if a matching primary key exists in
* the collection already or not.
*
* If the document contains a primary key field (based on the
* collections's primary key) then the database will search for
* an existing document with a matching id. If a matching
* document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with
* new data. Any keys that do not currently exist on the document
* will be added to the document.
*
* If the document does not contain an id or the id passed does
* not match an existing document, an insert is performed instead.
* If no id is present a new primary key id is provided for the
* document and the document is inserted.
*
* @param {Object} obj The document object to upsert or an array
* containing documents to upsert.
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains
* either "insert" or "update" depending on the type of operation
* that was performed and "result" contains the return data from
* the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection.
* This will update all matches for 'query' with the data held
* in 'update'. It will not overwrite the matched documents
* with the update document.
*
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Detect $replace operations and set flag
if (update.$replace) {
// Make sure we have an options object
options = options || {};
// Set the $replace flag in the options object
options.$replace = true;
// Move the replacement object out into the main update object
update = update.$replace;
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
/**
* Handles the update operation that was initiated by a call to update().
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
* @private
*/
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
self._removeFromIndexes(referencedDoc);
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
self._insertIntoIndexes(referencedDoc);
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
self._removeFromIndexes(referencedDoc);
result = self.updateObject(referencedDoc, update, query, options, '');
self._insertIntoIndexes(referencedDoc);
}
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this, updated || []); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
} else {
if (callback) { callback.call(this, updated || []); }
}
} else {
if (callback) { callback.call(this, updated || []); }
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references. It does this by removing existing keys
* from the base object and then adding the passed object's keys to
* the existing base object, thereby maintaining any references to
* the existing base object but effectively replacing the object with
* the new one.
* @param {Object} currentObj The base object to alter.
* @param {Object} newObj The new object to overwrite the existing one
* with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document via it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to
* update to.
* @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;
// Check if we have a $replace flag in the options object
if (options && options.$replace === true) {
operation = true;
replaceObj = update;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
// Early exit
return updated;
}
// DEVS PLEASE NOTE -- Early exit could have occurred above and code below will never be reached - Rob Evans - CEO - 05/08/2016
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (!operation && i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (!operation && this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$splicePull':
// Check that the target key is not undefined
if (doc[i] !== undefined) {
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update[i].$index;
if (tempIndex !== undefined) {
// Check for in bounds index
if (tempIndex < doc[i].length) {
this._updateSplicePull(doc[i], tempIndex);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePull from a key that is not an array! (' + i + ')');
}
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark
* (a dollar at the end of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search
* query key/values.
* @param {Object=} query The query identifying the documents to remove. If no
* query object is passed, all documents will be removed from the collection.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* The insert operation's callback.
* @callback Collection~insertCallback
* @param {Object} result The result object will contain two arrays (inserted
* and failed) which represent the documents that did get inserted and those
* that didn't for some reason (usually index violation). Failed items also
* contain a reason. Inspect the failed array for further information.
*
* A third field called "deferred" is a boolean value to indicate if the
* insert operation was deferred across more than one CPU cycle (to avoid
* blocking the main thread).
*/
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed});
this.deferEmit('change', {type: 'insert', data: inserted, failed: failed});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update (must be
* actual reference to original document).
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param {String} search The string to search for. Case sensitive.
* @param {Object=} options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = [].concat(analysis.indexMatch[0].lookup) || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
// Now process any $groupBy clause
if (options.$groupBy) {
op.data('flag.group', true);
op.time('group');
resultArr = this.group(options.$groupBy, resultArr);
op.time('group');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
/**
* Groups an array of documents into multiple array fields, named by the value
* of the given group path.
* @param {*} groupObj The key path the array objects should be grouped by.
* @param {Array} arr The array of documents to group.
* @returns {Object}
*/
Collection.prototype.group = function (groupObj, arr) {
// Convert the index object to an array of key val objects
var keys = sharedPathSolver.parse(groupObj, true),
groupPathSolver = new Path(),
groupValue,
groupResult = {},
keyIndex,
i;
if (keys.length) {
for (keyIndex = 0; keyIndex < keys.length; keyIndex++) {
groupPathSolver.path(keys[keyIndex].path);
// Execute group
for (i = 0; i < arr.length; i++) {
groupValue = groupPathSolver.get(arr[i]);
groupResult[groupValue] = groupResult[groupValue] || [];
groupResult[groupValue].push(arr[i]);
}
}
}
return groupResult;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param {String} key The path to sort by.
* @param {Array} arr The array of objects to sort.
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and
* returns an object containing details about the query which
* can be used to optimise the search.
*
* @param {Object} query The search query to analyse.
* @param {Object} options The query options object.
* @param {Operation} op The instance of the Operation class that
* this operation is using to track things like performance and steps
* taken etc.
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = [].concat(this._primaryIndex.lookup(query, options, op));
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = [].concat(indexRef.lookup(query, options, op));
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents
* that matches the subDocQuery parameter.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
/**
* Creates a condition handler that will react to changes in data on the
* collection.
* @example Create a condition handler that reacts when data changes.
* var coll = db.collection('test'),
* condition = coll.when({_id: 'test1', val: 1})
* .then(function () {
* console.log('Condition met!');
* })
* .else(function () {
* console.log('Condition un-met');
* });
*
* coll.insert({_id: 'test1', val: 1});
*
* @see Condition
* @param {Object} query The query that will trigger the condition's then()
* callback.
* @returns {Condition}
*/
Collection.prototype.when = function (query) {
var queryId = this.objectId();
this._when = this._when || {};
this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query);
return this._when[queryId];
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @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;
},{"./Condition":7,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":32,"./Shared":34}],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');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":34}],7:[function(_dereq_,module,exports){
"use strict";
/**
* The condition class monitors a data source and updates it's internal
* state depending on clauses that it has been given. When all clauses
* are satisfied the then() callback is fired. If conditions were met
* but data changed that made them un-met, the else() callback is fired.
*/
var //Overload = require('./Overload'),
Shared,
Condition;
Shared = _dereq_('./Shared');
/**
* Create a constructor method that calls the instance's init method.
* This allows the constructor to be overridden by other modules because
* they can override the init method with their own.
*/
Condition = function () {
this.init.apply(this, arguments);
};
Condition.prototype.init = function (dataSource, id, clause) {
this._dataSource = dataSource;
this._id = id;
this._query = [clause];
this._started = false;
this._state = [false];
this._satisfied = false;
// Set this to true by default for faster performance
this.earlyExit(true);
};
// Tell ForerunnerDB about our new module
Shared.addModule('Condition', Condition);
// Mixin some commonly used methods
Shared.mixin(Condition.prototype, 'Mixin.Common');
Shared.mixin(Condition.prototype, 'Mixin.ChainReactor');
Shared.synthesize(Condition.prototype, 'id');
Shared.synthesize(Condition.prototype, 'then');
Shared.synthesize(Condition.prototype, 'else');
Shared.synthesize(Condition.prototype, 'earlyExit');
Shared.synthesize(Condition.prototype, 'debug');
/**
* Adds a new clause to the condition.
* @param {Object} clause The query clause to add to the condition.
* @returns {Condition}
*/
Condition.prototype.and = function (clause) {
this._query.push(clause);
this._state.push(false);
return this;
};
/**
* Starts the condition so that changes to data will call callback
* methods according to clauses being met.
* @param {*} initialState Initial state of condition.
* @returns {Condition}
*/
Condition.prototype.start = function (initialState) {
if (!this._started) {
var self = this;
if (arguments.length !== 0) {
this._satisfied = initialState;
}
// Resolve the current state
this._updateStates();
self._onChange = function () {
self._updateStates();
};
// Create a chain reactor link to the data source so we start receiving CRUD ops from it
this._dataSource.on('change', self._onChange);
this._started = true;
}
return this;
};
/**
* Updates the internal status of all the clauses against the underlying
* data source.
* @private
*/
Condition.prototype._updateStates = function () {
var satisfied = true,
i;
for (i = 0; i < this._query.length; i++) {
this._state[i] = this._dataSource.count(this._query[i]) > 0;
if (this._debug) {
console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]);
}
if (!this._state[i]) {
satisfied = false;
// Early exit since we have found a state that is not true
if (this._earlyExit) {
break;
}
}
}
if (this._satisfied !== satisfied) {
// Our state has changed, fire the relevant operation
if (satisfied) {
// Fire the "then" operation
if (this._then) {
this._then();
}
} else {
// Fire the "else" operation
if (this._else) {
this._else();
}
}
this._satisfied = satisfied;
}
};
/**
* Stops the condition so that callbacks will no longer fire.
* @returns {Condition}
*/
Condition.prototype.stop = function () {
if (this._started) {
this._dataSource.off('change', this._onChange);
delete this._onChange;
this._started = false;
}
return this;
};
/**
* Drops the condition and removes it from memory.
* @returns {Condition}
*/
Condition.prototype.drop = function () {
this.stop();
delete this._dataSource.when[this._id];
return this;
};
// Tell ForerunnerDB that our module has finished loading
Shared.finishModule('Condition');
module.exports = Condition;
},{"./Shared":34}],8:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":34}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":15,"./Overload":27,"./Shared":34}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders,
PI180 = Math.PI / 180,
PI180R = 180 / Math.PI,
earthRadius = 6371; // mean radius of the earth
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
/**
* Converts degrees to radians.
* @param {Number} degrees
* @return {Number} radians
*/
GeoHash.prototype.radians = function radians (degrees) {
return degrees * PI180;
};
/**
* Converts radians to degrees.
* @param {Number} radians
* @return {Number} degrees
*/
GeoHash.prototype.degrees = function (radians) {
return radians * PI180R;
};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates a new lat/lng by travelling from the center point in the
* bearing specified for the distance specified.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} distanceKm The distance to travel in kilometers.
* @param {Number} bearing The bearing to travel in degrees (zero is
* north).
* @returns {{lat: Number, lng: Number}}
*/
GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) {
var curLon = centerPoint[1],
curLat = centerPoint[0],
destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))),
tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)),
destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º
return {
lat: this.degrees(destLat),
lng: this.degrees(destLon)
};
};
/**
* Calculates the extents of a bounding box around the center point which
* encompasses the radius in kilometers passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param radiusKm Radius in kilometers.
* @returns {{lat: Array, lng: Array}}
*/
GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) {
var maxWest,
maxEast,
maxNorth,
maxSouth,
lat = [],
lng = [];
maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0);
maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90);
maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180);
maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270);
lat[0] = maxNorth.lat;
lat[1] = maxSouth.lat;
lng[0] = maxWest.lng;
lng[1] = maxEast.lng;
return {
lat: lat,
lng: lng
};
};
/**
* Calculates all the geohashes that make up the bounding box that surrounds
* the circle created from the center point and radius passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} radiusKm The radius in kilometers to encompass.
* @param {Number} precision The number of characters to limit the returned
* geohash strings to.
* @returns {Array} The array of geohashes that encompass the bounding box.
*/
GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) {
var extent = this.calculateExtentByRadius(centerPoint, radiusKm),
northWest = [extent.lat[0], extent.lng[0]],
northEast = [extent.lat[0], extent.lng[1]],
southWest = [extent.lat[1], extent.lng[0]],
northWestHash = this.encode(northWest[0], northWest[1], precision),
northEastHash = this.encode(northEast[0], northEast[1], precision),
southWestHash = this.encode(southWest[0], southWest[1], precision),
hash,
widthCount = 0,
heightCount = 0,
widthIndex,
heightIndex,
hashArray = [];
hash = northWestHash;
hashArray.push(hash);
// Walk from north west to north east until we find the north east geohash
while (hash !== northEastHash) {
hash = this.calculateAdjacent(hash, 'right');
widthCount++;
hashArray.push(hash);
}
hash = northWestHash;
// Walk from north west to south west until we find the south west geohash
while (hash !== southWestHash) {
hash = this.calculateAdjacent(hash, 'bottom');
heightCount++;
}
// We now know the width and height in hash boxes of the area, fill in the
// rest of the hashes into the hashArray array
for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) {
hash = hashArray[widthIndex];
for (heightIndex = 0; heightIndex < heightCount; heightIndex++) {
hash = this.calculateAdjacent(hash, 'bottom');
hashArray.push(hash);
}
}
return hashArray;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to a longitude/latitude array.
* The array contains three latitudes and three longitudes. The
* first of each is the lower extent of the geohash bounding box,
* the second is the upper extent and the third is the center
* of the geohash bounding box.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
lat: lat,
lng: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
if (typeof module !== 'undefined') { module.exports = GeoHash; }
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
/**
* Looks up records that match the passed query and options.
* @param query The query to execute.
* @param options A query options object.
* @param {Operation=} op Optional operation instance that allows
* us to provide operation diagnostics and analytics back to the
* main calling instance as the process is running.
* @returns {*}
*/
Index2d.prototype.lookup = function (query, options, op) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options, op));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options, op) {
var self = this,
neighbours,
visitedCount,
visitedNodes,
visitedData,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
}
if (precision === 0) {
precision = 1;
}
// Calculate 9 box geohashes
if (op) { op.time('index2d.calculateHashArea'); }
neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision);
if (op) { op.time('index2d.calculateHashArea'); }
if (op) {
op.data('index2d.near.precision', precision);
op.data('index2d.near.hashArea', neighbours);
op.data('index2d.near.maxDistanceKm', maxDistanceKm);
op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]);
}
// Lookup all matching co-ordinates from the btree
results = [];
visitedCount = 0;
visitedData = {};
visitedNodes = [];
if (op) { op.time('index2d.near.getDocsInsideHashArea'); }
for (i = 0; i < neighbours.length; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visitedData[neighbours[i]] = search;
visitedCount += search._visitedCount;
visitedNodes = visitedNodes.concat(search._visitedNodes);
results = results.concat(search);
}
if (op) {
op.time('index2d.near.getDocsInsideHashArea');
op.data('index2d.near.startsWith', visitedData);
op.data('index2d.near.visitedTreeNodes', visitedNodes);
}
// Work with original data
if (op) { op.time('index2d.near.lookupDocsById'); }
results = this._collection._primaryIndex.lookup(results);
if (op) { op.time('index2d.near.lookupDocsById'); }
if (query.$distanceField) {
// Decouple the results before we modify them
results = this.decouple(results);
}
if (results.length) {
distance = {};
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
if (query.$distanceField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371));
}
if (query.$geoHashField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision));
}
// Add item as it is inside radius distance
finalResults.push(results[i]);
}
}
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Sort by distance from center
if (op) { op.time('index2d.near.sortResultsByDistance'); }
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
if (op) { op.time('index2d.near.sortResultsByDistance'); }
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.');
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":10,"./Path":28,"./Shared":34}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options, op) {
return this._btree.lookup(query, options, op);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":28,"./Shared":34}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":34}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk] !== undefined && val[pk] !== null) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":34}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":34}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Gets / sets the flag that will enable / disable chain reactor sending
* from this instance. Chain reactor sending is enabled by default on all
* instances.
* @param {Boolean} val True or false to enable or disable chain sending.
* @returns {*}
*/
chainEnabled: function (val) {
if (val !== undefined) {
this._chainDisabled = !val;
return this;
}
return !this._chainDisabled;
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain && !this._chainDisabled);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain && !this._chainDisabled) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":33}],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,
fired = false,
internalCallback = function () {
if (!fired) {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
fired = true;
}
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
fired = false,
internalCallback = function () {
if (!fired) {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
fired = true;
}
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event);
});
} else {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
}
return this;
},
'string, function': function (event, listener) {
var self = this,
arr,
index;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, listener);
});
} else {
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, id, listener);
});
} else {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
},
'string, *': function (event, id) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, id);
});
} else {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
this._emitting = true;
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
this._emitting = false;
this._processRemovalQueue();
return this;
},
/**
* If events are cleared with the off() method while the event emitter is
* actively processing any events then the off() calls get added to a
* queue to be executed after the event emitter is finished. This stops
* errors that might occur by potentially modifying the event queue while
* the emitter is running through them. This method is called after the
* event emitter is finished processing.
* @private
*/
_processRemovalQueue: function () {
var i;
if (this._eventRemovalQueue && this._eventRemovalQueue.length) {
// Execute each removal call
for (i = 0; i < this._eventRemovalQueue.length; i++) {
this._eventRemovalQueue[i]();
}
// Clear the removal queue
this._eventRemovalQueue = [];
}
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$fastIn':
if (test instanceof Array) {
// Source is a string or number, use indexOf to identify match in array
return test.indexOf(source) !== -1;
} else {
console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Removes an item from the passed array at the specified index.
* @param {Array} arr The array to remove from.
* @param {Number} index The index of the item to remove.
* @param {Number} count The number of items to remove.
* @private
*/
_updateSplicePull: function (arr, index, count) {
if (!count) { count = 1; }
arr.splice(index, count);
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":34}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":34}],29:[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 || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
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 || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
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) {
if (!err) {
localforage.setItem(key, data).then(function (data) {
if (callback) {
callback(false, data, tableStats);
}
}, function (err) {
if (callback) {
callback(err);
}
});
} else {
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, tableData, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, metaData, metaStats) {
if (callback) {
callback(err, tableStats, metaStats, {
tableData: tableData,
metaData: metaData,
tableDataName: self._db._name + '-' + self._name,
metaDataName: self._db._name + '-' + self._name + '-metaData'
});
}
});
} 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) {
// Remove all previous data
self.remove({}, function () {
// Now insert the new data
data = data || [];
self.insert(data, function () {
// 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); }
});
});
//self.setData(data);
});
} 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":30,"./PersistCrypto":31,"./Shared":34,"async":37,"localforage":75}],30:[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":34,"pako":77}],31:[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":34,"crypto-js":46}],32:[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":34}],33:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],34:[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.854',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],35:[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 = {};
},{}],36:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":93}],37:[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 (typeof arguments[1] === 'function') {
// 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 hasError = false;
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) {
if (hasError) return;
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;
hasError = true;
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 nonexistent dependency in ' + requires.join(', '));
}
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.apply(null, [null].concat(args));
}
});
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 () {
while(!q.paused && 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 = {};
var has = Object.prototype.hasOwnProperty;
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (has.call(memo, key)) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (has.call(queues, key)) {
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":93}],38:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],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) {
/**
* 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":40}],40:[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;
}));
},{}],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) {
(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);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":40}],42:[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":40}],43:[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":40,"./hmac":45,"./sha1":64}],44:[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":39,"./core":40}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var 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":40}],46:[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":38,"./cipher-core":39,"./core":40,"./enc-base64":41,"./enc-utf16":42,"./evpkdf":43,"./format-hex":44,"./hmac":45,"./lib-typedarrays":47,"./md5":48,"./mode-cfb":49,"./mode-ctr":51,"./mode-ctr-gladman":50,"./mode-ecb":52,"./mode-ofb":53,"./pad-ansix923":54,"./pad-iso10126":55,"./pad-iso97971":56,"./pad-nopadding":57,"./pad-zeropadding":58,"./pbkdf2":59,"./rabbit":61,"./rabbit-legacy":60,"./rc4":62,"./ripemd160":63,"./sha1":64,"./sha224":65,"./sha256":66,"./sha3":67,"./sha384":68,"./sha512":69,"./tripledes":70,"./x64-core":71}],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 () {
// 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":40}],48:[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":40}],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) {
/**
* 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":39,"./core":40}],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) {
/** @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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],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) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":39,"./core":40}],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) {
/**
* 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":39,"./core":40}],59:[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":40,"./hmac":45,"./sha1":64}],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;
// 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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],61:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],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;
/**
* 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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],63:[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":40}],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 () {
// 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":40}],65:[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":40,"./sha256":66}],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 (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":40}],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 (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":40,"./x64-core":71}],68:[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":40,"./sha512":69,"./x64-core":71}],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 () {
// 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":40,"./x64-core":71}],70:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],71:[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":40}],72:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// 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;
// 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 = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.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];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
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') {
window.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') {
window.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') {
window.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
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":95}],73:[function(_dereq_,module,exports){
// 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).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
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;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// 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 + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
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') {
window.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 = 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 keyPrefix = self._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 = 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') {
window.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') {
window.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) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
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
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":76,"promise":95}],74:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// 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 serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
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 serializerPromise.then(function(lib) {
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') {
window.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 = 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 = 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') {
window.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;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
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') {
window.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
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":76,"promise":95}],75:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// 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 ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
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
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// 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 globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// 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]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// 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(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(driverObject, callback,
errorCallback) {
var defineDriver = 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);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// 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.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":72,"./drivers/localstorage":73,"./drivers/websql":74,"promise":95}],76:[function(_dereq_,module,exports){
(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
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],77:[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":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate');
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);
* ```
**/
function Deflate(options) {
if (!(this instanceof Deflate)) return new Deflate(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 algorithm 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":80,"./utils/strings":81,"./zlib/deflate":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate');
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);
* ```
**/
function Inflate(options) {
if (!(this instanceof Inflate)) return new Inflate(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":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[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);
},{}],81:[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":80}],82:[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;
},{}],83:[function(_dereq_,module,exports){
'use strict';
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
};
},{}],84:[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 ^= -1;
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],85:[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.
*/
function Config(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":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[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;
},{}],87:[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;
};
},{}],88:[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;
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":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[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":80}],90:[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) */
};
},{}],91:[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) */
/* eslint-disable comma-spacing,array-bracket-spacing */
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];
/* eslint-enable comma-spacing,array-bracket-spacing */
/* 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) */
function StaticTreeDesc(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;
function TreeDesc(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":80}],92:[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;
},{}],93:[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; };
},{}],94:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":36}],95:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":94,"asap":36}]},{},[1]);
|
src/components/Footer.js | amit-kulkarni/react-food-order | import React from 'react';
export default function Footer() {
return (
<footer className="container">
<div className="row justify-content-center py-2" style={{textAlign: "center"}}>
<div className="col-12 col-md-3 my-1"> Copyright © None </div>
<div className="col-12 col-md-3 my-1"><a href="#">Terms and Conditions</a></div>
<div className="col-12 col-md-3 my-1">Twitter</div>
<div className="col-12 col-md-3 my-1">Facebook</div>
</div>
</footer>
)
} |
stories/Welcome.js | hollomancer/operationcode_frontend | import React from 'react';
const styles = {
main: {
margin: 15,
maxWidth: 600,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
},
logo: {
width: 200,
},
link: {
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
},
code: {
fontSize: 15,
fontWeight: 600,
padding: "2px 5px",
border: "1px solid #eae9e9",
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
},
note: {
opacity: 0.5,
}
};
export default class Welcome extends React.Component {
showApp(e) {
e.preventDefault();
if(this.props.showApp) this.props.showApp();
}
render() {
return (
<div style={styles.main}>
<h1>Welcome to STORYBOOK</h1>
<p>
This is a UI component dev environment for your app.
</p>
<p>
We've added some basic stories inside the <code style={styles.code}>src/stories</code> directory.
<br/>
A story is a single state of one or more UI components. You can have as many stories as you want.
<br/>
(Basically a story is like a visual test case.)
</p>
<p>
See these sample <a style={styles.link} href='#' onClick={this.showApp.bind(this)}>stories</a> for a component called <code style={styles.code}>Button</code>.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <code style={styles.code}>Button</code> component
located at <code style={styles.code}>src/stories/Button.js</code>.)
</p>
<p>
This is just one thing you can do with Storybook.
<br/>
Have a look at the <a style={styles.link} href="https://github.com/kadirahq/react-storybook" target="_blank">React Storybook</a> repo for more information.
</p>
<p style={styles.note}>
<b>NOTE:</b>
<br/>
Have a look at the <code style={styles.code}>.storybook/webpack.config.js</code> to add webpack
loaders and plugins you are using in this project.
</p>
</div>
);
}
}
|
blueocean-material-icons/src/js/components/svg-icons/image/image-aspect-ratio.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageImageAspectRatio = (props) => (
<SvgIcon {...props}>
<path d="M16 10h-2v2h2v-2zm0 4h-2v2h2v-2zm-8-4H6v2h2v-2zm4 0h-2v2h2v-2zm8-6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12z"/>
</SvgIcon>
);
ImageImageAspectRatio.displayName = 'ImageImageAspectRatio';
ImageImageAspectRatio.muiName = 'SvgIcon';
export default ImageImageAspectRatio;
|
jquery.js | lowearthorbiter/sheen | /*! 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&>(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); |
app/jsx/course_wizard/Checklist.js | venturehive/canvas-lms | /*
* Copyright (C) 2014 - 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 ChecklistItem from './ChecklistItem'
import ListItems from './ListItems'
import I18n from 'i18n!course_wizard'
var Checklist = React.createClass({
displayName: 'Checklist',
propTypes: {
selectedItem: PropTypes.string.isRequired,
clickHandler: PropTypes.func.isRequired,
className: PropTypes.string.isRequired
},
getInitialState: function () {
return {
selectedItem: this.props.selectedItem || ''
};
},
componentWillReceiveProps: function (newProps) {
this.setState({
selectedItem: newProps.selectedItem
});
},
renderChecklist: function () {
return ListItems.map((item) => {
var isSelected = this.state.selectedItem === item.key;
var id = 'wizard_' + item.key;
return (
<ChecklistItem complete={item.complete}
id={id}
key={item.key}
stepKey={item.key}
title={item.title}
onClick={this.props.clickHandler}
isSelected={isSelected}
/>
);
});
},
render: function () {
var checklist = this.renderChecklist();
return (
<div className={this.props.className}>
<h2 className='screenreader-only'>{I18n.t('Setup Checklist')}</h2>
<ul className='ic-wizard-box__nav-checklist'>{checklist}</ul>
</div>
);
}
});
export default Checklist
|
node_modules/material-ui/svg-icons/communication/import-export.js | Jbeagle/writeItEasy2.0 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CommunicationImportExport = function CommunicationImportExport(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3z' })
);
};
CommunicationImportExport = (0, _pure2.default)(CommunicationImportExport);
CommunicationImportExport.displayName = 'CommunicationImportExport';
CommunicationImportExport.muiName = 'SvgIcon';
exports.default = CommunicationImportExport; |
svg-icons/action/g-translate.js | dhavalbyteprophecy/material-ui-build | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ActionGTranslate = function ActionGTranslate(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M20 5h-9.12L10 2H4c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h7l1 3h8c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zM7.17 14.59c-2.25 0-4.09-1.83-4.09-4.09s1.83-4.09 4.09-4.09c1.04 0 1.99.37 2.74 1.07l.07.06-1.23 1.18-.06-.05c-.29-.27-.78-.59-1.52-.59-1.31 0-2.38 1.09-2.38 2.42s1.07 2.42 2.38 2.42c1.37 0 1.96-.87 2.12-1.46H7.08V9.91h3.95l.01.07c.04.21.05.4.05.61 0 2.35-1.61 4-3.92 4zm6.03-1.71c.33.6.74 1.18 1.19 1.7l-.54.53-.65-2.23zm.77-.76h-.99l-.31-1.04h3.99s-.34 1.31-1.56 2.74c-.52-.62-.89-1.23-1.13-1.7zM21 20c0 .55-.45 1-1 1h-7l2-2-.81-2.77.92-.92L17.79 18l.73-.73-2.71-2.68c.9-1.03 1.6-2.25 1.92-3.51H19v-1.04h-3.64V9h-1.04v1.04h-1.96L11.18 6H20c.55 0 1 .45 1 1v13z' })
);
};
ActionGTranslate = (0, _pure2.default)(ActionGTranslate);
ActionGTranslate.displayName = 'ActionGTranslate';
ActionGTranslate.muiName = 'SvgIcon';
exports.default = ActionGTranslate; |
src/views/components/LockCard.js | physiii/open-automation | import React from 'react';
import PropTypes from 'prop-types';
import ServiceCardBase from './ServiceCardBase.js';
import Button from './Button.js';
import {connect} from 'react-redux';
import {lockLock, lockUnlock} from '../../state/ducks/services-list/operations.js';
export const LockCard = (props) => {
const isLocked = props.service.state.get('locked'),
toggleLock = () => {
if (isLocked) {
props.unlock(props.service.id);
} else {
props.lock(props.service.id);
}
};
return (
<ServiceCardBase
name={props.service.settings.get('name') || 'Lock'}
status={props.service.state.get('locked') ? 'Locked' : 'Unlocked'}
isConnected={props.service.state.get('connected')}
onCardClick={toggleLock}
{...props}>
<Button onClick={toggleLock}>{props.service.state.get('locked') ? 'Unlock' : 'Lock'}</Button>
</ServiceCardBase>
);
};
LockCard.propTypes = {
service: PropTypes.object,
lock: PropTypes.func,
unlock: PropTypes.func
};
const mapDispatchToProps = (dispatch) => {
return {
lock: (serviceId) => dispatch(lockLock(serviceId)),
unlock: (serviceId) => dispatch(lockUnlock(serviceId))
};
};
export default connect(null, mapDispatchToProps)(LockCard);
|
src/components/Link/Link.js | ihnat/work-hard | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes, Component } from 'react';
import Location from '../../core/Location';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends Component {
static propTypes = {
to: PropTypes.string.isRequired,
state: PropTypes.object,
onClick: PropTypes.func,
};
static handleClick = (event) => {
let allowTransition = true;
let clickResult;
if (this.props && this.props.onClick) {
clickResult = this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (clickResult === false || event.defaultPrevented === true) {
allowTransition = false;
}
event.preventDefault();
if (allowTransition) {
const link = event.currentTarget;
Location.pushState(
this.props && this.props.state || null,
this.props && this.props.to || (link.pathname + link.search));
}
};
render() {
const { to, query, ...props } = this.props;
return <a href={Location.createHref(to, query)} onClick={Link.handleClick.bind(this)} {...props} />;
}
}
export default Link;
|
test/components/stateless/SubmitButtonTest.js | thomas-p-wilson/react-form | /* eslint-disable no-unused-expressions */
import React from 'react';
import { expect } from 'chai';
import {
fullRender,
shallowRender,
click
} from '../../utils';
import SubmitButton from '../../../src/components/stateless/SubmitButton';
import basicFieldTests from '../BasicFieldTests';
const validProps = {
'name': 'test',
'onClick': () => {}
};
describe('SubmitButton', () => {
describe('Basic field tests', basicFieldTests(SubmitButton, validProps));
describe('Prop tests', () => {
it('Should accept valid props', () => {
const component = shallowRender(<SubmitButton { ...validProps } />);
expect(component.props.name).to.equal('test');
expect(component.props.type).to.equal('submit');
expect(component.props.onClick).to.be.function;
});
});
describe('Click tests', () => {
it('Should execute click handler on click', () => {
let tmp = false;
const component = fullRender(
<SubmitButton name="test"
value="a"
onClick={ function (name, value) {
tmp = [name, value];
} }>
Execute
</SubmitButton>
);
click(component);
expect(tmp[0]).to.equal('test');
expect(tmp[1]).to.equal('a');
});
it('Should do nothing without click handler', () => {
const component = fullRender(
<SubmitButton name="test"
type="submit">Execute</SubmitButton>
);
click(component);
});
});
}); |
src/Parser/Druid/Restoration/Modules/Features/Lifebloom.js | hasseboulen/WoWAnalyzer | import React from 'react';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import { formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import ItemLink from 'common/ItemLink';
import Wrapper from 'common/Wrapper';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
class Lifebloom extends Analyzer {
static dependencies = {
combatants: Combatants,
};
hasDta;
on_initialized() {
this.hasDta = this.combatants.selected.hasWaist(ITEMS.THE_DARK_TITANS_ADVICE.id);
}
get uptime() {
return Object.keys(this.combatants.players)
.map(key => this.combatants.players[key])
.reduce((uptime, player) =>
uptime + player.getBuffUptime(SPELLS.LIFEBLOOM_HOT_HEAL.id), 0);
}
get uptimePercent() {
return this.uptime / this.owner.fightDuration;
}
// "The Dark Titan's Advice" legendary buffs Lifebloom, making high uptime more important
get suggestionThresholds() {
if (this.hasDta) {
return {
actual: this.uptimePercent,
isLessThan: {
minor: 0.90,
average: 0.80,
major: 0.70,
},
style: 'percentage',
};
} else {
return {
actual: this.uptimePercent,
isLessThan: {
minor: 0.80,
average: 0.60,
major: 0.40,
},
style: 'percentage',
};
}
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper>Your <SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} /> uptime can be improved. {this.hasDta ? <Wrapper>High uptime is particularly important for taking advantage of your equipped <ItemLink id={ITEMS.THE_DARK_TITANS_ADVICE.id} icon /></Wrapper> : ''}</Wrapper>)
.icon(SPELLS.LIFEBLOOM_HOT_HEAL.icon)
.actual(`${formatPercentage(this.uptimePercent)}% uptime`)
.recommended(`>${Math.round(formatPercentage(recommended))}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.LIFEBLOOM_HOT_HEAL.id} />}
value={`${formatPercentage(this.uptimePercent)} %`}
label="Lifebloom Uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(10);
}
export default Lifebloom;
|
static/src/components/Footer.js | Termnator/mikebot | // @flow
import React from 'react';
import numeral from 'numeral';
import * as StatsActions from '../actions/StatsActions';
import * as ShareActions from '../actions/ShareActions';
import ShareStore from '../stores/ShareStore';
import Constants from '../Constants';
const Footer = React.createClass({
render() {
const {count, changeCount, showStatsPanel, statsHasBeenShown} = this.props;
let statsBtnClasses = 'crossfade';
if (statsHasBeenShown) {
if (showStatsPanel) {
statsBtnClasses += ' two';
}
else {
statsBtnClasses += ' two-reverse';
}
}
let statsBtn2Classes = 'crossfade';
if (statsHasBeenShown) {
if (showStatsPanel) {
statsBtn2Classes += ' three';
}
else {
statsBtn2Classes += ' three-reverse';
}
}
let toolTip = 'Click for more Stats';
if (showStatsPanel) {
toolTip = '';
}
return (
<div className="footer">
<div className="airhorn-count">
<div className="stats-toggler" onClick={StatsActions.toggleStatsPanel}>
<div className="airhorn-count-content">
<img src={Constants.Image.AIRHORN_COUNTER} />
<div className="count-text">
<div className={`count ${changeCount ? 'count-big' : ''}`}>
{numeral(count).format('0,0')}
</div>
<div className="and-counting">and counting</div>
</div>
</div>
<div className="stats-btn">
<img
src={Constants.Image.ICON_CLOSE}
className={statsBtn2Classes}
onClick={StatsActions.hideStatsPanel} />
<img
src={Constants.Image.ICON_ABOUT}
className={statsBtnClasses}
data-tip={toolTip} />
</div>
</div>
</div>
<div className="main-text">
<span className="normal-text">
Open sourced by the team at Discord. Contribute yourself on
</span>
<a href={Constants.GITHUB_URL}>GitHub</a>
<a href={Constants.GITHUB_URL} className="arrow"> ➔</a>
</div>
<div className="social">
<img src={Constants.Image.ICON_TWITTER} onClick={ShareActions.withTwitter} />
<img src={Constants.Image.ICON_FACEBOOK} onClick={ShareActions.withFacebook} />
</div>
</div>
);
}
});
export default Footer;
|
e2e-tests/production-runtime/src/pages/env-vars.js | ChristopherBiscardi/gatsby | import React from 'react'
import Layout from '../components/layout'
const UseEnv = ({ heading, envVar }) => (
<React.Fragment>
<h2>{heading}</h2>
<pre>
<code data-testid={heading}>{JSON.stringify(envVar)}</code>
</pre>
</React.Fragment>
)
const SecondPage = () => (
<Layout>
<h1>Using env vars</h1>
<UseEnv heading="process.env" envVar={process.env} />
<UseEnv
heading="process.env.EXISTING_VAR"
envVar={process.env.EXISTING_VAR}
/>
<UseEnv
heading="process.env.NOT_EXISTING_VAR"
envVar={process.env.NOT_EXISTING_VAR}
/>
</Layout>
)
export default SecondPage
|
docs/src/app/components/pages/components/Stepper/HorizontalNonLinearStepper.js | igorbt/material-ui | import React from 'react';
import {
Step,
Stepper,
StepButton,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
/**
* Non-linear steppers allow users to enter a multi-step flow at any point.
*
* This example is similar to the regular horizontal stepper, except steps are no longer
* automatically set to `disabled={true}` based on the `activeStep` prop.
*
* We've used the `<StepButton>` here to demonstrate clickable step labels.
*/
class HorizontalNonLinearStepper extends React.Component {
state = {
stepIndex: 0,
};
handleNext = () => {
const {stepIndex} = this.state;
if (stepIndex < 2) {
this.setState({stepIndex: stepIndex + 1});
}
};
handlePrev = () => {
const {stepIndex} = this.state;
if (stepIndex > 0) {
this.setState({stepIndex: stepIndex - 1});
}
};
getStepContent(stepIndex) {
switch (stepIndex) {
case 0:
return 'Select campaign settings...';
case 1:
return 'What is an ad group anyways?';
case 2:
return 'This is the bit I really care about!';
default:
return 'You\'re a long way from home sonny jim!';
}
}
render() {
const {stepIndex} = this.state;
const contentStyle = {margin: '0 16px'};
return (
<div style={{width: '100%', maxWidth: 700, margin: 'auto'}}>
<Stepper linear={false} activeStep={stepIndex}>
<Step>
<StepButton onClick={() => this.setState({stepIndex: 0})}>
Select campaign settings
</StepButton>
</Step>
<Step>
<StepButton onClick={() => this.setState({stepIndex: 1})}>
Create an ad group
</StepButton>
</Step>
<Step>
<StepButton onClick={() => this.setState({stepIndex: 2})}>
Create an ad
</StepButton>
</Step>
</Stepper>
<div style={contentStyle}>
<p>{this.getStepContent(stepIndex)}</p>
<div style={{marginTop: 12}}>
<FlatButton
label="Back"
disabled={stepIndex === 0}
onClick={this.handlePrev}
style={{marginRight: 12}}
/>
<RaisedButton
label="Next"
disabled={stepIndex === 2}
primary={true}
onClick={this.handleNext}
/>
</div>
</div>
</div>
);
}
}
export default HorizontalNonLinearStepper;
|
test/specs/chart/BarChartSpec.js | scostaqb/recharts | import React from 'react';
import { expect } from 'chai';
import { BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts';
import { mount, render } from 'enzyme';
describe('<BarChart />', () => {
const data = [
{ name: 'food', uv: 400, pv: 2400 },
{ name: 'cosmetic', uv: 300, pv: 4567 },
{ name: 'storage', uv: 300, pv: 1398 },
{ name: 'digital', uv: 200, pv: 9800 },
];
it('Renders 8 bars in simple BarChart', () => {
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar dataKey="uv" fill="#ff7300"/>
<Bar dataKey="pv" fill="#387908"/>
</BarChart>
);
expect(wrapper.find('.recharts-rectangle').length).to.equal(8);
});
it('Render 4 labels when label is setted to be true', () => {
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar isAnimationActive={false} dataKey="uv" label fill="#ff7300"/>
</BarChart>
);
expect(wrapper.find('.recharts-bar-rectangle-labels').length).to.equal(1);
expect(wrapper.find('.recharts-bar-label').length).to.equal(4);
});
it('Renders 4 bar labels when label is set to be a react element', () => {
const Label = (props) => {
const { x, y, index } = props;
return <text key={`label-${index}`} x={x} y={y} className="customized-label">test</text>
};
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar isAnimationActive={false} dataKey="uv" fill="#ff7300" label={<Label/>}/>
</BarChart>
);
expect(wrapper.find('.customized-label').length).to.equal(4);
});
it('Renders 4 bar labels when label is set to be a function', () => {
const renderLabel = (props) => {
const { x, y, index } = props;
return <text key={`label-${index}`} x={x} y={y} className="customized-label">test</text>
};
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar isAnimationActive={false} dataKey="uv" fill="#ff7300" label={renderLabel}/>
</BarChart>
);
expect(wrapper.find('.customized-label').length).to.equal(4);
});
it('Don\'t renders any bars when no Bar item is added', () => {
const wrapper = render(
<BarChart width={100} height={50} data={data}>
</BarChart>
);
expect(wrapper.find('.recharts-rectangle').length).to.equal(0);
});
it('Renders 8 bars in a vertical BarChart', () => {
const wrapper = render(
<BarChart width={100} height={50} data={data} layout="vertical">
<XAxis type="number"/>
<YAxis type="category" dataKey="name"/>
<Bar dataKey="uv" fill="#ff7300"/>
<Bar dataKey="pv" fill="#387908"/>
</BarChart>
);
expect(wrapper.find('.recharts-rectangle').length).to.equal(8);
});
it('Renders 8 bars in a stacked BarChart', () => {
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<YAxis />
<Bar dataKey="uv" stackId="test" fill="#ff7300"/>
<Bar dataKey="pv" stackId="test" fill="#387908"/>
</BarChart>
);
expect(wrapper.find('.recharts-rectangle').length).to.equal(8);
});
// it('Renders tooltip when Tooltip item is added', () => {
// const wrapper = mount(
// <BarChart width={100} height={50} data={data}>
// <Bar dataKey="uv" stackId="test" fill="#ff7300" />
// <Bar dataKey="pv" stackId="test" fill="#387908" />
// <Tooltip />
// </BarChart>
// );
// wrapper.setState({
// isTooltipActive: true,
// activeTooltipIndex: 3,
// activeTooltipLabel: 4,
// activeTooltipCoord: {
// x: 95,
// y: 21,
// },
// });
// expect(wrapper.find('.recharts-default-tooltip').length).to.equal(1);
// expect(wrapper.find('.recharts-tooltip-wrapper').length).to.equal(1);
// });
it('Render empty when data is empty', () => {
const wrapper = render(
<BarChart width={100} height={50} data={[]}>
<Bar dataKey="uv" label fill="#ff7300"/>
</BarChart>
);
expect(wrapper.find('path').length).to.equal(0);
});
it('Render customized shapem when shape is set to be a react element', () => {
const Shape = (props) => {
const {x, y, width, height} = props;
return <circle className="customized-shape" cx={x} cy={y} r={8}/>
}
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar dataKey="uv" label fill="#ff7300" shape={<Shape/>}/>
</BarChart>
);
expect(wrapper.find('.customized-shape').length).to.equal(4);
});
it('Render customized shapem when shape is set to be a function', () => {
const renderShape = (props) => {
const {x, y, width, height} = props;
return <circle className="customized-shape" cx={x} cy={y} r={8}/>
}
const wrapper = render(
<BarChart width={100} height={50} data={data}>
<Bar dataKey="uv" label fill="#ff7300" shape={renderShape}/>
</BarChart>
);
expect(wrapper.find('.customized-shape').length).to.equal(4);
});
});
|
code/workspaces/web-app/src/components/modal/EditDataStoreDialog.spec.js | NERC-CEH/datalab | import React from 'react';
import { shallow } from 'enzyme';
import EditDataStoreDialog, { getOnDetailsEditSubmit } from './EditDataStoreDialog';
import modalDialogActions from '../../actions/modalDialogActions';
import dataStorageActions from '../../actions/dataStorageActions';
const editDataStoreDetailsMock = jest.fn();
const loadDataStorageMock = jest.fn();
dataStorageActions.editDataStoreDetails = editDataStoreDetailsMock;
dataStorageActions.loadDataStorage = loadDataStorageMock;
describe('Edit data store dialog', () => {
function shallowRender(props) {
return shallow(<EditDataStoreDialog {...props} />);
}
it('creates correct snapshot', () => {
// Arrange / Act
const output = shallowRender({
onCancel: jest.fn().mockName('onCancel'),
title: 'expectedTitle',
currentUsers: [{ label: 'expectedLabelOne', value: 'expectedValueOne' }],
userList: [{ label: 'expectedLabelTwo', value: 'expectedValueTwo' }],
loadUsersPromise: {
error: null,
fetching: false,
value: [],
},
stack: { name: 'stackName', displayName: 'Stack Display Name', description: 'Stack description' },
projectKey: 'project99',
typeName: 'Data Store',
});
// Assert
expect(output).toMatchSnapshot();
});
});
describe('getOnDetailsRequestSubmit returns a function that', () => {
const projectKey = 'project99';
const stackName = 'stackname';
const typeName = 'Data Store';
const onDetailsEditSubmit = getOnDetailsEditSubmit(projectKey, stackName, typeName);
const dispatchMock = jest.fn();
const values = {
displayName: 'Display Name',
users: [{ label: 'User One', value: 'userone' }, { label: 'User Two', value: 'usertwo' }],
};
beforeEach(() => {
jest.resetAllMocks();
});
it('dispatches action to close the modal dialog', async () => {
await onDetailsEditSubmit(values, dispatchMock);
expect(dispatchMock).toBeCalledWith(modalDialogActions.closeModalDialog());
});
it('dispatches action to update data store details with correct values', async () => {
const actionReturnValue = { type: 'EDIT_DATA_STORE_ACTION' };
editDataStoreDetailsMock.mockReturnValue(actionReturnValue);
await onDetailsEditSubmit(values, dispatchMock);
expect(dispatchMock).toBeCalledWith(actionReturnValue);
expect(editDataStoreDetailsMock).toBeCalledWith(
projectKey, stackName, { displayName: 'Display Name', users: ['userone', 'usertwo'] },
);
});
it('dispatches action to reload the data storage with correct values', async () => {
const actionReturnValue = { type: 'LOAD_DATA_STORAGE_ACTION' };
loadDataStorageMock.mockReturnValue(actionReturnValue);
await onDetailsEditSubmit(values, dispatchMock);
expect(dispatchMock).toBeCalledWith(actionReturnValue);
expect(loadDataStorageMock).toBeCalledWith(projectKey);
});
});
|
app/component/resume/PersonalDetailsSectionPage.js | mrFlick72/mrFlick72.github.io | import React from 'react';
import avatar from '../../asset/images/myPhoto.jpeg';
import ResumeRow from "./ResumeRow";
const PERSONAL_DETAILS_LABEL = {
"firstName": "First Name",
"lastName": "Last Name",
"address": "Address",
"zip": "Zip",
"city": "City",
"region": "Region",
"mail": "E-Mail",
"skype": "Skype",
"mobile": "Mobile",
"birthDate": "Birth Date",
"state": "State",
"sex": "Sex",
"taxCode": "Tax Code"
}
export default ({personalDetails}) => {
return <div>
<ResumeRow label="" avatar={avatar}/>{
Object.keys(personalDetails).map(function (key, index) {
return <ResumeRow label={PERSONAL_DETAILS_LABEL[key]}
content={personalDetails[key]}/>
})}</div>
} |
index.android.js | bangwu/leavemessage | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class leavemessage extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('leavemessage', () => leavemessage);
|
src/app.js | Schubidu/gambling-block | import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createHashHistory';
import { syncReduxAndRouter } from 'redux-simple-router';
import routes from './routes';
import Root from './containers/Root';
import configureStore from './redux/configureStore';
const history = createBrowserHistory();
const store = configureStore(window.__INITIAL_STATE__);
syncReduxAndRouter(history, store, (state) => state.router);
// Render the React application to the DOM
ReactDOM.render(
<Root history={history} routes={routes} store={store}/>,
document.getElementById('root')
);
|
stories/Lookup.js | propertybase/react-lds | import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, object, text } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { Button, Lookup, Spinner } from '../src';
const stories = storiesOf('Lookup', module);
const exampleData = [
{
id: '1',
email: '[email protected]',
label: 'Something',
meta: 'Very meta',
objectType: 'contact',
},
{
id: '2',
email: '[email protected]',
label: 'Really',
objectType: 'contact',
},
{
id: '3',
email: '[email protected]',
label: 'Not so',
objectType: 'contact',
},
{
id: '4',
email: '[email protected]',
label: 'Much useful',
objectType: 'contact',
},
{
id: '5',
email: '[email protected]',
label: 'Of any type',
objectType: 'contact',
},
{
id: '6',
email: '[email protected]',
label: 'Of some type',
objectType: 'account',
},
{
id: '7',
email: '[email protected]',
label: 'Of some record type',
objectType: 'record',
},
];
stories
.add('Uncontrolled', () => (
<Lookup
allowCreate={boolean('AllowCreate', false)}
error={text('Error', '') || undefined}
hideErrorMessage={boolean('HideErrorMessage', false)}
hideLabel={boolean('HideLabel', false)}
id="lookup"
initialSelection={object('InitialSelection', [{
id: '6',
email: '[email protected]',
label: 'Of some type',
objectType: 'account',
}])}
inputLabel={text('InputLabel', 'Accounts')}
listLabel={text('ListLabel', 'Recent Accounts')}
load={() => exampleData}
loadOnChange={boolean('Call load() onInputChange', true) || undefined}
loadOnFocus={boolean('Call load() onInputFocus', false) || undefined}
loadOnMount={boolean('Call load() onComponentDidMount', false) || undefined}
multi={boolean('Multi selection mode', false)}
objectType={text('ObjectType', '') || undefined}
onChange={action('changed')}
onFocus={action('focussed')}
placeholder={text('Placeholder', 'Search Accounts')}
required={boolean('Required', false)}
/>
))
.add('Uncontrolled with custom value', () => (
<Lookup
allowCreate={boolean('AllowCreate', true)}
error={text('Error', '') || undefined}
hideErrorMessage={boolean('HideErrorMessage', false)}
hideLabel={boolean('HideLabel', false)}
id="lookup"
selection={object('InitialSelection', [{
id: '1',
label: 'Custom value',
objectType: '',
}])}
inputLabel={text('InputLabel', 'Accounts')}
listLabel={text('ListLabel', 'Recent Accounts')}
load={() => []}
multi={boolean('Multi selection mode', false)}
objectType={text('ObjectType', '') || undefined}
onChange={action('changed')}
onFocus={action('focussed')}
placeholder={text('Placeholder', 'Search Accounts')}
required={boolean('Required', false)}
/>
))
.add('Controlled', () => (
<Lookup
error={text('Error', '') || undefined}
hideErrorMessage={boolean('HideErrorMessage', false)}
hideLabel={boolean('HideLabel', false)}
id="lookup"
inputLabel={text('InputLabel', 'Accounts')}
listLabel={text('ListLabel', 'Recent Accounts')}
load={() => exampleData}
loadOnChange={boolean('Call load() onInputChange', false)}
loadOnFocus={boolean('Call load() onInputFocus', false)}
loadOnMount={boolean('Call load() onComponentDidMount', false)}
multi={boolean('Multi selection mode', true)}
objectType={text('ObjectType', '') || undefined}
onChange={action('changed')}
onFocus={action('focussed')}
placeholder={text('Placeholder', 'Search Accounts')}
selection={object('Selection', [{
id: '6',
email: '[email protected]',
label: 'Of some type',
objectType: 'account',
}, {
id: '7',
email: '[email protected]',
label: 'Of some record type',
objectType: 'record',
}])}
required={boolean('Required', false)}
/>
))
.add('With custom selection and meta info', () => (
<Lookup
error={text('Error', '') || undefined}
hideErrorMessage={boolean('HideErrorMessage', false)}
hideLabel={boolean('HideLabel', false)}
id="lookup"
initialSelection={object('InitialSelection', [
{
id: '4',
email: '[email protected]',
meta: 'soo meta',
label: 'Much useful',
objectType: 'contact',
},
{
id: '5',
email: '[email protected]',
meta: 'soo meta',
label: 'Of any type',
objectType: 'contact',
},
{
id: '6',
email: '[email protected]',
meta: 'soo meta',
label: 'Of some type',
objectType: 'account',
},
{
id: '7',
email: '[email protected]',
meta: 'soo meta',
label: 'Of some record type',
objectType: 'record',
}
])}
inputLabel={text('InputLabel', 'Accounts')}
listLabel={text('ListLabel', 'Recent Accounts')}
load={() => exampleData}
loadOnChange={boolean('Call load() onInputChange', true) || undefined}
loadOnFocus={boolean('Call load() onInputFocus', false) || undefined}
loadOnMount={boolean('Call load() onComponentDidMount', false) || undefined}
multi={boolean('Multi selection mode', true)}
objectType={text('ObjectType', '') || undefined}
onChange={action('changed')}
onFocus={action('focussed')}
placeholder={text('Placeholder', 'Search Accounts')}
required={boolean('Required', false)}
renderMeta={() => (
<div>
<Spinner
style={{
top: '9px',
left: '6px',
position: 'relative',
}}
size="xx-small"
/>
<span className="slds-lookup__result-meta slds-text-body_small slds-m-left_medium">
Loading meta info...
</span>
</div>
)}
renderSelection={(item, { onClose }) => {
let f;
switch (item.objectType) {
case 'record':
f = 'destructive';
break;
case 'account':
f = 'brand';
break;
default:
f = null;
break;
}
return (
<Button
key={item.id}
onClick={onClose}
title={item.label}
tooltip="Click to deselect"
flavor={f}
/>
);
}}
/>
));
|
ajax/libs/remoteStorage/0.14.0/remotestorage-nocache.js | joeyparrish/cdnjs | /** remotestorage.js 0.14.0, http://remotestorage.io, MIT-licensed **/
/** FILE: lib/bluebird.js **/
/**
* bluebird build version 2.3.4
* Features enabled: core, nodeify
* Features disabled: race, call_get, generators, map, promisify, props, reduce, settle, some, progress, cancel, using, filter, any, each, timers
*/
/**
* @preserve Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=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(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var schedule = _dereq_("./schedule.js");
var Queue = _dereq_("./queue.js");
var errorObj = _dereq_("./util.js").errorObj;
var tryCatch1 = _dereq_("./util.js").tryCatch1;
var _process = typeof process !== "undefined" ? process : void 0;
function Async() {
this._isTickUsed = false;
this._schedule = schedule;
this._length = 0;
this._lateBuffer = new Queue(16);
this._functionBuffer = new Queue(65536);
var self = this;
this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() {
self._consumeFunctionBuffer();
};
}
Async.prototype.haveItemsQueued = function Async$haveItemsQueued() {
return this._length > 0;
};
Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) {
if (_process !== void 0 &&
_process.domain != null &&
!fn.domain) {
fn = _process.domain.bind(fn);
}
this._lateBuffer.push(fn, receiver, arg);
this._queueTick();
};
Async.prototype.invoke = function Async$invoke(fn, receiver, arg) {
if (_process !== void 0 &&
_process.domain != null &&
!fn.domain) {
fn = _process.domain.bind(fn);
}
var functionBuffer = this._functionBuffer;
functionBuffer.push(fn, receiver, arg);
this._length = functionBuffer.length();
this._queueTick();
};
Async.prototype._consumeFunctionBuffer =
function Async$_consumeFunctionBuffer() {
var functionBuffer = this._functionBuffer;
while (functionBuffer.length() > 0) {
var fn = functionBuffer.shift();
var receiver = functionBuffer.shift();
var arg = functionBuffer.shift();
fn.call(receiver, arg);
}
this._reset();
this._consumeLateBuffer();
};
Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() {
var buffer = this._lateBuffer;
while(buffer.length() > 0) {
var fn = buffer.shift();
var receiver = buffer.shift();
var arg = buffer.shift();
var res = tryCatch1(fn, receiver, arg);
if (res === errorObj) {
this._queueTick();
if (fn.domain != null) {
fn.domain.emit("error", res.e);
} else {
throw res.e;
}
}
}
};
Async.prototype._queueTick = function Async$_queue() {
if (!this._isTickUsed) {
this._schedule(this.consumeFunctionBuffer);
this._isTickUsed = true;
}
};
Async.prototype._reset = function Async$_reset() {
this._isTickUsed = false;
this._length = 0;
};
module.exports = new Async();
},{"./queue.js":15,"./schedule.js":16,"./util.js":19}],2:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var Promise = _dereq_("./promise.js")();
module.exports = Promise;
},{"./promise.js":12}],3:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function() {
var inherits = _dereq_("./util.js").inherits;
var defineProperty = _dereq_("./es5.js").defineProperty;
var rignore = new RegExp(
"\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" +
"tryCatch(?:1|2|3|4|Apply)|new \\w*PromiseArray|" +
"\\w*PromiseArray\\.\\w*PromiseArray|" +
"setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" +
"process._tickCallback|nextTick|Async\\$\\w+)\\b"
);
var rtraceline = null;
var formatStack = null;
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj.toString();
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function CapturedTrace(ignoreUntil, isTopLevel) {
this.captureStackTrace(CapturedTrace, isTopLevel);
}
inherits(CapturedTrace, Error);
CapturedTrace.prototype.captureStackTrace =
function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) {
captureStackTrace(this, ignoreUntil, isTopLevel);
};
CapturedTrace.possiblyUnhandledRejection =
function CapturedTrace$PossiblyUnhandledRejection(reason) {
if (typeof console === "object") {
var message;
if (typeof reason === "object" || typeof reason === "function") {
var stack = reason.stack;
message = "Possibly unhandled " + formatStack(stack, reason);
} else {
message = "Possibly unhandled " + String(reason);
}
if (typeof console.error === "function" ||
typeof console.error === "object") {
console.error(message);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
};
CapturedTrace.combine = function CapturedTrace$Combine(current, prev) {
var curLast = current.length - 1;
for (var i = prev.length - 1; i >= 0; --i) {
var line = prev[i];
if (current[curLast] === line) {
current.pop();
curLast--;
} else {
break;
}
}
current.push("From previous event:");
var lines = current.concat(prev);
var ret = [];
for (var i = 0, len = lines.length; i < len; ++i) {
if (((rignore.test(lines[i]) && rtraceline.test(lines[i])) ||
(i > 0 && !rtraceline.test(lines[i])) &&
lines[i] !== "From previous event:")
) {
continue;
}
ret.push(lines[i]);
}
return ret;
};
CapturedTrace.protectErrorMessageNewlines = function(stack) {
for (var i = 0; i < stack.length; ++i) {
if (rtraceline.test(stack[i])) {
break;
}
}
if (i <= 1) return;
var errorMessageLines = [];
for (var j = 0; j < i; ++j) {
errorMessageLines.push(stack.shift());
}
stack.unshift(errorMessageLines.join("\u0002\u0000\u0001"));
};
CapturedTrace.isSupported = function CapturedTrace$IsSupported() {
return typeof captureStackTrace === "function";
};
var captureStackTrace = (function stackDetection() {
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
rtraceline = /^\s*at\s*/;
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
var captureStackTrace = Error.captureStackTrace;
return function CapturedTrace$_captureStackTrace(
receiver, ignoreUntil) {
captureStackTrace(receiver, ignoreUntil);
};
}
var err = new Error();
if (typeof err.stack === "string" &&
typeof "".startsWith === "function" &&
(err.stack.startsWith("stackDetection@")) &&
stackDetection.name === "stackDetection") {
defineProperty(Error, "stackTraceLimit", {
writable: true,
enumerable: false,
configurable: false,
value: 25
});
rtraceline = /@/;
var rline = /[@\n]/;
formatStack = function(stack, error) {
if (typeof stack === "string") {
return (error.name + ". " + error.message + "\n" + stack);
}
if (error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
return function captureStackTrace(o) {
var stack = new Error().stack;
var split = stack.split(rline);
var len = split.length;
var ret = "";
for (var i = 0; i < len; i += 2) {
ret += split[i];
ret += "@";
ret += split[i + 1];
ret += "\n";
}
o.stack = ret;
};
} else {
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
return null;
}
})();
return CapturedTrace;
};
},{"./es5.js":8,"./util.js":19}],4:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util.js");
var errors = _dereq_("./errors.js");
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
var keys = _dereq_("./es5.js").keys;
var TypeError = errors.TypeError;
function CatchFilter(instances, callback, promise) {
this._instances = instances;
this._callback = callback;
this._promise = promise;
}
function CatchFilter$_safePredicate(predicate, e) {
var safeObject = {};
var retfilter = tryCatch1(predicate, safeObject, e);
if (retfilter === errorObj) return retfilter;
var safeKeys = keys(safeObject);
if (safeKeys.length) {
errorObj.e = new TypeError(
"Catch filter must inherit from Error "
+ "or be a simple predicate function");
return errorObj;
}
return retfilter;
}
CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundTo;
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||
(item != null && item.prototype instanceof Error);
if (itemIsErrorType && e instanceof item) {
var ret = tryCatch1(cb, boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
} else if (typeof item === "function" && !itemIsErrorType) {
var shouldHandle = CatchFilter$_safePredicate(item, e);
if (shouldHandle === errorObj) {
var trace = errors.canAttach(errorObj.e)
? errorObj.e
: new Error(errorObj.e + "");
this._promise._attachExtraTrace(trace);
e = errorObj.e;
break;
} else if (shouldHandle) {
var ret = tryCatch1(cb, boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
}
}
}
NEXT_FILTER.e = e;
return NEXT_FILTER;
};
return CatchFilter;
};
},{"./errors.js":6,"./es5.js":8,"./util.js":19}],5:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
module.exports = function(Promise) {
var returner = function Promise$_returner() {
return this;
};
var thrower = function Promise$_thrower() {
throw this;
};
var wrapper = function Promise$_wrapper(value, action) {
if (action === 1) {
return function Promise$_thrower() {
throw value;
};
} else if (action === 2) {
return function Promise$_returner() {
return value;
};
}
};
Promise.prototype["return"] =
Promise.prototype.thenReturn =
function Promise$thenReturn(value) {
if (wrapsPrimitiveReceiver && isPrimitive(value)) {
return this._then(
wrapper(value, 2),
void 0,
void 0,
void 0,
void 0
);
}
return this._then(returner, void 0, void 0, value, void 0);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow =
function Promise$thenThrow(reason) {
if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
void 0,
void 0,
void 0,
void 0
);
}
return this._then(thrower, void 0, void 0, reason, void 0);
};
};
},{"./util.js":19}],6:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var Objectfreeze = _dereq_("./es5.js").freeze;
var util = _dereq_("./util.js");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof OperationalError) ||
e["isOperational"] === true);
}
function isError(obj) {
return obj instanceof Error;
}
function canAttach(obj) {
return isError(obj);
}
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
this.message = typeof message === "string" ? message : defaultMessage;
this.name = nameProperty;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
AggregateError.prototype.length = 0;
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
this.name = "OperationalError";
this.message = message;
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
this.message = message.message;
this.stack = message.stack;
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var key = "__BluebirdErrorTypes__";
var errorTypes = Error[key];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, key, errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
canAttach: canAttach
};
},{"./es5.js":8,"./util.js":19}],7:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise) {
var TypeError = _dereq_('./errors.js').TypeError;
function apiRejection(msg) {
var error = new TypeError(msg);
var ret = Promise.rejected(error);
var parent = ret._peekContext();
if (parent != null) {
parent._attachExtraTrace(error);
}
return ret;
}
return apiRejection;
};
},{"./errors.js":6}],8:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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 isES5 = (function(){
"use strict";
return this === void 0;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
keys: Object.keys,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
}
var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
}
var ObjectFreeze = function ObjectFreeze(obj) {
return obj;
}
var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
}
var ArrayIsArray = function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
}
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5
};
}
},{}],9:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise, NEXT_FILTER, cast) {
var util = _dereq_("./util.js");
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
function returnThis() {
return this;
}
function throwThis() {
throw this;
}
function return$(r) {
return function Promise$_returner() {
return r;
};
}
function throw$(r) {
return function Promise$_thrower() {
throw r;
};
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
}
return ret._then(then, thrower, void 0, reasonOrValue, void 0);
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo)
: handler();
if (ret !== void 0) {
var maybePromise = cast(ret, void 0);
if (maybePromise instanceof Promise) {
return promisedFinally(maybePromise, reasonOrValue,
promise.isFulfilled());
}
}
if (promise.isRejected()) {
NEXT_FILTER.e = reasonOrValue;
return NEXT_FILTER;
} else {
return reasonOrValue;
}
}
function tapHandler(value) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo, value)
: handler(value);
if (ret !== void 0) {
var maybePromise = cast(ret, void 0);
if (maybePromise instanceof Promise) {
return promisedFinally(maybePromise, value, true);
}
}
return value;
}
Promise.prototype._passThroughHandler =
function Promise$_passThroughHandler(handler, isFinally) {
if (typeof handler !== "function") return this.then();
var promiseAndHandler = {
promise: this,
handler: handler
};
return this._then(
isFinally ? finallyHandler : tapHandler,
isFinally ? finallyHandler : void 0, void 0,
promiseAndHandler, void 0);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function Promise$finally(handler) {
return this._passThroughHandler(handler, true);
};
Promise.prototype.tap = function Promise$tap(handler) {
return this._passThroughHandler(handler, false);
};
};
},{"./util.js":19}],10:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports =
function(Promise, PromiseArray, cast, INTERNAL) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var caller = function(count) {
var values = [];
for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
return new Function("holder", " \n\
'use strict'; \n\
var callback = holder.fn; \n\
return callback(values); \n\
".replace(/values/g, values.join(", ")));
};
var thenCallbacks = [];
var callers = [void 0];
for (var i = 1; i <= 5; ++i) {
thenCallbacks.push(thenCallback(i));
callers.push(caller(i));
}
var Holder = function(total, fn) {
this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
this.fn = fn;
this.total = total;
this.now = 0;
};
Holder.prototype.callers = callers;
Holder.prototype.checkFulfillment = function(promise) {
var now = this.now;
now++;
var total = this.total;
if (now >= total) {
var handler = this.callers[total];
var ret = tryCatch1(handler, void 0, this);
if (ret === errorObj) {
promise._rejectUnchecked(ret.e);
} else if (!promise._tryFollow(ret)) {
promise._fulfillUnchecked(ret);
}
} else {
this.now = now;
}
};
}
Promise.join = function Promise$Join() {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (last < 6 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
var holder = new Holder(last, fn);
var reject = ret._reject;
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = cast(arguments[i], void 0);
if (maybePromise instanceof Promise) {
if (maybePromise.isPending()) {
maybePromise._then(callbacks[i], reject,
void 0, ret, holder);
} else if (maybePromise.isFulfilled()) {
callbacks[i].call(ret,
maybePromise._settledValue, holder);
} else {
ret._reject(maybePromise._settledValue);
maybePromise._unsetRejectionIsUnhandled();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
return ret;
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
var ret = new PromiseArray(args).promise();
return fn !== void 0 ? ret.spread(fn) : ret;
};
};
},{"./util.js":19}],11:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch2 = util.tryCatch2;
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
function thrower(r) {
throw r;
}
function Promise$_spreadAdapter(val, receiver) {
if (!util.isArray(val)) return Promise$_successAdapter(val, receiver);
var ret = util.tryCatchApply(this, [null].concat(val), receiver);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
function Promise$_successAdapter(val, receiver) {
var nodeback = this;
var ret = val === void 0
? tryCatch1(nodeback, receiver, null)
: tryCatch2(nodeback, receiver, null, val);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
function Promise$_errorAdapter(reason, receiver) {
var nodeback = this;
var ret = tryCatch1(nodeback, receiver, reason);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
Promise.prototype.nodeify = function Promise$nodeify(nodeback, options) {
if (typeof nodeback == "function") {
var adapter = Promise$_successAdapter;
if (options !== void 0 && Object(options).spread) {
adapter = Promise$_spreadAdapter;
}
this._then(
adapter,
Promise$_errorAdapter,
void 0,
nodeback,
this._boundTo
);
}
return this;
};
};
},{"./async.js":1,"./util.js":19}],12:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict(bluebird) {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
module.exports = function() {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var errors = _dereq_("./errors.js");
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {e: null};
var cast = _dereq_("./thenables.js")(Promise, INTERNAL);
var PromiseArray = _dereq_("./promise_array.js")(Promise, INTERNAL, cast);
var CapturedTrace = _dereq_("./captured_trace.js")();
var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
var PromiseResolver = _dereq_("./promise_resolver.js");
var isArray = util.isArray;
var errorObj = util.errorObj;
var tryCatch1 = util.tryCatch1;
var tryCatch2 = util.tryCatch2;
var tryCatchApply = util.tryCatchApply;
var RangeError = errors.RangeError;
var TypeError = errors.TypeError;
var CancellationError = errors.CancellationError;
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var originatesFromRejection = errors.originatesFromRejection;
var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection;
var canAttach = errors.canAttach;
var thrower = util.thrower;
var apiRejection = _dereq_("./errors_api_rejection")(Promise);
var makeSelfResolutionError = function Promise$_makeSelfResolutionError() {
return new TypeError("circular promise resolution chain");
};
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("the promise constructor requires a resolver function");
}
if (this.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly");
}
this._bitField = 0;
this._fulfillmentHandler0 = void 0;
this._rejectionHandler0 = void 0;
this._promise0 = void 0;
this._receiver0 = void 0;
this._settledValue = void 0;
this._boundTo = void 0;
if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
}
function returnFirstElement(elements) {
return elements[0];
}
Promise.prototype.bind = function Promise$bind(thisArg) {
var maybePromise = cast(thisArg, void 0);
var ret = new Promise(INTERNAL);
if (maybePromise instanceof Promise) {
var binder = maybePromise.then(function(thisArg) {
ret._setBoundTo(thisArg);
});
var p = Promise.all([this, binder]).then(returnFirstElement);
ret._follow(p);
} else {
ret._follow(this);
ret._setBoundTo(thisArg);
}
ret._propagateFrom(this, 2 | 1);
return ret;
};
Promise.prototype.toString = function Promise$toString() {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] =
function Promise$catch(fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (typeof item === "function") {
catchInstances[j++] = item;
} else {
var catchFilterTypeError =
new TypeError(
"A catch filter must be an error constructor "
+ "or a filter function");
this._attachExtraTrace(catchFilterTypeError);
return Promise.reject(catchFilterTypeError);
}
}
catchInstances.length = j;
fn = arguments[i];
this._resetTrace();
var catchFilter = new CatchFilter(catchInstances, fn, this);
return this._then(void 0, catchFilter.doFilter, void 0,
catchFilter, void 0);
}
return this._then(void 0, fn, void 0, void 0, void 0);
};
Promise.prototype.then =
function Promise$then(didFulfill, didReject, didProgress) {
return this._then(didFulfill, didReject, didProgress,
void 0, void 0);
};
Promise.prototype.done =
function Promise$done(didFulfill, didReject, didProgress) {
var promise = this._then(didFulfill, didReject, didProgress,
void 0, void 0);
promise._setIsFinal();
};
Promise.prototype.spread = function Promise$spread(didFulfill, didReject) {
return this._then(didFulfill, didReject, void 0,
APPLY, void 0);
};
Promise.prototype.isCancellable = function Promise$isCancellable() {
return !this.isResolved() &&
this._cancellable();
};
Promise.prototype.toJSON = function Promise$toJSON() {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: void 0,
rejectionReason: void 0
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this._settledValue;
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this._settledValue;
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function Promise$all() {
return new PromiseArray(this).promise();
};
Promise.is = function Promise$Is(val) {
return val instanceof Promise;
};
Promise.all = function Promise$All(promises) {
return new PromiseArray(promises).promise();
};
Promise.prototype.error = function Promise$_error(fn) {
return this.caught(originatesFromRejection, fn);
};
Promise.prototype._resolveFromSyncValue =
function Promise$_resolveFromSyncValue(value) {
if (value === errorObj) {
this._cleanValues();
this._setRejected();
this._settledValue = value.e;
this._ensurePossibleRejectionHandled();
} else {
var maybePromise = cast(value, void 0);
if (maybePromise instanceof Promise) {
this._follow(maybePromise);
} else {
this._cleanValues();
this._setFulfilled();
this._settledValue = value;
}
}
};
Promise.method = function Promise$_Method(fn) {
if (typeof fn !== "function") {
throw new TypeError("fn must be a function");
}
return function Promise$_method() {
var value;
switch(arguments.length) {
case 0: value = tryCatch1(fn, this, void 0); break;
case 1: value = tryCatch1(fn, this, arguments[0]); break;
case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break;
default:
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
value = tryCatchApply(fn, args, this); break;
}
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function");
}
var value = isArray(args)
? tryCatchApply(fn, args, ctx)
: tryCatch1(fn, ctx, args);
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.defer = Promise.pending = function Promise$Defer() {
var promise = new Promise(INTERNAL);
promise._setTrace(void 0);
return new PromiseResolver(promise);
};
Promise.bind = function Promise$Bind(thisArg) {
var maybePromise = cast(thisArg, void 0);
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
if (maybePromise instanceof Promise) {
var p = maybePromise.then(function(thisArg) {
ret._setBoundTo(thisArg);
});
ret._follow(p);
} else {
ret._setBoundTo(thisArg);
ret._setFulfilled();
}
return ret;
};
Promise.cast = function Promise$_Cast(obj) {
var ret = cast(obj, void 0);
if (!(ret instanceof Promise)) {
var val = ret;
ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._setFulfilled();
ret._cleanValues();
ret._settledValue = val;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function Promise$Reject(reason) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
markAsOriginatingFromRejection(reason);
ret._cleanValues();
ret._setRejected();
ret._settledValue = reason;
if (!canAttach(reason)) {
var trace = new Error(reason + "");
ret._setCarriedStackTrace(trace);
}
ret._ensurePossibleRejectionHandled();
return ret;
};
Promise.onPossiblyUnhandledRejection =
function Promise$OnPossiblyUnhandledRejection(fn) {
CapturedTrace.possiblyUnhandledRejection = typeof fn === "function"
? fn : void 0;
};
var unhandledRejectionHandled;
Promise.onUnhandledRejectionHandled =
function Promise$onUnhandledRejectionHandled(fn) {
unhandledRejectionHandled = typeof fn === "function" ? fn : void 0;
};
var debugging = false || !!(
typeof process !== "undefined" &&
typeof process.execPath === "string" &&
typeof process.env === "object" &&
(process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development")
);
Promise.longStackTraces = function Promise$LongStackTraces() {
if (async.haveItemsQueued() &&
debugging === false
) {
throw new Error("cannot enable long stack traces after promises have been created");
}
debugging = CapturedTrace.isSupported();
};
Promise.hasLongStackTraces = function Promise$HasLongStackTraces() {
return debugging && CapturedTrace.isSupported();
};
Promise.prototype._then =
function Promise$_then(
didFulfill,
didReject,
didProgress,
receiver,
internalData
) {
var haveInternalData = internalData !== void 0;
var ret = haveInternalData ? internalData : new Promise(INTERNAL);
if (!haveInternalData) {
if (debugging) {
var haveSameContext = this._peekContext() === this._traceParent;
ret._traceParent = haveSameContext ? this._traceParent : this;
}
ret._propagateFrom(this, 7);
}
var callbackIndex =
this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
if (this.isResolved()) {
async.invoke(this._queueSettleAt, this, callbackIndex);
}
return ret;
};
Promise.prototype._length = function Promise$_length() {
return this._bitField & 262143;
};
Promise.prototype._isFollowingOrFulfilledOrRejected =
function Promise$_isFollowingOrFulfilledOrRejected() {
return (this._bitField & 939524096) > 0;
};
Promise.prototype._isFollowing = function Promise$_isFollowing() {
return (this._bitField & 536870912) === 536870912;
};
Promise.prototype._setLength = function Promise$_setLength(len) {
this._bitField = (this._bitField & -262144) |
(len & 262143);
};
Promise.prototype._setFulfilled = function Promise$_setFulfilled() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._setRejected = function Promise$_setRejected() {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._setFollowing = function Promise$_setFollowing() {
this._bitField = this._bitField | 536870912;
};
Promise.prototype._setIsFinal = function Promise$_setIsFinal() {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._isFinal = function Promise$_isFinal() {
return (this._bitField & 33554432) > 0;
};
Promise.prototype._cancellable = function Promise$_cancellable() {
return (this._bitField & 67108864) > 0;
};
Promise.prototype._setCancellable = function Promise$_setCancellable() {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() {
this._bitField = this._bitField & (~67108864);
};
Promise.prototype._setRejectionIsUnhandled =
function Promise$_setRejectionIsUnhandled() {
this._bitField = this._bitField | 2097152;
};
Promise.prototype._unsetRejectionIsUnhandled =
function Promise$_unsetRejectionIsUnhandled() {
this._bitField = this._bitField & (~2097152);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled =
function Promise$_isRejectionUnhandled() {
return (this._bitField & 2097152) > 0;
};
Promise.prototype._setUnhandledRejectionIsNotified =
function Promise$_setUnhandledRejectionIsNotified() {
this._bitField = this._bitField | 524288;
};
Promise.prototype._unsetUnhandledRejectionIsNotified =
function Promise$_unsetUnhandledRejectionIsNotified() {
this._bitField = this._bitField & (~524288);
};
Promise.prototype._isUnhandledRejectionNotified =
function Promise$_isUnhandledRejectionNotified() {
return (this._bitField & 524288) > 0;
};
Promise.prototype._setCarriedStackTrace =
function Promise$_setCarriedStackTrace(capturedTrace) {
this._bitField = this._bitField | 1048576;
this._fulfillmentHandler0 = capturedTrace;
};
Promise.prototype._unsetCarriedStackTrace =
function Promise$_unsetCarriedStackTrace() {
this._bitField = this._bitField & (~1048576);
this._fulfillmentHandler0 = void 0;
};
Promise.prototype._isCarryingStackTrace =
function Promise$_isCarryingStackTrace() {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._getCarriedStackTrace =
function Promise$_getCarriedStackTrace() {
return this._isCarryingStackTrace()
? this._fulfillmentHandler0
: void 0;
};
Promise.prototype._receiverAt = function Promise$_receiverAt(index) {
var ret = index === 0
? this._receiver0
: this[(index << 2) + index - 5 + 4];
if (this._isBound() && ret === void 0) {
return this._boundTo;
}
return ret;
};
Promise.prototype._promiseAt = function Promise$_promiseAt(index) {
return index === 0
? this._promise0
: this[(index << 2) + index - 5 + 3];
};
Promise.prototype._fulfillmentHandlerAt =
function Promise$_fulfillmentHandlerAt(index) {
return index === 0
? this._fulfillmentHandler0
: this[(index << 2) + index - 5 + 0];
};
Promise.prototype._rejectionHandlerAt =
function Promise$_rejectionHandlerAt(index) {
return index === 0
? this._rejectionHandler0
: this[(index << 2) + index - 5 + 1];
};
Promise.prototype._addCallbacks = function Promise$_addCallbacks(
fulfill,
reject,
progress,
promise,
receiver
) {
var index = this._length();
if (index >= 262143 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
if (receiver !== void 0) this._receiver0 = receiver;
if (typeof fulfill === "function" && !this._isCarryingStackTrace())
this._fulfillmentHandler0 = fulfill;
if (typeof reject === "function") this._rejectionHandler0 = reject;
if (typeof progress === "function") this._progressHandler0 = progress;
} else {
var base = (index << 2) + index - 5;
this[base + 3] = promise;
this[base + 4] = receiver;
this[base + 0] = typeof fulfill === "function"
? fulfill : void 0;
this[base + 1] = typeof reject === "function"
? reject : void 0;
this[base + 2] = typeof progress === "function"
? progress : void 0;
}
this._setLength(index + 1);
return index;
};
Promise.prototype._setProxyHandlers =
function Promise$_setProxyHandlers(receiver, promiseSlotValue) {
var index = this._length();
if (index >= 262143 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promiseSlotValue;
this._receiver0 = receiver;
} else {
var base = (index << 2) + index - 5;
this[base + 3] = promiseSlotValue;
this[base + 4] = receiver;
this[base + 0] =
this[base + 1] =
this[base + 2] = void 0;
}
this._setLength(index + 1);
};
Promise.prototype._proxyPromiseArray =
function Promise$_proxyPromiseArray(promiseArray, index) {
this._setProxyHandlers(promiseArray, index);
};
Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) {
promise._setProxied();
this._setProxyHandlers(promise, -15);
};
Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) {
if (obj !== void 0) {
this._bitField = this._bitField | 8388608;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~8388608);
}
};
Promise.prototype._isBound = function Promise$_isBound() {
return (this._bitField & 8388608) === 8388608;
};
Promise.prototype._resolveFromResolver =
function Promise$_resolveFromResolver(resolver) {
var promise = this;
this._setTrace(void 0);
this._pushContext();
function Promise$_resolver(val) {
if (promise._tryFollow(val)) {
return;
}
promise._fulfill(val);
}
function Promise$_rejecter(val) {
var trace = canAttach(val) ? val : new Error(val + "");
promise._attachExtraTrace(trace);
markAsOriginatingFromRejection(val);
promise._reject(val, trace === val ? void 0 : trace);
}
var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter);
this._popContext();
if (r !== void 0 && r === errorObj) {
var e = r.e;
var trace = canAttach(e) ? e : new Error(e + "");
promise._reject(e, trace);
}
};
Promise.prototype._spreadSlowCase =
function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) {
var promiseForAll = new PromiseArray(values).promise();
var promise2 = promiseForAll._then(function() {
return targetFn.apply(boundTo, arguments);
}, void 0, void 0, APPLY, void 0);
promise._follow(promise2);
};
Promise.prototype._callSpread =
function Promise$_callSpread(handler, promise, value) {
var boundTo = this._boundTo;
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; ++i) {
if (cast(value[i], void 0) instanceof Promise) {
this._spreadSlowCase(handler, promise, value, boundTo);
return;
}
}
}
promise._pushContext();
return tryCatchApply(handler, value, boundTo);
};
Promise.prototype._callHandler =
function Promise$_callHandler(
handler, receiver, promise, value) {
var x;
if (receiver === APPLY && !this.isRejected()) {
x = this._callSpread(handler, promise, value);
} else {
promise._pushContext();
x = tryCatch1(handler, receiver, value);
}
promise._popContext();
return x;
};
Promise.prototype._settlePromiseFromHandler =
function Promise$_settlePromiseFromHandler(
handler, receiver, value, promise
) {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
return;
}
var x = this._callHandler(handler, receiver, promise, value);
if (promise._isFollowing()) return;
if (x === errorObj || x === promise || x === NEXT_FILTER) {
var err = x === promise
? makeSelfResolutionError()
: x.e;
var trace = canAttach(err) ? err : new Error(err + "");
if (x !== NEXT_FILTER) promise._attachExtraTrace(trace);
promise._rejectUnchecked(err, trace);
} else {
var castValue = cast(x, promise);
if (castValue instanceof Promise) {
if (castValue.isRejected() &&
!castValue._isCarryingStackTrace() &&
!canAttach(castValue._settledValue)) {
var trace = new Error(castValue._settledValue + "");
promise._attachExtraTrace(trace);
castValue._setCarriedStackTrace(trace);
}
promise._follow(castValue);
promise._propagateFrom(castValue, 1);
} else {
promise._fulfillUnchecked(x);
}
}
};
Promise.prototype._follow =
function Promise$_follow(promise) {
this._setFollowing();
if (promise.isPending()) {
this._propagateFrom(promise, 1);
promise._proxyPromise(this);
} else if (promise.isFulfilled()) {
this._fulfillUnchecked(promise._settledValue);
} else {
this._rejectUnchecked(promise._settledValue,
promise._getCarriedStackTrace());
}
if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled();
if (debugging &&
promise._traceParent == null) {
promise._traceParent = this;
}
};
Promise.prototype._tryFollow =
function Promise$_tryFollow(value) {
if (this._isFollowingOrFulfilledOrRejected() ||
value === this) {
return false;
}
var maybePromise = cast(value, void 0);
if (!(maybePromise instanceof Promise)) {
return false;
}
this._follow(maybePromise);
return true;
};
Promise.prototype._resetTrace = function Promise$_resetTrace() {
if (debugging) {
this._trace = new CapturedTrace(this._peekContext() === void 0);
}
};
Promise.prototype._setTrace = function Promise$_setTrace(parent) {
if (debugging) {
var context = this._peekContext();
this._traceParent = context;
var isTopLevel = context === void 0;
if (parent !== void 0 &&
parent._traceParent === context) {
this._trace = parent._trace;
} else {
this._trace = new CapturedTrace(isTopLevel);
}
}
return this;
};
Promise.prototype._attachExtraTrace =
function Promise$_attachExtraTrace(error) {
if (debugging) {
var promise = this;
var stack = error.stack;
stack = typeof stack === "string" ? stack.split("\n") : [];
CapturedTrace.protectErrorMessageNewlines(stack);
var headerLineCount = 1;
var combinedTraces = 1;
while(promise != null &&
promise._trace != null) {
stack = CapturedTrace.combine(
stack,
promise._trace.stack.split("\n")
);
promise = promise._traceParent;
combinedTraces++;
}
var stackTraceLimit = Error.stackTraceLimit || 10;
var max = (stackTraceLimit + headerLineCount) * combinedTraces;
var len = stack.length;
if (len > max) {
stack.length = max;
}
if (len > 0)
stack[0] = stack[0].split("\u0002\u0000\u0001").join("\n");
if (stack.length <= headerLineCount) {
error.stack = "(No stack trace)";
} else {
error.stack = stack.join("\n");
}
}
};
Promise.prototype._cleanValues = function Promise$_cleanValues() {
if (this._cancellable()) {
this._cancellationParent = void 0;
}
};
Promise.prototype._propagateFrom =
function Promise$_propagateFrom(parent, flags) {
if ((flags & 1) > 0 && parent._cancellable()) {
this._setCancellable();
this._cancellationParent = parent;
}
if ((flags & 4) > 0) {
this._setBoundTo(parent._boundTo);
}
if ((flags & 2) > 0) {
this._setTrace(parent);
}
};
Promise.prototype._fulfill = function Promise$_fulfill(value) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._fulfillUnchecked(value);
};
Promise.prototype._reject =
function Promise$_reject(reason, carriedStackTrace) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._rejectUnchecked(reason, carriedStackTrace);
};
Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) {
var handler = this.isFulfilled()
? this._fulfillmentHandlerAt(index)
: this._rejectionHandlerAt(index);
var value = this._settledValue;
var receiver = this._receiverAt(index);
var promise = this._promiseAt(index);
if (typeof handler === "function") {
this._settlePromiseFromHandler(handler, receiver, value, promise);
} else {
var done = false;
var isFulfilled = this.isFulfilled();
if (receiver !== void 0) {
if (receiver instanceof Promise &&
receiver._isProxied()) {
receiver._unsetProxied();
if (isFulfilled) receiver._fulfillUnchecked(value);
else receiver._rejectUnchecked(value,
this._getCarriedStackTrace());
done = true;
} else if (receiver instanceof PromiseArray) {
if (isFulfilled) receiver._promiseFulfilled(value, promise);
else receiver._promiseRejected(value, promise);
done = true;
}
}
if (!done) {
if (isFulfilled) promise._fulfill(value);
else promise._reject(value, this._getCarriedStackTrace());
}
}
if (index >= 4) {
this._queueGC();
}
};
Promise.prototype._isProxied = function Promise$_isProxied() {
return (this._bitField & 4194304) === 4194304;
};
Promise.prototype._setProxied = function Promise$_setProxied() {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._unsetProxied = function Promise$_unsetProxied() {
this._bitField = this._bitField & (~4194304);
};
Promise.prototype._isGcQueued = function Promise$_isGcQueued() {
return (this._bitField & -1073741824) === -1073741824;
};
Promise.prototype._setGcQueued = function Promise$_setGcQueued() {
this._bitField = this._bitField | -1073741824;
};
Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() {
this._bitField = this._bitField & (~-1073741824);
};
Promise.prototype._queueGC = function Promise$_queueGC() {
if (this._isGcQueued()) return;
this._setGcQueued();
async.invokeLater(this._gc, this, void 0);
};
Promise.prototype._gc = function Promise$gc() {
var len = this._length() * 5 - 5;
for (var i = 0; i < len; i++) {
delete this[i];
}
this._clearFirstHandlerData();
this._setLength(0);
this._unsetGcQueued();
};
Promise.prototype._clearFirstHandlerData =
function Promise$_clearFirstHandlerData() {
this._fulfillmentHandler0 = void 0;
this._rejectionHandler0 = void 0;
this._promise0 = void 0;
this._receiver0 = void 0;
};
Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) {
if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
async.invoke(this._settlePromiseAt, this, index);
};
Promise.prototype._fulfillUnchecked =
function Promise$_fulfillUnchecked(value) {
if (!this.isPending()) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err, void 0);
}
this._cleanValues();
this._setFulfilled();
this._settledValue = value;
var len = this._length();
if (len > 0) {
async.invoke(this._settlePromises, this, len);
}
};
Promise.prototype._rejectUncheckedCheckError =
function Promise$_rejectUncheckedCheckError(reason) {
var trace = canAttach(reason) ? reason : new Error(reason + "");
this._rejectUnchecked(reason, trace === reason ? void 0 : trace);
};
Promise.prototype._rejectUnchecked =
function Promise$_rejectUnchecked(reason, trace) {
if (!this.isPending()) return;
if (reason === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err);
}
this._cleanValues();
this._setRejected();
this._settledValue = reason;
if (this._isFinal()) {
async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace);
return;
}
var len = this._length();
if (trace !== void 0) this._setCarriedStackTrace(trace);
if (len > 0) {
async.invoke(this._rejectPromises, this, null);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._rejectPromises = function Promise$_rejectPromises() {
this._settlePromises();
this._unsetCarriedStackTrace();
};
Promise.prototype._settlePromises = function Promise$_settlePromises() {
var len = this._length();
for (var i = 0; i < len; i++) {
this._settlePromiseAt(i);
}
};
Promise.prototype._ensurePossibleRejectionHandled =
function Promise$_ensurePossibleRejectionHandled() {
this._setRejectionIsUnhandled();
if (CapturedTrace.possiblyUnhandledRejection !== void 0) {
async.invokeLater(this._notifyUnhandledRejection, this, void 0);
}
};
Promise.prototype._notifyUnhandledRejectionIsHandled =
function Promise$_notifyUnhandledRejectionIsHandled() {
if (typeof unhandledRejectionHandled === "function") {
async.invokeLater(unhandledRejectionHandled, void 0, this);
}
};
Promise.prototype._notifyUnhandledRejection =
function Promise$_notifyUnhandledRejection() {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue;
var trace = this._getCarriedStackTrace();
this._setUnhandledRejectionIsNotified();
if (trace !== void 0) {
this._unsetCarriedStackTrace();
reason = trace;
}
if (typeof CapturedTrace.possiblyUnhandledRejection === "function") {
CapturedTrace.possiblyUnhandledRejection(reason, this);
}
}
};
var contextStack = [];
Promise.prototype._peekContext = function Promise$_peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return void 0;
};
Promise.prototype._pushContext = function Promise$_pushContext() {
if (!debugging) return;
contextStack.push(this);
};
Promise.prototype._popContext = function Promise$_popContext() {
if (!debugging) return;
contextStack.pop();
};
Promise.noConflict = function Promise$NoConflict() {
return noConflict(Promise);
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
async._schedule = fn;
};
if (!CapturedTrace.isSupported()) {
Promise.longStackTraces = function(){};
debugging = false;
}
Promise._makeSelfResolutionError = makeSelfResolutionError;
_dereq_("./finally.js")(Promise, NEXT_FILTER, cast);
_dereq_("./direct_resolve.js")(Promise);
_dereq_("./synchronous_inspection.js")(Promise);
_dereq_("./join.js")(Promise, PromiseArray, cast, INTERNAL);
Promise.RangeError = RangeError;
Promise.CancellationError = CancellationError;
Promise.TimeoutError = TimeoutError;
Promise.TypeError = TypeError;
Promise.OperationalError = OperationalError;
Promise.RejectionError = OperationalError;
Promise.AggregateError = errors.AggregateError;
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
Promise.Promise = Promise;
_dereq_('./nodeify.js')(Promise);
Promise.prototype = Promise.prototype;
return Promise;
};
},{"./async.js":1,"./captured_trace.js":3,"./catch_filter.js":4,"./direct_resolve.js":5,"./errors.js":6,"./errors_api_rejection":7,"./finally.js":9,"./join.js":10,"./nodeify.js":11,"./promise_array.js":13,"./promise_resolver.js":14,"./synchronous_inspection.js":17,"./thenables.js":18,"./util.js":19}],13:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise, INTERNAL, cast) {
var canAttach = _dereq_("./errors.js").canAttach;
var util = _dereq_("./util.js");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -1: return void 0;
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
var parent = void 0;
if (values instanceof Promise) {
parent = values;
promise._propagateFrom(parent, 1 | 4);
}
promise._setTrace(parent);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(void 0, -2);
}
PromiseArray.prototype.length = function PromiseArray$length() {
return this._length;
};
PromiseArray.prototype.promise = function PromiseArray$promise() {
return this._promise;
};
PromiseArray.prototype._init =
function PromiseArray$_init(_, resolveValueIfEmpty) {
var values = cast(this._values, void 0);
if (values instanceof Promise) {
this._values = values;
values._setBoundTo(this._promise._boundTo);
if (values.isFulfilled()) {
values = values._settledValue;
if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable");
this.__hardReject__(err);
return;
}
} else if (values.isPending()) {
values._then(
PromiseArray$_init,
this._reject,
void 0,
this,
resolveValueIfEmpty
);
return;
} else {
values._unsetRejectionIsUnhandled();
this._reject(values._settledValue);
return;
}
} else if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable");
this.__hardReject__(err);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
var len = this.getActualLength(values.length);
var newLen = len;
var newValues = this.shouldCopyValues() ? new Array(len) : this._values;
var isDirectScanNeeded = false;
for (var i = 0; i < len; ++i) {
var maybePromise = cast(values[i], void 0);
if (maybePromise instanceof Promise) {
if (maybePromise.isPending()) {
maybePromise._proxyPromiseArray(this, i);
} else {
maybePromise._unsetRejectionIsUnhandled();
isDirectScanNeeded = true;
}
} else {
isDirectScanNeeded = true;
}
newValues[i] = maybePromise;
}
this._values = newValues;
this._length = newLen;
if (isDirectScanNeeded) {
this._scanDirectValues(len);
}
};
PromiseArray.prototype._settlePromiseAt =
function PromiseArray$_settlePromiseAt(index) {
var value = this._values[index];
if (!(value instanceof Promise)) {
this._promiseFulfilled(value, index);
} else if (value.isFulfilled()) {
this._promiseFulfilled(value._settledValue, index);
} else if (value.isRejected()) {
this._promiseRejected(value._settledValue, index);
}
};
PromiseArray.prototype._scanDirectValues =
function PromiseArray$_scanDirectValues(len) {
for (var i = 0; i < len; ++i) {
if (this._isResolved()) {
break;
}
this._settlePromiseAt(i);
}
};
PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() {
return this._values === null;
};
PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype.__hardReject__ =
PromiseArray.prototype._reject = function PromiseArray$_reject(reason) {
this._values = null;
var trace = canAttach(reason) ? reason : new Error(reason + "");
this._promise._attachExtraTrace(trace);
this._promise._reject(reason, trace);
};
PromiseArray.prototype._promiseProgressed =
function PromiseArray$_promiseProgressed(progressValue, index) {
if (this._isResolved()) return;
this._promise._progress({
index: index,
value: progressValue
});
};
PromiseArray.prototype._promiseFulfilled =
function PromiseArray$_promiseFulfilled(value, index) {
if (this._isResolved()) return;
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
PromiseArray.prototype._promiseRejected =
function PromiseArray$_promiseRejected(reason, index) {
if (this._isResolved()) return;
this._totalResolved++;
this._reject(reason);
};
PromiseArray.prototype.shouldCopyValues =
function PromiseArray$_shouldCopyValues() {
return true;
};
PromiseArray.prototype.getActualLength =
function PromiseArray$getActualLength(len) {
return len;
};
return PromiseArray;
};
},{"./errors.js":6,"./util.js":19}],14:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var util = _dereq_("./util.js");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors.js");
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var async = _dereq_("./async.js");
var haveGetters = util.haveGetters;
var es5 = _dereq_("./es5.js");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
} else {
ret = obj;
}
errors.markAsOriginatingFromRejection(ret);
return ret;
}
function nodebackForPromise(promise) {
function PromiseResolver$_callback(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (arguments.length > 2) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
promise._fulfill(args);
} else {
promise._fulfill(value);
}
promise = null;
}
return PromiseResolver$_callback;
}
var PromiseResolver;
if (!haveGetters) {
PromiseResolver = function PromiseResolver(promise) {
this.promise = promise;
this.asCallback = nodebackForPromise(promise);
this.callback = this.asCallback;
};
}
else {
PromiseResolver = function PromiseResolver(promise) {
this.promise = promise;
};
}
if (haveGetters) {
var prop = {
get: function() {
return nodebackForPromise(this.promise);
}
};
es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
es5.defineProperty(PromiseResolver.prototype, "callback", prop);
}
PromiseResolver._nodebackForPromise = nodebackForPromise;
PromiseResolver.prototype.toString = function PromiseResolver$toString() {
return "[object PromiseResolver]";
};
PromiseResolver.prototype.resolve =
PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
var promise = this.promise;
if (promise._tryFollow(value)) {
return;
}
async.invoke(promise._fulfill, promise, value);
};
PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
var promise = this.promise;
errors.markAsOriginatingFromRejection(reason);
var trace = errors.canAttach(reason) ? reason : new Error(reason + "");
promise._attachExtraTrace(trace);
async.invoke(promise._reject, promise, reason);
if (trace !== reason) {
async.invoke(this._setCarriedStackTrace, this, trace);
}
};
PromiseResolver.prototype.progress =
function PromiseResolver$progress(value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
async.invoke(this.promise._progress, this.promise, value);
};
PromiseResolver.prototype.cancel = function PromiseResolver$cancel() {
async.invoke(this.promise.cancel, this.promise, void 0);
};
PromiseResolver.prototype.timeout = function PromiseResolver$timeout() {
this.reject(new TimeoutError("timeout"));
};
PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() {
return this.promise.isResolved();
};
PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() {
return this.promise.toJSON();
};
PromiseResolver.prototype._setCarriedStackTrace =
function PromiseResolver$_setCarriedStackTrace(trace) {
if (this.promise.isRejected()) {
this.promise._setCarriedStackTrace(trace);
}
};
module.exports = PromiseResolver;
},{"./async.js":1,"./errors.js":6,"./es5.js":8,"./util.js":19}],15:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
function arrayCopy(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
this._makeCapacity();
}
Queue.prototype._willBeOverCapacity =
function Queue$_willBeOverCapacity(size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function Queue$_pushOne(arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function Queue$push(fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function Queue$shift() {
var front = this._front,
ret = this[front];
this[front] = void 0;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function Queue$length() {
return this._length;
};
Queue.prototype._makeCapacity = function Queue$_makeCapacity() {
var len = this._capacity;
for (var i = 0; i < len; ++i) {
this[i] = void 0;
}
};
Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 3);
}
};
Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) {
var oldFront = this._front;
var oldCapacity = this._capacity;
var oldQueue = new Array(oldCapacity);
var length = this.length();
arrayCopy(this, 0, oldQueue, 0, oldCapacity);
this._capacity = capacity;
this._makeCapacity();
this._front = 0;
if (oldFront + length <= oldCapacity) {
arrayCopy(oldQueue, oldFront, this, 0, length);
} else { var lengthBeforeWrapping =
length - ((oldFront + length) & (oldCapacity - 1));
arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping);
arrayCopy(oldQueue, 0, this, lengthBeforeWrapping,
length - lengthBeforeWrapping);
}
};
module.exports = Queue;
},{}],16:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var schedule;
var _MutationObserver;
if (typeof process === "object" && typeof process.version === "string") {
schedule = function Promise$_Scheduler(fn) {
process.nextTick(fn);
};
}
else if ((typeof MutationObserver !== "undefined" &&
(_MutationObserver = MutationObserver)) ||
(typeof WebKitMutationObserver !== "undefined" &&
(_MutationObserver = WebKitMutationObserver))) {
schedule = (function() {
var div = document.createElement("div");
var queuedFn = void 0;
var observer = new _MutationObserver(
function Promise$_Scheduler() {
var fn = queuedFn;
queuedFn = void 0;
fn();
}
);
observer.observe(div, {
attributes: true
});
return function Promise$_Scheduler(fn) {
queuedFn = fn;
div.classList.toggle("foo");
};
})();
}
else if (typeof setTimeout !== "undefined") {
schedule = function Promise$_Scheduler(fn) {
setTimeout(fn, 0);
};
}
else throw new Error("no async scheduler available");
module.exports = schedule;
},{}],17:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== void 0) {
this._bitField = promise._bitField;
this._settledValue = promise.isResolved()
? promise._settledValue
: void 0;
}
else {
this._bitField = 0;
this._settledValue = void 0;
}
}
PromiseInspection.prototype.isFulfilled =
Promise.prototype.isFulfilled = function Promise$isFulfilled() {
return (this._bitField & 268435456) > 0;
};
PromiseInspection.prototype.isRejected =
Promise.prototype.isRejected = function Promise$isRejected() {
return (this._bitField & 134217728) > 0;
};
PromiseInspection.prototype.isPending =
Promise.prototype.isPending = function Promise$isPending() {
return (this._bitField & 402653184) === 0;
};
PromiseInspection.prototype.value =
Promise.prototype.value = function Promise$value() {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise");
}
return this._settledValue;
};
PromiseInspection.prototype.error =
PromiseInspection.prototype.reason =
Promise.prototype.reason = function Promise$reason() {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise");
}
return this._settledValue;
};
PromiseInspection.prototype.isResolved =
Promise.prototype.isResolved = function Promise$isResolved() {
return (this._bitField & 402653184) > 0;
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],18:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var canAttach = _dereq_("./errors.js").canAttach;
var errorObj = util.errorObj;
var isObject = util.isObject;
function getThen(obj) {
try {
return obj.then;
}
catch(e) {
errorObj.e = e;
return errorObj;
}
}
function Promise$_Cast(obj, originalPromise) {
if (isObject(obj)) {
if (obj instanceof Promise) {
return obj;
}
else if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
obj._then(
ret._fulfillUnchecked,
ret._rejectUncheckedCheckError,
ret._progressUnchecked,
ret,
null
);
ret._setFollowing();
return ret;
}
var then = getThen(obj);
if (then === errorObj) {
if (originalPromise !== void 0 && canAttach(then.e)) {
originalPromise._attachExtraTrace(then.e);
}
return Promise.reject(then.e);
} else if (typeof then === "function") {
return Promise$_doThenable(obj, then, originalPromise);
}
}
return obj;
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function Promise$_doThenable(x, then, originalPromise) {
var resolver = Promise.defer();
var called = false;
try {
then.call(
x,
Promise$_resolveFromThenable,
Promise$_rejectFromThenable,
Promise$_progressFromThenable
);
} catch(e) {
if (!called) {
called = true;
var trace = canAttach(e) ? e : new Error(e + "");
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(trace);
}
resolver.promise._reject(e, trace);
}
}
return resolver.promise;
function Promise$_resolveFromThenable(y) {
if (called) return;
called = true;
if (x === y) {
var e = Promise._makeSelfResolutionError();
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(e);
}
resolver.promise._reject(e, void 0);
return;
}
resolver.resolve(y);
}
function Promise$_rejectFromThenable(r) {
if (called) return;
called = true;
var trace = canAttach(r) ? r : new Error(r + "");
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(trace);
}
resolver.promise._reject(r, trace);
}
function Promise$_progressFromThenable(v) {
if (called) return;
var promise = resolver.promise;
if (typeof promise._progress === "function") {
promise._progress(v);
}
}
}
return Promise$_Cast;
};
},{"./errors.js":6,"./util.js":19}],19:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
var es5 = _dereq_("./es5.js");
var haveGetters = (function(){
try {
var o = {};
es5.defineProperty(o, "f", {
get: function () {
return 3;
}
});
return o.f === 3;
}
catch (e) {
return false;
}
})();
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
function tryCatch1(fn, receiver, arg) {
try { return fn.call(receiver, arg); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch2(fn, receiver, arg, arg2) {
try { return fn.call(receiver, arg, arg2); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch3(fn, receiver, arg, arg2, arg3) {
try { return fn.call(receiver, arg, arg2, arg3); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch4(fn, receiver, arg, arg2, arg3, arg4) {
try { return fn.call(receiver, arg, arg2, arg3, arg4); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatchApply(fn, args, receiver) {
try { return fn.apply(receiver, args); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function asString(val) {
return typeof val === "string" ? val : ("" + val);
}
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return !isPrimitive(value);
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(asString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : void 0;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
var wrapsPrimitiveReceiver = (function() {
return this !== "string";
}).call("string");
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
if (es5.isES5) {
return function(obj, opts) {
var ret = [];
var visitedKeys = Object.create(null);
var getKeys = Object(opts).includeHidden
? Object.getOwnPropertyNames
: Object.keys;
while (obj != null) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
return function(obj) {
var ret = [];
/*jshint forin:false */
for (var key in obj) {
ret.push(key);
}
return ret;
};
}
})();
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.keys(fn.prototype);
return keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027*/
function f() {}
f.prototype = obj;
return f;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
haveGetters: haveGetters,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch1: tryCatch1,
tryCatch2: tryCatch2,
tryCatch3: tryCatch3,
tryCatch4: tryCatch4,
tryCatchApply: tryCatchApply,
inherits: inherits,
withAppended: withAppended,
asString: asString,
maybeWrapAsError: maybeWrapAsError,
wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
toFastProperties: toFastProperties,
filledRange: filledRange
};
module.exports = ret;
},{"./es5.js":8}]},{},[2])
(2)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
/** FILE: src/remotestorage.js **/
(function (global) {
var hasLocalStorage;
// wrapper to implement defer() functionality
Promise.defer = function () {
var resolve, reject;
var promise = new Promise(function() {
resolve = arguments[0];
reject = arguments[1];
});
return {
resolve: resolve,
reject: reject,
promise: promise
};
};
function logError(error) {
if (typeof(error) === 'string') {
console.error(error);
} else {
console.error(error.message, error.stack);
}
}
function emitUnauthorized(r) {
if (r.statusCode === 403 || r.statusCode === 401) {
this._emit('error', new RemoteStorage.Unauthorized());
}
return Promise.resolve(r);
}
function shareFirst(path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
var self = this;
if (this.local) {
if (maxAge === undefined) {
if ((typeof this.remote === 'object') &&
this.remote.connected && this.remote.online) {
maxAge = 2*this.getSyncInterval();
} else {
RemoteStorage.log('Not setting default maxAge, because remote is offline or not connected');
maxAge = false;
}
}
var maxAgeInvalid = function (maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
};
if (maxAgeInvalid(maxAge)) {
return Promise.reject('Argument \'maxAge\' must be false or a number');
}
return this.local.get(path, maxAge, this.sync.queueGetRequest.bind(this.sync));
} else {
return this.remote.get(path);
}
},
put: function (path, body, contentType) {
if (shareFirst.bind(this)(path)) {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
else if (this.local) {
return this.local.put(path, body, contentType);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
},
'delete': function (path) {
if (this.local) {
return this.local.delete(path);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path));
}
},
_wrapBusyDone: function (result) {
var self = this;
this._emit('wire-busy');
return result.then(function (r) {
self._emit('wire-done', { success: true });
return Promise.resolve(r);
}, function (err) {
self._emit('wire-done', { success: false });
return Promise.reject(err);
});
}
};
/**
* Class: RemoteStorage
*
* TODO needs proper introduction and links to relevant classes etc
*
* Constructor for global remoteStorage object.
*
* This class primarily contains feature detection code and a global convenience API.
*
* Depending on which features are built in, it contains different attributes and
* functions. See the individual features for more information.
*
* (start code)
* var remoteStorage = new RemoteStorage({
* logging: true, // defaults to false
* cordovaRedirectUri: 'https://app.mygreatapp.com' // defaults to undefined
* });
* (end code)
*/
var RemoteStorage = function (cfg) {
/**
* Event: ready
*
* Fired when ready
**/
/**
* Event: not-connected
*
* Fired when ready, but no storage connected ("anonymous mode")
**/
/**
* Event: connected
*
* Fired when a remote storage has been connected
**/
/**
* Event: disconnected
*
* Fired after disconnect
**/
/**
* Event: error
*
* Fired when an error occurs
*
* Arguments:
* the error
**/
/**
* Event: features-loaded
*
* Fired when all features are loaded
**/
/**
* Event: connecting
*
* Fired before webfinger lookup
**/
/**
* Event: authing
*
* Fired before redirecting to the authing server
**/
/**
* Event: wire-busy
*
* Fired when a wire request starts
**/
/**
* Event: wire-done
*
* Fired when a wire request completes
**/
/**
* Event: network-offline
*
* Fired once when a wire request fails for the first time, and
* `remote.online` is set to false
**/
/**
* Event: network-online
*
* Fired once when a wire request succeeds for the first time after a
* failed one, and `remote.online` is set back to true
**/
// Initial configuration property settings.
if (typeof cfg === 'object') {
RemoteStorage.config.logging = !!cfg.logging;
RemoteStorage.config.cordovaRedirectUri = cfg.cordovaRedirectUri;
}
RemoteStorage.eventHandling(
this, 'ready', 'connected', 'disconnected', 'not-connected', 'conflict',
'error', 'features-loaded', 'connecting', 'authing',
'sync-interval-change', 'wire-busy', 'wire-done',
'network-offline', 'network-online'
);
// pending get/put/delete calls.
this._pending = [];
this._setGPD({
get: this._pendingGPD('get'),
put: this._pendingGPD('put'),
delete: this._pendingGPD('delete')
});
this._cleanups = [];
this._pathHandlers = { change: {} };
this.apiKeys = {};
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (hasLocalStorage) {
try {
this.apiKeys = JSON.parse(localStorage.getItem('remotestorage:api-keys')) || {};
} catch(exc) {
// ignored
}
this.setBackend(localStorage.getItem('remotestorage:backend') || 'remotestorage');
}
var origOn = this.on;
this.on = function (eventName, handler) {
if (eventName === 'ready' && this.remote.connected && this._allLoaded) {
setTimeout(handler, 0);
} else if (eventName === 'features-loaded' && this._allLoaded) {
setTimeout(handler, 0);
}
return origOn.call(this, eventName, handler);
};
this._init();
this.fireInitial = function () {
if (this.local) {
setTimeout(this.local.fireInitial.bind(this.local), 0);
}
}.bind(this);
this.on('ready', this.fireInitial.bind(this));
};
RemoteStorage.SyncedGetPutDelete = SyncedGetPutDelete;
RemoteStorage.DiscoveryError = function (message) {
Error.apply(this, arguments);
this.message = message;
};
RemoteStorage.DiscoveryError.prototype = Object.create(Error.prototype);
RemoteStorage.Unauthorized = function () { Error.apply(this, arguments); };
RemoteStorage.Unauthorized.prototype = Object.create(Error.prototype);
/**
* Method: RemoteStorage.log
*
* Log using console.log, when remoteStorage logging is enabled.
*
* You can enable logging with <enableLog>.
*
* (In node.js you can also enable logging during remoteStorage object
* creation. See: <RemoteStorage>).
*/
RemoteStorage.log = function () {
if (RemoteStorage.config.logging) {
console.log.apply(console, arguments);
}
};
RemoteStorage.config = {
logging: false,
changeEvents: {
local: true,
window: false,
remote: true,
conflict: true
},
discoveryTimeout: 10000,
cordovaRedirectUri: undefined
};
RemoteStorage.prototype = {
/**
* Method: displayWidget
*
* Displays the widget at the top right of the page. Make sure to call this function
* once on every pageload (after the html 'body' tag), unless you use a custom widget.
*
* Parameters:
*
* domID: identifier of the DOM element which should embody the widget (optional)
*/
// (see src/widget.js for implementation)
/**
* Property: remote
*
* Properties:
*
* connected - Boolean, whether or not a remote store is connected
* online - Boolean, whether last sync action was successful or not
* userAddress - String, the user address of the connected user
* properties - String, the properties of the WebFinger link
*/
/**
* Method: scope
*
* Returns a BaseClient with a certain scope (base path). Please use this method
* only for debugging, and always use defineModule instead, to get access to a
* BaseClient from a module in an app.
*
* Parameters:
*
* scope - A string, with a leading and a trailing slash, specifying the
* base path of the BaseClient that will be returned.
*
* Code example:
*
* (start code)
* remoteStorage.scope('/pictures/').getListing('');
* remoteStorage.scope('/public/pictures/').getListing('');
*/
/**
* Method: startSync
*
* Start synchronization with remote storage, downloading and uploading any
* changes within the cached paths.
*
* Please consider: local changes will attempt sync immediately, and remote
* changes should also be synced timely when using library defaults. So
* this is mostly useful for letting users sync manually, when pressing a
* sync button for example. This might feel safer to them sometimes, esp.
* when shifting between offline and online a lot.
*/
// (see src/sync.js for implementation)
/**
* Method: connect
*
* Connect to a remoteStorage server.
*
* Parameters:
* userAddress - The user address (user@host) to connect to.
* token - (optional) A bearer token acquired beforehand
*
* Discovers the WebFinger profile of the given user address and initiates
* the OAuth dance.
*
* This method must be called *after* all required access has been claimed.
* When using the connect widget, it will call this method itself.
*
* Special cases:
*
* 1. If a bearer token is supplied as second argument, the OAuth dance
* will be skipped and the supplied token be used instead. This is
* useful outside of browser environments, where the token has been
* acquired in a different way.
*
* 2. If the Webfinger profile for the given user address doesn't contain
* an auth URL, the library will assume that client and server have
* established authorization among themselves, which will omit bearer
* tokens in all requests later on. This is useful for example when using
* Kerberos and similar protocols.
*/
connect: function (userAddress, token) {
this.setBackend('remotestorage');
if (userAddress.indexOf('@') < 0) {
this._emit('error', new RemoteStorage.DiscoveryError("User address doesn't contain an @."));
return;
}
if (global.cordova) {
if (typeof RemoteStorage.config.cordovaRedirectUri !== 'string') {
this._emit('error', new RemoteStorage.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));
return;
}
if (!global.cordova.InAppBrowser) {
this._emit('error', new RemoteStorage.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"));
return;
}
}
this.remote.configure({
userAddress: userAddress
});
this._emit('connecting');
var discoveryTimeout = setTimeout(function () {
this._emit('error', new RemoteStorage.DiscoveryError("No storage information found for this user address."));
}.bind(this), RemoteStorage.config.discoveryTimeout);
RemoteStorage.Discover(userAddress).then(function (info) {
// Info contains fields: href, storageApi, authURL (optional), properties
clearTimeout(discoveryTimeout);
this._emit('authing');
info.userAddress = userAddress;
this.remote.configure(info);
if (! this.remote.connected) {
if (info.authURL) {
if (typeof token === 'undefined') {
// Normal authorization step; the default way to connect
this.authorize(info.authURL, RemoteStorage.config.cordovaRedirectUri);
} else if (typeof token === 'string') {
// Token supplied directly by app/developer/user
RemoteStorage.log('Skipping authorization sequence and connecting with known token');
this.remote.configure({ token: token });
} else {
throw new Error("Supplied bearer token must be a string");
}
} else {
// In lieu of an excplicit authURL, assume that the browser and
// server handle any authorization needs; for instance, TLS may
// trigger the browser to use a client certificate, or a 401 Not
// Authorized response may make the browser send a Kerberos ticket
// using the SPNEGO method.
this.impliedauth();
}
}
}.bind(this), function(err) {
clearTimeout(discoveryTimeout);
this._emit('error', new RemoteStorage.DiscoveryError("No storage information found for this user address."));
}.bind(this));
},
/**
* Method: disconnect
*
* "Disconnect" from remotestorage server to terminate current session.
* This method clears all stored settings and deletes the entire local
* cache.
*/
disconnect: function () {
if (this.remote) {
this.remote.configure({
userAddress: null,
href: null,
storageApi: null,
token: null,
properties: null
});
}
this._setGPD({
get: this._pendingGPD('get'),
put: this._pendingGPD('put'),
delete: this._pendingGPD('delete')
});
var n = this._cleanups.length, i = 0;
var oneDone = function () {
i++;
if (i >= n) {
this._init();
RemoteStorage.log('Done cleaning up, emitting disconnected and disconnect events');
this._emit('disconnected');
}
}.bind(this);
if (n > 0) {
this._cleanups.forEach(function (cleanup) {
var cleanupResult = cleanup(this);
if (typeof(cleanupResult) === 'object' && typeof(cleanupResult.then) === 'function') {
cleanupResult.then(oneDone);
} else {
oneDone();
}
}.bind(this));
} else {
oneDone();
}
},
setBackend: function (what) {
this.backend = what;
if (hasLocalStorage) {
if (what) {
localStorage.setItem('remotestorage:backend', what);
} else {
localStorage.removeItem('remotestorage:backend');
}
}
},
/**
* Method: onChange
*
* Add a "change" event handler to the given path. Whenever a "change"
* happens (as determined by the backend, such as e.g.
* <RemoteStorage.IndexedDB>) and the affected path is equal to or below
* the given 'path', the given handler is called.
*
* You should usually not use this method directly, but instead use the
* "change" events provided by <RemoteStorage.BaseClient>.
*
* Parameters:
* path - Absolute path to attach handler to.
* handler - Handler function.
*/
onChange: function (path, handler) {
if (! this._pathHandlers.change[path]) {
this._pathHandlers.change[path] = [];
}
this._pathHandlers.change[path].push(handler);
},
/**
* Method: enableLog
*
* Enable remoteStorage logging.
*/
enableLog: function () {
RemoteStorage.config.logging = true;
},
/**
* Method: disableLog
*
* Disable remoteStorage logging
*/
disableLog: function () {
RemoteStorage.config.logging = false;
},
/**
* Method: log
*
* The same as <RemoteStorage.log>.
*/
log: function () {
RemoteStorage.log.apply(RemoteStorage, arguments);
},
/**
* Method: setApiKeys (experimental)
*
* Set API keys for (currently) GoogleDrive and/or Dropbox backend support.
* See also the 'backends' example in the starter-kit. Note that support for
* both these backends is still experimental.
*
* Parameters:
* type - string, either 'googledrive' or 'dropbox'
* keys - object, with one string field; 'clientId' for GoogleDrive, or
* 'appKey' for Dropbox.
*
*/
setApiKeys: function (type, keys) {
if (keys) {
this.apiKeys[type] = keys;
if (type === 'dropbox' && (typeof this.dropbox === 'undefined' ||
this.dropbox.clientId !== keys.appKey)) {
RemoteStorage.Dropbox._rs_init(this);
} else if (type === 'googledrive' && (typeof this.googledrive === 'undefined' ||
this.googledrive.clientId !== keys.clientId)) {
RemoteStorage.GoogleDrive._rs_init(this);
}
} else {
delete this.apiKeys[type];
}
if (hasLocalStorage) {
localStorage.setItem('remotestorage:api-keys', JSON.stringify(this.apiKeys));
}
},
/**
* Method: setCordovaRedirectUri
*
* Set redirect URI to be used for the OAuth redirect within the
* in-app-browser window in Cordova apps.
*
* Parameters:
* uri - string, valid HTTP(S) URI
*/
setCordovaRedirectUri: function (uri) {
if (typeof uri !== 'string' || !uri.match(/http(s)?\:\/\//)) {
throw new Error("Cordova redirect URI must be a URI string");
}
RemoteStorage.config.cordovaRedirectUri = uri;
},
/**
** INITIALIZATION
**/
_init: function () {
var self = this,
readyFired = false;
function fireReady() {
try {
if (!readyFired) {
self._emit('ready');
readyFired = true;
}
} catch(e) {
console.error("'ready' failed: ", e, e.stack);
self._emit('error', e);
}
}
this._loadFeatures(function (features) {
this.log('[RemoteStorage] All features loaded');
this.local = features.local && new features.local();
// this.remote set by WireClient._rs_init as lazy property on
// RS.prototype
if (this.local && this.remote) {
this._setGPD(SyncedGetPutDelete, this);
this._bindChange(this.local);
} else if (this.remote) {
this._setGPD(this.remote, this.remote);
}
if (this.remote) {
this.remote.on('connected', function (){
fireReady();
self._emit('connected');
});
this.remote.on('not-connected', function (){
fireReady();
self._emit('not-connected');
});
if (this.remote.connected) {
fireReady();
self._emit('connected');
}
if (!this.hasFeature('Authorize')) {
this.remote.stopWaitingForToken();
}
}
this._collectCleanupFunctions();
try {
this._allLoaded = true;
this._emit('features-loaded');
} catch(exc) {
logError(exc);
this._emit('error', exc);
}
this._processPending();
}.bind(this));
},
_collectCleanupFunctions: function () {
this._cleanups = [];
for (var i=0; i < this.features.length; i++) {
var cleanup = this.features[i].cleanup;
if (typeof(cleanup) === 'function') {
this._cleanups.push(cleanup);
}
}
},
/**
** FEATURE DETECTION
**/
_loadFeatures: function (callback) {
var featureList = [
'WireClient',
'I18n',
'Dropbox',
'GoogleDrive',
'Access',
'Caching',
'Discover',
'Authorize',
'Widget',
'IndexedDB',
'LocalStorage',
'InMemoryStorage',
'Sync',
'BaseClient',
'Env'
];
var features = [];
var featuresDone = 0;
var self = this;
function featureDone() {
featuresDone++;
if (featuresDone === featureList.length) {
setTimeout(function () {
features.caching = !!RemoteStorage.Caching;
features.sync = !!RemoteStorage.Sync;
[
'IndexedDB',
'LocalStorage',
'InMemoryStorage'
].some(function (cachingLayer) {
if (features.some(function (feature) { return feature.name === cachingLayer; })) {
features.local = RemoteStorage[cachingLayer];
return true;
}
});
self.features = features;
callback(features);
}, 0);
}
}
function featureInitialized(name) {
self.log("[RemoteStorage] [FEATURE "+name+"] initialized.");
features.push({
name : name,
init : RemoteStorage[name]._rs_init,
supported : true,
cleanup : RemoteStorage[name]._rs_cleanup
});
featureDone();
}
function featureFailed(name, err) {
self.log("[RemoteStorage] [FEATURE "+name+"] initialization failed ( "+err+")");
featureDone();
}
function featureSupported(name, success) {
self.log("[RemoteStorage] [FEATURE "+name+"]" + success ? "":" not"+" supported");
if (!success) {
featureDone();
}
}
function initFeature(name) {
var initResult;
try {
initResult = RemoteStorage[name]._rs_init(self);
} catch(e) {
featureFailed(name, e);
return;
}
if (typeof(initResult) === 'object' && typeof(initResult.then) === 'function') {
initResult.then(
function (){ featureInitialized(name); },
function (err){ featureFailed(name, err); }
);
} else {
featureInitialized(name);
}
}
featureList.forEach(function (featureName) {
self.log("[RemoteStorage] [FEATURE " + featureName + "] initializing...");
var impl = RemoteStorage[featureName];
var supported;
if (impl) {
supported = !impl._rs_supported || impl._rs_supported();
if (typeof supported === 'object') {
supported.then(
function (){
featureSupported(featureName, true);
initFeature(featureName);
},
function (){
featureSupported(featureName, false);
}
);
} else if (typeof supported === 'boolean') {
featureSupported(featureName, supported);
if (supported) {
initFeature(featureName);
}
}
} else {
featureSupported(featureName, false);
}
});
},
/**
* Method: hasFeature
*
* Checks whether a feature is enabled or not within remoteStorage.
* Returns a boolean.
*
* Parameters:
* name - Capitalized name of the feature. e.g. Authorize, or IndexedDB
*
* Example:
* (start code)
* if (remoteStorage.hasFeature('LocalStorage')) {
* console.log('LocalStorage is enabled!');
* }
* (end code)
*
*/
hasFeature: function (feature) {
for (var i = this.features.length - 1; i >= 0; i--) {
if (this.features[i].name === feature) {
return this.features[i].supported;
}
}
return false;
},
/**
** GET/PUT/DELETE INTERFACE HELPERS
**/
_setGPD: function (impl, context) {
function wrap(func) {
return function () {
return func.apply(context, arguments)
.then(emitUnauthorized.bind(this));
};
}
this.get = wrap(impl.get);
this.put = wrap(impl.put);
this.delete = wrap(impl.delete);
},
_pendingGPD: function (methodName) {
return function () {
var pending = Promise.defer();
this._pending.push({
method: methodName,
args: Array.prototype.slice.call(arguments),
promise: pending
});
return pending.promise;
}.bind(this);
},
_processPending: function () {
this._pending.forEach(function (pending) {
try {
this[pending.method].apply(this, pending.args).then(pending.promise.resolve, pending.promise.reject);
} catch(e) {
pending.promise.reject(e);
}
}.bind(this));
this._pending = [];
},
/**
** CHANGE EVENT HANDLING
**/
_bindChange: function (object) {
object.on('change', this._dispatchEvent.bind(this, 'change'));
},
_dispatchEvent: function (eventName, event) {
var self = this;
Object.keys(this._pathHandlers[eventName]).forEach(function (path) {
var pl = path.length;
if (event.path.substr(0, pl) === path) {
self._pathHandlers[eventName][path].forEach(function (handler) {
var ev = {};
for (var key in event) { ev[key] = event[key]; }
ev.relativePath = event.path.replace(new RegExp('^' + path), '');
try {
handler(ev);
} catch(e) {
console.error("'change' handler failed: ", e, e.stack);
self._emit('error', e);
}
});
}
});
}
};
/**
* Property: connected
*
* Boolean property indicating if remoteStorage is currently connected.
*/
Object.defineProperty(RemoteStorage.prototype, 'connected', {
get: function () {
return this.remote.connected;
}
});
/**
* Property: access
*
* Tracking claimed access scopes. A <RemoteStorage.Access> instance.
*
*
* Property: caching
*
* Caching settings. A <RemoteStorage.Caching> instance.
*
* Not available in no-cache builds.
*
*
* Property: remote
*
* Access to the remote backend used. Usually a <RemoteStorage.WireClient>.
*
*
* Property: local
*
* Access to the local caching backend used. Usually either a
* <RemoteStorage.IndexedDB> or <RemoteStorage.LocalStorage> instance.
*
* Not available in no-cache builds.
*/
global.RemoteStorage = RemoteStorage;
if ((typeof module === 'object') && (typeof module.exports !== 'undefined')){
module.exports = RemoteStorage;
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/util.js **/
/**
* Class: RemoteStorage.Util
*
* Provides reusable utility functions at RemoteStorage.util
*
*/
(function (global) {
/**
* Function: fixArrayBuffers
*
* Takes an object and its copy as produced by the _deepClone function
* below, and finds and fixes any ArrayBuffers that were cast to `{}` instead
* of being cloned to new ArrayBuffers with the same content.
*
* It recurses into sub-objects, but skips arrays if they occur.
*/
function fixArrayBuffers(srcObj, dstObj) {
var field, srcArr, dstArr;
if (typeof(srcObj) !== 'object' || Array.isArray(srcObj) || srcObj === null) {
return;
}
for (field in srcObj) {
if (typeof(srcObj[field]) === 'object' && srcObj[field] !== null) {
if (srcObj[field].toString() === '[object ArrayBuffer]') {
dstObj[field] = new ArrayBuffer(srcObj[field].byteLength);
srcArr = new Int8Array(srcObj[field]);
dstArr = new Int8Array(dstObj[field]);
dstArr.set(srcArr);
} else {
fixArrayBuffers(srcObj[field], dstObj[field]);
}
}
}
}
RemoteStorage.util = {
getEventEmitter: function () {
var object = {};
var args = Array.prototype.slice.call(arguments);
args.unshift(object);
RemoteStorage.eventHandling.apply(RemoteStorage, args);
object.emit = object._emit;
return object;
},
extend: function (target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
for (var key in source) {
target[key] = source[key];
}
});
return target;
},
asyncEach: function (array, callback) {
return this.asyncMap(array, callback).
then(function () { return array; });
},
asyncMap: function (array, callback) {
var pending = Promise.defer();
var n = array.length, i = 0;
var results = [], errors = [];
function oneDone() {
i++;
if (i === n) {
pending.resolve(results, errors);
}
}
array.forEach(function (item, index) {
var result;
try {
result = callback(item);
} catch(exc) {
oneDone();
errors[index] = exc;
}
if (typeof(result) === 'object' && typeof(result.then) === 'function') {
result.then(function (res) { results[index] = res; oneDone(); },
function (error) { errors[index] = error; oneDone(); });
} else {
oneDone();
results[index] = result;
}
});
return pending.promise;
},
containingFolder: function (path) {
if (path === '') {
return '/';
}
if (! path) {
throw "Path not given!";
}
return path.replace(/\/+/g, '/').replace(/[^\/]+\/?$/, '');
},
isFolder: function (path) {
return path.substr(-1) === '/';
},
isDocument: function (path) {
return !RemoteStorage.util.isFolder(path);
},
baseName: function (path) {
var parts = path.split('/');
if (this.isFolder(path)) {
return parts[parts.length-2]+'/';
} else {
return parts[parts.length-1];
}
},
cleanPath: function (path) {
return path.replace(/\/+/g, '/')
.split('/').map(encodeURIComponent).join('/')
.replace(/'/g, '%27');
},
bindAll: function (object) {
for (var key in this) {
if (typeof(object[key]) === 'function') {
object[key] = object[key].bind(object);
}
}
},
equal: function (a, b, seen) {
var key;
seen = seen || [];
if (typeof(a) !== typeof(b)) {
return false;
}
if (typeof(a) === 'number' || typeof(a) === 'boolean' || typeof(a) === 'string') {
return a === b;
}
if (typeof(a) === 'function') {
return a.toString() === b.toString();
}
if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {
// Without the following conversion the browsers wouldn't be able to
// tell the ArrayBuffer instances apart.
a = new Uint8Array(a);
b = new Uint8Array(b);
}
// If this point has been reached, a and b are either arrays or objects.
if (a instanceof Array) {
if (a.length !== b.length) {
return false;
}
for (var i = 0, c = a.length; i < c; i++) {
if (!RemoteStorage.util.equal(a[i], b[i], seen)) {
return false;
}
}
} else {
// Check that keys from a exist in b
for (key in a) {
if (a.hasOwnProperty(key) && !(key in b)) {
return false;
}
}
// Check that keys from b exist in a, and compare the values
for (key in b) {
if (!b.hasOwnProperty(key)) {
continue;
}
if (!(key in a)) {
return false;
}
var seenArg;
if (typeof(b[key]) === 'object') {
if (seen.indexOf(b[key]) >= 0) {
// Circular reference, don't attempt to compare this object.
// If nothing else returns false, the objects match.
continue;
}
seenArg = seen.slice();
seenArg.push(b[key]);
}
if (!RemoteStorage.util.equal(a[key], b[key], seenArg)) {
return false;
}
}
}
return true;
},
equalObj: function (obj1, obj2) {
console.warn('DEPRECATION WARNING: RemoteStorage.util.equalObj has been replaced by RemoteStorage.util.equal.');
return RemoteStorage.util.equal(obj1, obj2);
},
deepClone: function (obj) {
var clone;
if (obj === undefined) {
return undefined;
} else {
clone = JSON.parse(JSON.stringify(obj));
fixArrayBuffers(obj, clone);
return clone;
}
},
pathsFromRoot: function (path) {
var paths = [path];
var parts = path.replace(/\/$/, '').split('/');
while (parts.length > 1) {
parts.pop();
paths.push(parts.join('/')+'/');
}
return paths;
},
/* jshint ignore:start */
md5sum: function(str) {
//
// http://www.myersdaily.org/joseph/javascript/md5.js
//
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
function md5blk(s) {
var md5blks = [], i;
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i) + (s.charCodeAt(i+1) << 8) + (s.charCodeAt(i+2) << 16) + (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
};
if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
return md5(str);
},
/* jshint ignore:end */
localStorageAvailable: function() {
if (!('localStorage' in global)) { return false }
try {
global.localStorage.setItem('rs-check', 1);
global.localStorage.removeItem('rs-check');
return true;
} catch(error) {
return false;
}
}
};
if (!RemoteStorage.prototype.util) {
Object.defineProperty(RemoteStorage.prototype, 'util', {
get: function () {
console.log('DEPRECATION WARNING: remoteStorage.util was moved to RemoteStorage.util');
return RemoteStorage.util;
}
});
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/eventhandling.js **/
(function (global) {
/**
* Interface: eventhandling
*/
var methods = {
/**
* Method: addEventListener
*
* Install an event handler for the given event name
*/
addEventListener: function (eventName, handler) {
if (typeof(eventName) !== 'string') {
throw new Error('Argument eventName should be a string');
}
if (typeof(handler) !== 'function') {
throw new Error('Argument handler should be a function');
}
RemoteStorage.log('[Eventhandling] Adding event listener', eventName, handler);
this._validateEvent(eventName);
this._handlers[eventName].push(handler);
},
/**
* Method: removeEventListener
*
* Remove a previously installed event handler
*/
removeEventListener: function (eventName, handler) {
this._validateEvent(eventName);
var hl = this._handlers[eventName].length;
for (var i=0;i<hl;i++) {
if (this._handlers[eventName][i] === handler) {
this._handlers[eventName].splice(i, 1);
return;
}
}
},
_emit: function (eventName) {
this._validateEvent(eventName);
var args = Array.prototype.slice.call(arguments, 1);
this._handlers[eventName].slice().forEach(function (handler) {
handler.apply(this, args);
});
},
_validateEvent: function (eventName) {
if (! (eventName in this._handlers)) {
throw new Error("Unknown event: " + eventName);
}
},
_delegateEvent: function (eventName, target) {
target.on(eventName, function (event) {
this._emit(eventName, event);
}.bind(this));
},
_addEvent: function (eventName) {
this._handlers[eventName] = [];
}
};
/**
* Method: eventhandling.on
*
* Alias for <addEventListener>
**/
methods.on = methods.addEventListener;
/**
* Function: eventHandling
*
* Mixes event handling functionality into an object.
*
* The first parameter is always the object to be extended.
* All remaining parameter are expected to be strings, interpreted as valid event
* names.
*
* Example:
* (start code)
* var MyConstructor = function () {
* eventHandling(this, 'connected', 'disconnected');
*
* this._emit('connected');
* this._emit('disconnected');
* // This would throw an exception:
* // this._emit('something-else');
* };
*
* var myObject = new MyConstructor();
* myObject.on('connected', function () { console.log('connected'); });
* myObject.on('disconnected', function () { console.log('disconnected'); });
* // This would throw an exception as well:
* // myObject.on('something-else', function () {});
* (end code)
*/
RemoteStorage.eventHandling = function (object) {
var eventNames = Array.prototype.slice.call(arguments, 1);
for (var key in methods) {
object[key] = methods[key];
}
object._handlers = {};
eventNames.forEach(function (eventName) {
object._addEvent(eventName);
});
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/wireclient.js **/
(function (global) {
var RS = RemoteStorage;
/**
* Class: RemoteStorage.WireClient
*
* WireClient Interface
* --------------------
*
* This file exposes a get/put/delete interface on top of XMLHttpRequest.
* It requires to be configured with parameters about the remotestorage server to
* connect to.
* Each instance of WireClient is always associated with a single remotestorage
* server and access token.
*
* Usually the WireClient instance can be accessed via `remoteStorage.remote`.
*
* This is the get/put/delete interface:
*
* - #get() takes a path and optionally a ifNoneMatch option carrying a version
* string to check. It returns a promise that will be fulfilled with the HTTP
* response status, the response body, the MIME type as returned in the
* 'Content-Type' header and the current revision, as returned in the 'ETag'
* header.
* - #put() takes a path, the request body and a content type string. It also
* accepts the ifMatch and ifNoneMatch options, that map to the If-Match and
* If-None-Match headers respectively. See the remotestorage-01 specification
* for details on handling these headers. It returns a promise, fulfilled with
* the same values as the one for #get().
* - #delete() takes a path and the ifMatch option as well. It returns a promise
* fulfilled with the same values as the one for #get().
*
* In addition to this, the WireClient has some compatibility features to work with
* remotestorage 2012.04 compatible storages. For example it will cache revisions
* from folder listings in-memory and return them accordingly as the "revision"
* parameter in response to #get() requests. Similarly it will return 404 when it
* receives an empty folder listing, to mimic remotestorage-01 behavior. Note
* that it is not always possible to know the revision beforehand, hence it may
* be undefined at times (especially for caching-roots).
*/
var hasLocalStorage;
var SETTINGS_KEY = 'remotestorage:wireclient';
var API_2012 = 1, API_00 = 2, API_01 = 3, API_02 = 4, API_HEAD = 5;
var STORAGE_APIS = {
'draft-dejong-remotestorage-00': API_00,
'draft-dejong-remotestorage-01': API_01,
'draft-dejong-remotestorage-02': API_02,
'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012
};
var isArrayBufferView;
if (typeof(ArrayBufferView) === 'function') {
isArrayBufferView = function (object) { return object && (object instanceof ArrayBufferView); };
} else {
var arrayBufferViews = [
Int8Array, Uint8Array, Int16Array, Uint16Array,
Int32Array, Uint32Array, Float32Array, Float64Array
];
isArrayBufferView = function (object) {
for (var i=0;i<8;i++) {
if (object instanceof arrayBufferViews[i]) {
return true;
}
}
return false;
};
}
var isFolder = RemoteStorage.util.isFolder;
var cleanPath = RemoteStorage.util.cleanPath;
function addQuotes(str) {
if (typeof(str) !== 'string') {
return str;
}
if (str === '*') {
return '*';
}
return '"' + str + '"';
}
function stripQuotes(str) {
if (typeof(str) !== 'string') {
return str;
}
return str.replace(/^["']|["']$/g, '');
}
function readBinaryData(content, mimeType, callback) {
var blob;
global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder;
if (typeof global.BlobBuilder !== 'undefined') {
var bb = new global.BlobBuilder();
bb.append(content);
blob = bb.getBlob(mimeType);
} else {
blob = new Blob([content], { type: mimeType });
}
var reader = new FileReader();
if (typeof reader.addEventListener === 'function') {
reader.addEventListener('loadend', function () {
callback(reader.result); // reader.result contains the contents of blob as a typed array
});
} else {
reader.onloadend = function() {
callback(reader.result); // reader.result contains the contents of blob as a typed array
};
}
reader.readAsArrayBuffer(blob);
}
function getTextFromArrayBuffer(arrayBuffer, encoding) {
var pending = Promise.defer();
if (typeof Blob === 'undefined') {
var buffer = new Buffer(new Uint8Array(arrayBuffer));
pending.resolve(buffer.toString(encoding));
} else {
var blob;
global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder;
if (typeof global.BlobBuilder !== 'undefined') {
var bb = new global.BlobBuilder();
bb.append(arrayBuffer);
blob = bb.getBlob();
} else {
blob = new Blob([arrayBuffer]);
}
var fileReader = new FileReader();
if (typeof fileReader.addEventListener === 'function') {
fileReader.addEventListener('loadend', function (evt) {
pending.resolve(evt.target.result);
});
} else {
fileReader.onloadend = function(evt) {
pending.resolve(evt.target.result);
};
}
fileReader.readAsText(blob, encoding);
}
return pending.promise;
}
function determineCharset(mimeType) {
var charset = 'UTF-8';
var charsetMatch;
if (mimeType) {
charsetMatch = mimeType.match(/charset=(.+)$/);
if (charsetMatch) {
charset = charsetMatch[1];
}
}
return charset;
}
function isFolderDescription(body) {
return ((body['@context'] === 'http://remotestorage.io/spec/folder-description')
&& (typeof(body['items']) === 'object'));
}
function isSuccessStatus(status) {
return [201, 204, 304].indexOf(status) >= 0;
}
function isErrorStatus(status) {
return [401, 403, 404, 412].indexOf(status) >= 0;
}
var onErrorCb;
/**
* Class : RemoteStorage.WireClient
**/
RS.WireClient = function (rs) {
this.rs = rs;
this.connected = false;
/**
* Event: change
* Never fired for some reason
* # TODO create issue and fix or remove
*
* Event: connected
* Fired when the wireclient connect method realizes that it is in
* possession of a token and href
**/
RS.eventHandling(this, 'change', 'connected', 'not-connected',
'wire-busy', 'wire-done');
onErrorCb = function (error){
if (error instanceof RemoteStorage.Unauthorized) {
this.configure({token: null});
}
}.bind(this);
rs.on('error', onErrorCb);
if (hasLocalStorage) {
var settings;
try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {}
if (settings) {
setTimeout(function () {
this.configure(settings);
}.bind(this), 0);
}
}
this._revisionCache = {};
if (this.connected) {
setTimeout(this._emit.bind(this), 0, 'connected');
}
};
RS.WireClient.REQUEST_TIMEOUT = 30000;
RS.WireClient.prototype = {
/**
* Property: token
*
* Holds the bearer token of this WireClient, as obtained in the OAuth dance
*
* Example:
* (start code)
*
* remoteStorage.remote.token
* // -> 'DEADBEEF01=='
*/
/**
* Property: href
*
* Holds the server's base URL, as obtained in the Webfinger discovery
*
* Example:
* (start code)
*
* remoteStorage.remote.href
* // -> 'https://storage.example.com/users/jblogg/'
*/
/**
* Property: storageApi
*
* Holds the spec version the server claims to be compatible with
*
* Example:
* (start code)
*
* remoteStorage.remote.storageApi
* // -> 'draft-dejong-remotestorage-01'
*/
_request: function (method, uri, token, headers, body, getEtag, fakeRevision) {
if ((method === 'PUT' || method === 'DELETE') && uri[uri.length - 1] === '/') {
return Promise.reject('Don\'t ' + method + ' on directories!');
}
var revision;
var reqType;
var self = this;
if (token !== RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN) {
headers['Authorization'] = 'Bearer ' + token;
}
this._emit('wire-busy', {
method: method,
isFolder: isFolder(uri)
});
return RS.WireClient.request(method, uri, {
body: body,
headers: headers,
responseType: 'arraybuffer'
}).then(function(response) {
if (!self.online) {
self.online = true;
self.rs._emit('network-online');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: true
});
if (isErrorStatus(response.status)) {
RemoteStorage.log('[WireClient] Error response status', response.status);
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = undefined;
}
return Promise.resolve({statusCode: response.status, revision: revision});
} else if (isSuccessStatus(response.status) ||
(response.status === 200 && method !== 'GET')) {
revision = stripQuotes(response.getResponseHeader('ETag'));
RemoteStorage.log('[WireClient] Successful request', revision);
return Promise.resolve({statusCode: response.status, revision: revision});
} else {
var mimeType = response.getResponseHeader('Content-Type');
var body;
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = response.status === 200 ? fakeRevision : undefined;
}
var charset = determineCharset(mimeType);
if ((!mimeType) || charset === 'binary') {
RemoteStorage.log('[WireClient] Successful request with unknown or binary mime-type', revision);
return Promise.resolve({statusCode: response.status, body: response.response, contentType: mimeType, revision: revision});
} else {
return getTextFromArrayBuffer(response.response, charset).then(function (body) {
RemoteStorage.log('[WireClient] Successful request', revision);
return Promise.resolve({statusCode: response.status, body: body, contentType: mimeType, revision: revision});
});
}
}
}, function (error) {
if (self.online) {
self.online = false;
self.rs._emit('network-offline');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: false
});
return Promise.reject(error);
});
},
/**
*
* Method: configure
*
* Sets the userAddress, href, storageApi, token, and properties of a
* remote store. Also sets connected and online to true and emits the
* 'connected' event, if both token and href are present.
*
* Parameters:
* settings - An object that may contain userAddress (string or null),
* href (string or null), storageApi (string or null), token (string
* or null), and/or properties (the JSON-parsed properties object
* from the user's WebFinger record, see section 10 of
* http://tools.ietf.org/html/draft-dejong-remotestorage-03
* or null).
* Fields that are not included (i.e. `undefined`), stay at
* their current value. To set a field, include that field
* with a `string` value. To reset a field, for instance when
* the user disconnected their storage, or you found that the
* token you have has expired, simply set that field to `null`.
*/
configure: function (settings) {
if (typeof settings !== 'object') {
throw new Error('WireClient configure settings parameter should be an object');
}
if (typeof settings.userAddress !== 'undefined') {
this.userAddress = settings.userAddress;
}
if (typeof settings.href !== 'undefined') {
this.href = settings.href;
}
if (typeof settings.storageApi !== 'undefined') {
this.storageApi = settings.storageApi;
}
if (typeof settings.token !== 'undefined') {
this.token = settings.token;
}
if (typeof settings.properties !== 'undefined') {
this.properties = settings.properties;
}
if (typeof this.storageApi !== 'undefined') {
this._storageApi = STORAGE_APIS[this.storageApi] || API_HEAD;
this.supportsRevs = this._storageApi >= API_00;
}
if (this.href && this.token) {
this.connected = true;
this.online = true;
this._emit('connected');
} else {
this.connected = false;
}
if (hasLocalStorage) {
localStorage[SETTINGS_KEY] = JSON.stringify({
userAddress: this.userAddress,
href: this.href,
storageApi: this.storageApi,
token: this.token,
properties: this.properties
});
}
},
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
get: function (path, options) {
var self = this;
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
var headers = {};
if (this.supportsRevs) {
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
} else if (options.ifNoneMatch) {
var oldRev = this._revisionCache[path];
}
return this._request('GET', this.href + cleanPath(path), this.token, headers,
undefined, this.supportsRevs, this._revisionCache[path])
.then(function (r) {
if (!isFolder(path)) {
return Promise.resolve(r);
}
var itemsMap = {};
if (typeof(r.body) !== 'undefined') {
try {
r.body = JSON.parse(r.body);
} catch (e) {
return Promise.reject('Folder description at ' + self.href + cleanPath(path) + ' is not JSON');
}
}
if (r.statusCode === 200 && typeof(r.body) === 'object') {
// New folder listing received
if (Object.keys(r.body).length === 0) {
// Empty folder listing of any spec
r.statusCode = 404;
} else if (isFolderDescription(r.body)) {
// >= 02 spec
for (var item in r.body.items) {
self._revisionCache[path + item] = r.body.items[item].ETag;
}
itemsMap = r.body.items;
} else {
// < 02 spec
Object.keys(r.body).forEach(function (key){
self._revisionCache[path + key] = r.body[key];
itemsMap[key] = {'ETag': r.body[key]};
});
}
r.body = itemsMap;
return Promise.resolve(r);
} else {
return Promise.resolve(r);
}
});
},
put: function (path, body, contentType, options) {
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) {
contentType += '; charset=binary';
}
var headers = { 'Content-Type': contentType };
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
}
return this._request('PUT', this.href + cleanPath(path), this.token,
headers, body, this.supportsRevs);
},
'delete': function (path, options) {
if (!this.connected) {
throw new Error('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
var headers = {};
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
}
return this._request('DELETE', this.href + cleanPath(path), this.token,
headers,
undefined, this.supportsRevs);
}
};
// Shared cleanPath used by Dropbox
RS.WireClient.cleanPath = cleanPath;
// Shared isArrayBufferView used by WireClient and Dropbox
RS.WireClient.isArrayBufferView = isArrayBufferView;
RS.WireClient.readBinaryData = readBinaryData;
// Shared request function used by WireClient, GoogleDrive and Dropbox.
RS.WireClient.request = function (method, url, options) {
var pending = Promise.defer();
RemoteStorage.log('[WireClient]', method, url);
var timedOut = false;
var timer = setTimeout(function () {
timedOut = true;
pending.reject('timeout');
}, RS.WireClient.REQUEST_TIMEOUT);
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (options.responseType) {
xhr.responseType = options.responseType;
}
if (options.headers) {
for (var key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
xhr.onload = function () {
if (timedOut) { return; }
clearTimeout(timer);
pending.resolve(xhr);
};
xhr.onerror = function (error) {
if (timedOut) { return; }
clearTimeout(timer);
pending.reject(error);
};
var body = options.body;
if (typeof(body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) {
body = new Uint8Array(body);
}
xhr.send(body);
return pending.promise;
};
Object.defineProperty(RemoteStorage.WireClient.prototype, 'storageType', {
get: function () {
if (this.storageApi) {
var spec = this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);
return spec ? spec[1] : '2012.04';
}
}
});
RS.WireClient._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
remoteStorage.remote = new RS.WireClient(remoteStorage);
this.online = true;
};
RS.WireClient._rs_supported = function () {
return !! global.XMLHttpRequest;
};
RS.WireClient._rs_cleanup = function (remoteStorage){
if (hasLocalStorage){
delete localStorage[SETTINGS_KEY];
}
remoteStorage.removeEventListener('error', onErrorCb);
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/discover.js **/
(function (global) {
// feature detection flags
var haveXMLHttpRequest, hasLocalStorage;
// used to store settings in localStorage
var SETTINGS_KEY = 'remotestorage:discover';
// cache loaded from localStorage
var cachedInfo = {};
/**
* Class: RemoteStorage.Discover
*
* This function deals with the Webfinger lookup, discovering a connecting
* user's storage details.
*
* The discovery timeout can be configured via
* `RemoteStorage.config.discoveryTimeout` (in ms).
*
* Arguments:
*
* userAddress - user@host
*
* Returns:
*
* A promise for an object with the following properties.
*
* href - Storage base URL,
* storageType - Storage type,
* authUrl - OAuth URL,
* properties - Webfinger link properties
**/
RemoteStorage.Discover = function (userAddress) {
if (userAddress in cachedInfo) {
return Promise.resolve(cachedInfo[userAddress]);
}
var webFinger = new WebFinger({
tls_only: false,
uri_fallback: true,
request_timeout: 5000
});
var pending = Promise.defer();
webFinger.lookup(userAddress, function (err, response) {
if (err) {
return pending.reject(err);
} else if ((typeof response.idx.links.remotestorage !== 'object') ||
(typeof response.idx.links.remotestorage.length !== 'number') ||
(response.idx.links.remotestorage.length <= 0)) {
RemoteStorage.log("[Discover] WebFinger record for " + userAddress + " does not have remotestorage defined in the links section ", JSON.stringify(response.json));
return pending.reject("WebFinger record for " + userAddress + " does not have remotestorage defined in the links section.");
}
var rs = response.idx.links.remotestorage[0];
var authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] ||
rs.properties['auth-endpoint'];
var storageType = rs.properties['http://remotestorage.io/spec/version'] ||
rs.type;
// cache fetched data
cachedInfo[userAddress] = { href: rs.href, storageType: storageType, authURL: authURL, properties: rs.properties };
if (hasLocalStorage) {
localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo });
}
return pending.resolve(cachedInfo[userAddress]);
});
return pending.promise;
};
RemoteStorage.Discover._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (hasLocalStorage) {
var settings;
try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {}
if (settings) {
cachedInfo = settings.cache;
}
}
};
RemoteStorage.Discover._rs_supported = function () {
haveXMLHttpRequest = !! global.XMLHttpRequest;
return haveXMLHttpRequest;
};
RemoteStorage.Discover._rs_cleanup = function () {
if (hasLocalStorage) {
delete localStorage[SETTINGS_KEY];
}
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: node_modules/webfinger.js/src/webfinger.js **/
/* global define */
/*!
* webfinger.js
* version 2.4.2
* http://github.com/silverbucket/webfinger.js
*
* Developed and Maintained by:
* Nick Jennings <[email protected]> 2012 - 2016
*
* webfinger.js is released under the AGPL (see LICENSE).
*
* You don't have to do anything special to choose one license or the other and you don't
* have to notify anyone which license you are using.
* Please see the corresponding license file for details of these licenses.
* You are free to use, modify and distribute this software, but all copyright
* information must remain.
*
*/
if (typeof XMLHttpRequest === 'undefined') {
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
}
(function (undefined) {
// URI to property name map
var LINK_URI_MAPS = {
'http://webfist.org/spec/rel': 'webfist',
'http://webfinger.net/rel/avatar': 'avatar',
'remotestorage': 'remotestorage',
'http://tools.ietf.org/id/draft-dejong-remotestorage': 'remotestorage',
'remoteStorage': 'remotestorage',
'http://www.packetizer.com/rel/share': 'share',
'http://webfinger.net/rel/profile-page': 'profile',
'me': 'profile',
'vcard': 'vcard',
'blog': 'blog',
'http://packetizer.com/rel/blog': 'blog',
'http://schemas.google.com/g/2010#updates-from': 'updates',
'https://camlistore.org/rel/server': 'camilstore'
};
var LINK_PROPERTIES = {
'avatar': [],
'remotestorage': [],
'blog': [],
'vcard': [],
'updates': [],
'share': [],
'profile': [],
'webfist': [],
'camlistore': []
};
// list of endpoints to try, fallback from beginning to end.
var URIS = ['webfinger', 'host-meta', 'host-meta.json'];
function generateErrorObject(obj) {
obj.toString = function () {
return this.message;
};
return obj;
}
// given a URL ensures it's HTTPS.
// returns false for null string or non-HTTPS URL.
function isSecure(url) {
if (typeof url !== 'string') {
return false;
}
var parts = url.split('://');
if (parts[0] === 'https') {
return true;
}
return false;
}
/**
* Function: WebFinger
*
* WebFinger constructor
*
* Returns:
*
* return WebFinger object
*/
function WebFinger(config) {
if (typeof config !== 'object') {
config = {};
}
this.config = {
tls_only: (typeof config.tls_only !== 'undefined') ? config.tls_only : true,
webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false,
uri_fallback: (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false,
request_timeout: (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000
};
}
// make an http request and look for JRD response, fails if request fails
// or response not json.
WebFinger.prototype.__fetchJRD = function (url, errorHandler, sucessHandler) {
var self = this;
var xhr = new XMLHttpRequest();
function __processState() {
if (xhr.status === 200) {
if (self.__isValidJSON(xhr.responseText)) {
return sucessHandler(xhr.responseText);
} else {
return errorHandler(generateErrorObject({
message: 'invalid json',
url: url,
status: xhr.status
}));
}
} else if (xhr.status === 404) {
return errorHandler(generateErrorObject({
message: 'resource not found',
url: url,
status: xhr.status
}));
} else if ((xhr.status >= 301) && (xhr.status <= 302)) {
var location = xhr.getResponseHeader('Location');
if (isSecure(location)) {
return __makeRequest(location); // follow redirect
} else {
return errorHandler(generateErrorObject({
message: 'no redirect URL found',
url: url,
status: xhr.status
}));
}
} else {
return errorHandler(generateErrorObject({
message: 'error during request',
url: url,
status: xhr.status
}));
}
}
function __makeRequest() {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
__processState();
}
};
xhr.onload = function (a, b) {
__processState();
}
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept', 'application/jrd+json, application/json');
xhr.send();
}
return __makeRequest();
};
WebFinger.prototype.__isValidJSON = function (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
WebFinger.prototype.__isLocalhost = function (host) {
var local = /^localhost(\.localdomain)?(\:[0-9]+)?$/;
return local.test(host);
};
// processes JRD object as if it's a webfinger response object
// looks for known properties and adds them to profile datat struct.
WebFinger.prototype.__processJRD = function (URL, JRD, errorHandler, successHandler) {
var parsedJRD = JSON.parse(JRD);
if ((typeof parsedJRD !== 'object') ||
(typeof parsedJRD.links !== 'object')) {
if (typeof parsedJRD.error !== 'undefined') {
return errorHandler(generateErrorObject({ message: parsedJRD.error, request: URL }));
} else {
return errorHandler(generateErrorObject({ message: 'unknown response from server', request: URL }));
}
}
var links = parsedJRD.links;
var result = { // webfinger JRD - object, json, and our own indexing
object: parsedJRD,
json: JRD,
idx: {}
};
result.idx.properties = {
'name': undefined
};
result.idx.links = JSON.parse(JSON.stringify(LINK_PROPERTIES));
// process links
links.map(function (link, i) {
if (LINK_URI_MAPS.hasOwnProperty(link.rel)) {
if (result.idx.links[LINK_URI_MAPS[link.rel]]) {
var entry = {};
Object.keys(link).map(function (item, n) {
entry[item] = link[item];
});
result.idx.links[LINK_URI_MAPS[link.rel]].push(entry);
}
}
});
// process properties
var props = JSON.parse(JRD).properties;
for (var key in props) {
if (props.hasOwnProperty(key)) {
if (key === 'http://packetizer.com/ns/name') {
result.idx.properties.name = props[key];
}
}
}
return successHandler(result);
};
WebFinger.prototype.lookup = function (address, cb) {
if (typeof address !== 'string') {
throw new Error('first parameter must be a user address');
} else if (typeof cb !== 'function') {
throw new Error('second parameter must be a callback');
}
var self = this;
var host = '';
if (address.indexOf('://') > -1) {
// other uri format
host = address.replace(/ /g,'').split('://')[1];
} else {
// useraddress
host = address.replace(/ /g,'').split('@')[1];
}
var uri_index = 0; // track which URIS we've tried already
var protocol = 'https'; // we use https by default
if (self.__isLocalhost(host)) {
protocol = 'http';
}
function __buildURL() {
var uri = '';
if (! address.split('://')[1]) {
// the URI has not been defined, default to acct
uri = 'acct:';
}
return protocol + '://' + host + '/.well-known/' +
URIS[uri_index] + '?resource=' + uri + address;
}
// control flow for failures, what to do in various cases, etc.
function __fallbackChecks(err) {
if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try
uri_index = uri_index + 1;
return __call();
} else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http
uri_index = 0;
protocol = 'http';
return __call();
} else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt
uri_index = 0;
protocol = 'http';
host = 'webfist.org';
// webfist will
// 1. make a query to the webfist server for the users account
// 2. from the response, get a link to the actual webfinger json data
// (stored somewhere in control of the user)
// 3. make a request to that url and get the json
// 4. process it like a normal webfinger response
var URL = __buildURL();
self.__fetchJRD(URL, cb, function (data) { // get link to users JRD
self.__processJRD(URL, data, cb, function (result) {
if ((typeof result.idx.links.webfist === 'object') &&
(typeof result.idx.links.webfist[0].href === 'string')) {
self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {
self.__processJRD(URL, JRD, cb, function (result) {
return cb(null, cb);
});
});
}
});
});
} else {
return cb(err);
}
}
function __call() {
// make request
var URL = __buildURL();
self.__fetchJRD(URL, __fallbackChecks, function (JRD) {
self.__processJRD(URL, JRD, cb, function (result) { cb(null, result); });
});
}
return setTimeout(__call, 0);
};
WebFinger.prototype.lookupLink = function (address, rel, cb) {
if (LINK_PROPERTIES.hasOwnProperty(rel)) {
this.lookup(address, function (err, p) {
var links = p.idx.links[rel];
if (err) {
return cb(err);
} else if (links.length === 0) {
return cb('no links found with rel="' + rel + '"');
} else {
return cb(null, links[0]);
}
});
} else {
return cb('unsupported rel ' + rel);
}
};
if (typeof window === 'object') {
window.WebFinger = WebFinger;
} else if (typeof (define) === 'function' && define.amd) {
define([], function () { return WebFinger; });
} else {
try {
module.exports = WebFinger;
} catch (e) {}
}
})();
/** FILE: src/authorize.js **/
(function (global) {
function extractParams(url) {
//FF already decodes the URL fragment in document.location.hash, so use this instead:
var location = url || RemoteStorage.Authorize.getLocation().href,
hashPos = location.indexOf('#'),
hash;
if (hashPos === -1) { return; }
hash = location.substring(hashPos+1);
// if hash is not of the form #key=val&key=val, it's probably not for us
if (hash.indexOf('=') === -1) { return; }
return hash.split('&').reduce(function (params, kvs) {
var kv = kvs.split('=');
if (kv[0] === 'state' && kv[1].match(/rsDiscovery/)) {
// extract rsDiscovery data from the state param
var stateValue = decodeURIComponent(kv[1]);
var encodedData = stateValue.substr(stateValue.indexOf('rsDiscovery='))
.split('&')[0]
.split('=')[1];
params['rsDiscovery'] = JSON.parse(atob(encodedData));
// remove rsDiscovery param
stateValue = stateValue.replace(new RegExp('\&?rsDiscovery=' + encodedData), '');
if (stateValue.length > 0) {
params['state'] = stateValue;
}
} else {
params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
}
return params;
}, {});
}
RemoteStorage.ImpliedAuth = function (storageApi, redirectUri) {
RemoteStorage.log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);
// Set a fixed access token, signalling to not send it as Bearer
remoteStorage.remote.configure({
token: RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN
});
document.location = redirectUri;
};
RemoteStorage.Authorize = function (remoteStorage, authURL, scope, redirectUri, clientId) {
RemoteStorage.log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId);
// keep track of the discovery data during redirect if we can't save it in localStorage
if (!RemoteStorage.util.localStorageAvailable() &&
remoteStorage.backend === 'remotestorage') {
redirectUri += redirectUri.indexOf('#') > 0 ? '&' : '#';
var discoveryData = {
userAddress: remoteStorage.remote.userAddress,
href: remoteStorage.remote.href,
storageApi: remoteStorage.remote.storageApi,
properties: remoteStorage.remote.properties
};
redirectUri += 'rsDiscovery=' + btoa(JSON.stringify(discoveryData));
}
var url = authURL, hashPos = redirectUri.indexOf('#');
url += authURL.indexOf('?') > 0 ? '&' : '?';
url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, ''));
url += '&scope=' + encodeURIComponent(scope);
url += '&client_id=' + encodeURIComponent(clientId);
if (hashPos !== - 1 && hashPos+1 !== redirectUri.length) {
url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1));
}
url += '&response_type=token';
if (global.cordova) {
return RemoteStorage.Authorize.openWindow(
url,
redirectUri,
'location=yes,clearsessioncache=yes,clearcache=yes'
)
.then(function(authResult) {
remoteStorage.remote.configure({
token: authResult.access_token
});
})
.then(null, function(error) {
console.error(error);
remoteStorage.widget.view.setState('initial');
});
}
RemoteStorage.Authorize.setLocation(url);
};
RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN = false;
RemoteStorage.prototype.authorize = function (authURL, cordovaRedirectUri) {
this.access.setStorageType(this.remote.storageType);
var scope = this.access.scopeParameter;
var redirectUri = global.cordova ?
cordovaRedirectUri :
String(RemoteStorage.Authorize.getLocation());
var clientId = redirectUri.match(/^(https?:\/\/[^\/]+)/)[0];
RemoteStorage.Authorize(this, authURL, scope, redirectUri, clientId);
};
/**
* Get current document location
*
* Override this method if access to document.location is forbidden
*/
RemoteStorage.Authorize.getLocation = function () {
return global.document.location;
};
/**
* Set current document location
*
* Override this method if access to document.location is forbidden
*/
RemoteStorage.Authorize.setLocation = function (location) {
if (typeof location === 'string') {
global.document.location.href = location;
} else if (typeof location === 'object') {
global.document.location = location;
} else {
throw "Invalid location " + location;
}
};
/**
* Open new InAppBrowser window for OAuth in Cordova
*/
RemoteStorage.Authorize.openWindow = function (url, redirectUri, options) {
var pending = Promise.defer();
var newWindow = global.open(url, '_blank', options);
if (!newWindow || newWindow.closed) {
pending.reject('Authorization popup was blocked');
return pending.promise;
}
var handleExit = function () {
pending.reject('Authorization was canceled');
};
var handleLoadstart = function (event) {
if (event.url.indexOf(redirectUri) !== 0) {
return;
}
newWindow.removeEventListener('exit', handleExit);
newWindow.close();
var authResult = extractParams(event.url);
if (!authResult) {
return pending.reject('Authorization error');
}
return pending.resolve(authResult);
};
newWindow.addEventListener('loadstart', handleLoadstart);
newWindow.addEventListener('exit', handleExit);
return pending.promise;
};
RemoteStorage.prototype.impliedauth = function () {
RemoteStorage.ImpliedAuth(this.remote.storageApi, String(document.location));
};
RemoteStorage.Authorize._rs_supported = function () {
return typeof(document) !== 'undefined';
};
var onFeaturesLoaded;
RemoteStorage.Authorize._rs_init = function (remoteStorage) {
onFeaturesLoaded = function () {
var authParamsUsed = false;
if (params) {
if (params.error) {
throw "Authorization server errored: " + params.error;
}
// rsDiscovery came with the redirect, because it couldn't be
// saved in localStorage
if (params.rsDiscovery) {
remoteStorage.remote.configure(params.rsDiscovery);
}
if (params.access_token) {
remoteStorage.remote.configure({
token: params.access_token
});
authParamsUsed = true;
}
if (params.remotestorage) {
remoteStorage.connect(params.remotestorage);
authParamsUsed = true;
}
if (params.state) {
location = RemoteStorage.Authorize.getLocation();
RemoteStorage.Authorize.setLocation(location.href.split('#')[0]+'#'+params.state);
}
}
if (!authParamsUsed) {
remoteStorage.remote.stopWaitingForToken();
}
};
var params = extractParams(),
location;
if (params) {
location = RemoteStorage.Authorize.getLocation();
location.hash = '';
}
remoteStorage.on('features-loaded', onFeaturesLoaded);
};
RemoteStorage.Authorize._rs_cleanup = function (remoteStorage) {
remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/access.js **/
(function(global) {
var SETTINGS_KEY = "remotestorage:access";
/**
* Class: RemoteStorage.Access
*
* Keeps track of claimed access and scopes.
*/
RemoteStorage.Access = function() {
this.reset();
};
RemoteStorage.Access.prototype = {
/**
* Method: claim
*
* Claim access on a given scope with given mode.
*
* Parameters:
* scope - An access scope, such as "contacts" or "calendar"
* mode - Access mode. Either "r" for read-only or "rw" for read/write
*
* Example:
* (start code)
* remoteStorage.access.claim('contacts', 'r');
* remoteStorage.access.claim('pictures', 'rw');
* (end code)
*
* Root access:
* Claiming root access, meaning complete access to all files and folders
* of a storage, can be done using an asterisk:
*
* (start code)
* remoteStorage.access.claim('*', 'rw');
* (end code)
*/
claim: function(scope, mode) {
if (typeof(scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) {
throw new Error('Scope should be a non-empty string without forward slashes');
}
if (!mode.match(/^rw?$/)) {
throw new Error('Mode should be either \'r\' or \'rw\'');
}
this._adjustRootPaths(scope);
this.scopeModeMap[scope] = mode;
},
get: function(scope) {
return this.scopeModeMap[scope];
},
remove: function(scope) {
var savedMap = {};
var name;
for (name in this.scopeModeMap) {
savedMap[name] = this.scopeModeMap[name];
}
this.reset();
delete savedMap[scope];
for (name in savedMap) {
this.set(name, savedMap[name]);
}
},
/**
* Verify permission for a given scope.
*/
checkPermission: function(scope, mode) {
var actualMode = this.get(scope);
return actualMode && (mode === 'r' || actualMode === 'rw');
},
/**
* Verify permission for a given path.
*/
checkPathPermission: function(path, mode) {
if (this.checkPermission('*', mode)) {
return true;
}
return !!this.checkPermission(this._getModuleName(path), mode);
},
reset: function() {
this.rootPaths = [];
this.scopeModeMap = {};
},
/**
* Return the module name for a given path.
*/
_getModuleName: function(path) {
if (path[0] !== '/') {
throw new Error('Path should start with a slash');
}
var moduleMatch = path.replace(/^\/public/, '').match(/^\/([^\/]*)\//);
return moduleMatch ? moduleMatch[1] : '*';
},
_adjustRootPaths: function(newScope) {
if ('*' in this.scopeModeMap || newScope === '*') {
this.rootPaths = ['/'];
} else if (! (newScope in this.scopeModeMap)) {
this.rootPaths.push('/' + newScope + '/');
this.rootPaths.push('/public/' + newScope + '/');
}
},
_scopeNameForParameter: function(scope) {
if (scope.name === '*' && this.storageType) {
if (this.storageType === '2012.04') {
return '';
} else if (this.storageType.match(/remotestorage-0[01]/)) {
return 'root';
}
}
return scope.name;
},
setStorageType: function(type) {
this.storageType = type;
}
};
/**
* Property: scopes
*
* Holds an array of claimed scopes in the form
* > { name: "<scope-name>", mode: "<mode>" }
*/
Object.defineProperty(RemoteStorage.Access.prototype, 'scopes', {
get: function() {
return Object.keys(this.scopeModeMap).map(function(key) {
return { name: key, mode: this.scopeModeMap[key] };
}.bind(this));
}
});
Object.defineProperty(RemoteStorage.Access.prototype, 'scopeParameter', {
get: function() {
return this.scopes.map(function(scope) {
return this._scopeNameForParameter(scope) + ':' + scope.mode;
}.bind(this)).join(' ');
}
});
// Documented in src/remotestorage.js
Object.defineProperty(RemoteStorage.prototype, 'access', {
get: function() {
var access = new RemoteStorage.Access();
Object.defineProperty(this, 'access', {
value: access
});
return access;
},
configurable: true
});
RemoteStorage.Access._rs_init = function() {};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/env.js **/
(function (pMode) {
var mode = pMode,
env = {},
isBackground = false;
RemoteStorage.Env = function () {
return env;
};
RemoteStorage.Env.isBrowser = function () {
return mode === "browser";
};
RemoteStorage.Env.isNode = function () {
return mode === "node";
};
RemoteStorage.Env.goBackground = function () {
isBackground = true;
RemoteStorage.Env._emit("background");
};
RemoteStorage.Env.goForeground = function () {
isBackground = false;
RemoteStorage.Env._emit("foreground");
};
RemoteStorage.Env._rs_init = function (remoteStorage) {
RemoteStorage.eventHandling(RemoteStorage.Env, "background", "foreground");
function visibility() {
if (document[env.hiddenProperty]) {
RemoteStorage.Env.goBackground();
} else {
RemoteStorage.Env.goForeground();
}
}
if ( mode === 'browser') {
if ( typeof(document.hidden) !== "undefined" ) {
env.hiddenProperty = "hidden";
env.visibilityChangeEvent = "visibilitychange";
} else if ( typeof(document.mozHidden) !== "undefined" ) {
env.hiddenProperty = "mozHidden";
env.visibilityChangeEvent = "mozvisibilitychange";
} else if ( typeof(document.msHidden) !== "undefined" ) {
env.hiddenProperty = "msHidden";
env.visibilityChangeEvent = "msvisibilitychange";
} else if ( typeof(document.webkitHidden) !== "undefined" ) {
env.hiddenProperty = "webkitHidden";
env.visibilityChangeEvent = "webkitvisibilitychange";
}
document.addEventListener(env.visibilityChangeEvent, visibility, false);
visibility();
}
};
RemoteStorage.Env._rs_cleanup = function (remoteStorage) {
};
})(typeof(window) !== 'undefined' ? 'browser' : 'node');
/** FILE: src/i18n.js **/
(function () {
/**
* Class: RemoteStorage.I18n
*
* TODO add documentation
**/
"use strict";
var dictionary = {
"view_info": 'This app allows you to use your own storage. <a href="http://remotestorage.io/" target="_blank">Learn more!</a>',
"view_connect": "<strong>Connect</strong> remote storage",
"view_connecting": "Connecting <strong>%s</strong>",
"view_offline": "Offline",
"view_error_occured": "Sorry! An error occured.",
"view_invalid_key": "Wrong key!",
"view_confirm_reset": "Are you sure you want to reset everything? This will clear your local data and reload the page.",
"view_get_me_out": "Get me out of here!",
"view_error_plz_report": 'If this problem persists, please <a href="http://remotestorage.io/community/" target="_blank">let us know</a>!',
"view_unauthorized": "Unauthorized! Click here to reconnect."
};
RemoteStorage.I18n = {
translate: function () {
var str = arguments[0],
params = Array.prototype.splice.call(arguments, 1);
if (typeof dictionary[str] !== "string") {
throw "Unknown translation string: " + str;
} else {
str = dictionary[str];
}
return (str.replace(/%s/g, function (){ return params.shift(); }));
},
getDictionary: function () {
return dictionary;
},
setDictionary: function (newDictionary) {
dictionary = newDictionary;
},
_rs_init: function() {
}
};
})();
/** FILE: src/assets.js **/
/** THIS FILE WAS GENERATED BY build/compile-assets.js. DO NOT CHANGE IT MANUALLY, BUT INSTEAD CHANGE THE ASSETS IN assets/. **/
RemoteStorage.Assets = {
cipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHdpZHRoPSIyNS4xNzciIHZlcnNpb249IjEuMSIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIGQ9Im0yNS4xNzcgNS41MzIzYy0wLjA1NjQtMC4xMTI5MS0wLjA1NjQtMC4yMjU4MS0wLjE2OTM2LTAuMzM4NzEtMC4xMTI5LTAuMTEyOS0wLjI4MjI1LTAuMTY5MzYtMC4zOTUxNi0wLjE2OTM2aC0xMS40MDNjLTAuNzMzLTIuODc5LTMuMzg2NC01LjAyNDItNi40OTEzLTUuMDI0Mi0zLjY2OTMgMC02LjcxNzcgMy4wNDg0LTYuNzE3NyA2LjcxNzcgMCAzLjcyNjMgMy4wNDg0IDYuNzE3MyA2LjcxNzcgNi43MTczIDMuMzMwNyAwIDYuMDQwMy0yLjQyNzQgNi42MDQ4LTUuNTg4N2gyLjU0MDN2My42Njk0YzAgMC4yODIyNiAwLjI4MjI2IDAuNTA4MDYgMC41NjQ1MiAwLjUwODA2aDEuNzVjMC4yODIyNiAwIDAuNTY0NTItMC4yMjU4IDAuNTY0NTItMC41MDgwNnYtMy42Njk0aDEuNDY3N3Y1LjY0NTJjMCAwLjI4MjI1IDAuMjI1OCAwLjUwODA2IDAuNTA4MDYgMC41MDgwNmgxLjgwNjRjMC4yODIyNiAwIDAuNTA4MDctMC4yMjU4MSAwLjU2NDUyLTAuNTA4MDZ2LTUuNjQ1MmgxLjUyNDJjMC4xMTI5MSAwIDAuMjgyMjYgMCAwLjM5NTE2LTAuMTEyOSAwLjExMjkxLTAuMTEyOSAwLjE2OTM2LTAuMjgyMjYgMC4xNjkzNi0wLjM5NTE2di0xLjgwNjR6bS0xOC40NTkgNS4wODA3Yy0yLjA4ODcgMC0zLjgzODctMS42OTM2LTMuODM4Ny0zLjgzODcgMC0yLjE0NTIgMS43NS0zLjgzODcgMy44Mzg3LTMuODM4NyAyLjE0NTIgMCAzLjgzODcgMS42OTM2IDMuODM4NyAzLjgzODcgMCAyLjE0NTItMS42OTM2IDMuODM4Ny0zLjgzODcgMy44Mzg3eiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K',
connectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAtMTAzNi40KSI+CiAgPHBhdGggZD0ibTEgMTA0Ny40di02aDd2LTRsNyA3LTcgN3YtNHoiIGZpbGw9IiNmZmYiLz4KIDwvZz4KPC9zdmc+Cg==',
disconnectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4wIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIHN0eWxlPSJibG9jay1wcm9ncmVzc2lvbjp0Yjt0ZXh0LWluZGVudDowO2NvbG9yOiMwMDAwMDA7dGV4dC10cmFuc2Zvcm06bm9uZSIgZD0ibTguMDAwMSAwYy0wLjQ3MTQgMC0wLjk2MTAzIDAuNTQxOS0wLjk1IDF2NmMtMC4wMDc0NyAwLjUyODMxIDAuNDIxNjMgMSAwLjk1IDFzMC45NTc0Ny0wLjQ3MTY5IDAuOTUtMXYtNmMwLjAxNDYyMi0wLjYwNTEtMC40Nzg2LTEtMC45NS0xem0tMy4zNDM4IDIuNWMtMC4wODcxODYgMC4wMTkyOTQtMC4xNzE2MyAwLjA1MDk1OS0wLjI1IDAuMDkzNzUtMi45OTk1IDEuNTcxNS0zLjkxODQgNC43OTc5LTMuMTI1IDcuNDY4OCAwLjc5MzQgMi42NyAzLjI3OTkgNC45MzcgNi42ODc1IDQuOTM3IDMuMzU5MiAwIDUuODc3Mi0yLjE0OSA2LjcxOTItNC43ODEgMC44NDEtMi42MzIxLTAuMDU4LTUuODIzNC0zLjEyNS03LjU5NC0wLjQzNC0wLjI1MzYtMS4wNTktMC4wODk5LTEuMzEzIDAuMzQzNy0wLjI1MzYgMC40MzM2LTAuMDkgMS4wNTg5IDAuMzQ0IDEuMzEyNSAyLjM5MDggMS4zNzk4IDIuODgyNSAzLjQ5NDQgMi4yODEyIDUuMzc1LTAuNjAxMiAxLjg4MDYtMi4zNDQgMy40Mzc1LTQuOTA2MiAzLjQzNzUtMi41NzU5IDAtNC4yOTc2LTEuNjUwMi00Ljg3NS0zLjU5MzgtMC41Nzc2LTEuOTQzNS0wLjA0Ny00LjA0OCAyLjE4NzMtNS4yMTg3IDAuMzc4Ny0wLjIwNjMgMC41NzkxLTAuNjkyNSAwLjQ1NTgtMS4xMDU3LTAuMTIzMi0wLjQxMzMtMC41NTcyLTAuNzEwMy0wLjk4Ny0wLjY3NTUtMC4wMzEzLTAuMDAxNS0wLjA2MjYtMC4wMDE1LTAuMDkzOCAweiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K',
dropbox: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEBAhEOpfuQAABhZJREFUWMPVl31snVUdxz+/5/2577e3b7QbHaOD0nXshW4ZZkpGQmJYZkJUDAaZzCBGAxGd+pdZQsJIjCaKgFu09GWybIggm8yhMCsY92rcOkPHunbdtKOUbX36svX23uc+xz+eDsrWlztiNJzk5D7JPS+fc8739/2dA5+EsqJtyK18ZlCKbX9Lk6fd1uo5xbTVZmtwa4v35Np5Mry4TLYXCzAnyhsry2SwrmnokdnaTruq6i3e0lXl0tqQlkURCxwdDp9Th5p3+p9iS8afqk/VZq9kaZoDN8apdU3B1KFnmLde7AkezH0n3V0UQOJpz2hIsqEhLU+WOeAagmtCxISYBe1nVf4vfWrByYdSpyf3W9ziLapy6JgbAduAiBn2S1rCQBYODAQP7H01/zxby4JpAW5s8mproxypiRKNGIJrQNT8EMA1wTGEU8MBP/q7umPw0dSbAA3N3n3zI2yLG2oScPgbNYWICY4Be86o/le6g0W576bPXQWwcqvXdJ2t1idMsA1hJoCoCRfGYdOhwsa4TUWFrr7pGmDrzAiQCHfD//Xxwk/33Z/6HoA0tnhLXZ3XMoYqsy4PYs4M4Ohg6pB2ddqO+vR6BWL27AARXbBNiBjwh9Oqs+O8ukcT4eaopjLqGsJSCdSX29SX23x/lctXlzgE1zBAANxWIQuGxlWNACxr8WozJp0lljKsGXbA0qGu1GRBxsTUQRAGLgboIuQVvHI8S+f7eeK2TLsDSQd296rhPaeDm09+PdX/gQYqN3uZ+jh7ro+oRusKDdgmVEY1GqstSiOhdegCmoQAIoImIWTPYIHdXVlyBYhaVwLA70+rPz7fllvLi2W5KcPw9q3eS/VJ7kmYgm1A3BIWV5osq7IIlMLUQJOrAXQBXQtr1BR2d2XpOu8TtULR+gq2nQh+vv8rqUdnNaKGZm/9qnJpmp/U+fxCB5lYsaGFdTYAY9L3jmNj9F9S7OgKVh9/KNVelBVf8untv8TYSS8gbsrHyh8C2LqQtGE0z9CJYfVuUblgRZv3WGOJvJG0cF8/lWPNdo+O93xsHYoVuqkL/xzIs/HPHt2DPg0Zko+v0I8vbfHun9aKE5sH9YaobJsf5V4mRLXv33kSlmAYwspqgw23R7A1EJlahKYOSsHTB0cZHQ9IOBA3NSrjGo4hWAY82xH8rH1b/jF2laoPAOb80jPqYtKTMdRcTQNd+xAgbgmuJbiGELfh3lsc7q41KQSTABBcC1qPjLH/XzniNqScsP1kgMsm9nJ34e2mNcmFAMby1qFPZyz1WlxXrprhuEUgUPDbd8Y59n6edbe61KZ1TF14vSfPLw5dYjhXIOMIM6lGAV+u0+tv+ttI/2+6/LsMQVXpUFCAqJkS9MT5anB2NGDjWxf5Yp3DvjN5th/LUhETolaRTqigxMGIWVKtHVyX2tGTJd2X5agUIfi8CmvUFOKGT++gT8wqLlKUgnwATxwq7P32m35Z+32pPQZA54MpH1iSb/XWZmx2VthTD1AATCBlCZ+dpwNg6EJjlUH3hQIKRaCujhZFaOPtfUH+8HvBnQceSP11yjA8vC616+A5FevL8jt/YiCR0HiQcAUVrnDHHO0jHTUNllXrpC0NRXiefjAxM4rhHLzQpZqf+eFFd/LkM17JGlu9p+xC8IgPhGlaqE1rNJZrxOzQok0dnjviY+nhbSntCH3DAWN+QMIWEhYsqTD4wYHChrPfSP9kqnmM6QAMkYtz4xqmDqeGA+rLNObGZVozkglx1ZfqZAvC2ZGAz9RYlEbAlsLoNd+Kx5RqO5/njKXDsnKdhCXFOaFAZUzjznlhyt5xIjiSLbBz2oVO98fRdalOoGZ5m/dUQ4pvJZ3Zr/CXlS5A74gabzlYePztr6U2faxr+eRy/RYvtjgjHauvkxvi9oTDXaGBuAUJWyh1hb3vqsOvfiG5/L/yMAE483BqdNeuXO3LvcGX3vEUhsZVsaYL9IzACz3BXcVOXvQOfKRsupBZv8R4bnW19rmqGPzqHz4BcMGn5U/Hgod5oiT3P3kvVj7rrfnx/pHBu7d7Azc1eY3/l0drzWbPXNjsGXySy38AbtMqneWU7BkAAAAASUVORK5CYII=',
googledrive: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEA85ztzJcQAABZVJREFUWMPtl1uoXVcVhr8x5tprn7M1NG1i0pQqSG2jLcXipYJXjPogqFgpaHMSFUkpIjU+leKbDxIQSiHgjZgmrfXgQ6SKj5Ji7YVS05aUUqKQlNLQeDnN5Zzk9Jy99xy/D3OttU/StDlV33TBZM3FXmuMf/5jjv+fG/7XL1vti9tnv3Dtnnf+87JY8YmZNxEMM1sZ7tWpjz764mriVqvKvmfb1ONLy3+dGyWu6EWbvQwoydv5BMSqFuereakmfnls1GP25IDaBGYYjplhljDz5tk7YMtPfurAf6UE9Z6tNwDPAPXwtcxL1x9n4zRgDjjm1gCyC6JpCLoW/OX65of1nzCwG6gNo3aYeXF981mTvK2/WWFiMmoj7X+z5JcE0N87c4e7b3EvyTwZT5/r8ezZHu6GuWGpSegJ8/ZeBu6fHv35s1/7t0rQv29mjWF/ATZ1L4bQwohrpkYc/sBpwhJYAVdKYECzYAESIk4Am3sf+sPCW2LAzb9jbpvMDXfD3fEqkRIcGdbsevlt9LylPYG1K6/K3QzK75uAr78lBgb3b7sc2cl2Uaa21sDiGMvB2iQeu/EMm6bKHjD3SUsCEChnpEAKiLisd/PB+UsyMPjZNwzzh1ixcnOfsFCX51NU/PTvA6pkTUdYw4R3zyu1ArMDqyvBQB82+FiJUQJ4C8YgVT1SSvSTs+vEmkcwe7qEsUnt233Aij0BW4ZPbfngKpRQs7hXpYQNvRiuEtATWOW4bLi+z04pJbCnBAkBJggBQlIBIZCUJM0Cm9+QgcED2+/G7BprdMZaAFZExm1FWcz+NLdj32G/6XfPCB5GoJKp7H5FARHRtgRI1y0/+cm7Lwpg+v7t64DvNd5S2mqirKXHy6RoArp1Ykrc2hKtKCtXlNEyoQ6Ydi498fF1F2FAdwEbV9UnZne+8q19Z7o63vTb+TPnRneeWxwxHGdyziii6wApQNEydKUUd5wHYGrftvci7tKKLSME5bvCaruynI9rNL7vdZgiHhiP898Wl8bMnxty+uyIhcURo1FgjSg1DCDph4uPfuR9AFbvvS25p2cxbiyKVuh2o1O44n2lLLacb5v75v5fX6yl5h753IwUD+YcRAQ5B6FMMhj0jboSRhnAE258wvp7Z7aYcbCYCeCGt97ubfICLDP/q4WZ32x7M20fPfb+hxbH9ZdjHOQIIoR74EDywA3coa6MqtJnrP+LmRmcB63ob8dA1wllRm95LVc//22S16TGeKqqpqoHk10ESGJj/zjjgIhAISKCyJmcY6Uu8Pbq7C0V6ABh35dzvYWQG0QAhmSYCaUlNhzdCrlX2jpE6tV4b9DYcGFKEgG8svQucoicC4CsII8zeTxutAEQzx1duPL3vrxjdlnou0SDLdTulxJQmalXNzN98jpEJiSo+qTeoEnsnWC5lVZNRhkOZiq0G8XCmz1gpp3j/ZYdYLhj9qCkn3fJQ4QKeh9OccWxz6O0hGKM9wakeoBEZ1BmqfOMyYFk4gXS+edG4J4ju6/644VK+AOJhSIYpVRBpn/qPVRL65A51dRavJoG2UQkOqf0hgVrGG7u6syoJDObB+55nRANb589Afy40W0UwkY91h39CiLweg1UU+W3ohLNvC2VurJ1htR6A3QaYPCjI7uvOvGGOlfv2XoSuBzEhmNfZXDqBrweUPVqUlWodneSG+6J1NTevThfDpEjmnsmzuuCPPfCvRvfcakT0S2Aeq9tYPr0ZryeBvOOlZBKUIEiCAVZwTgy41x6v6hm0LFZ4o7N7IuXPA+EDx+XjQ+tP/4lUrW2vCI1ydR0iYgmWdtu4yzG7bOiAdn8iYlA0iFJh1Z1JJv+ye2b3n1419XRH2riP0aqqlKClABIjUMW+rtSlw5qmCpgsynnl56/d+M/+P91wfUvQjDgTzx9h9AAAAAASUVORK5CYII=',
nocipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPHBhdGggZD0ibSAxMy4yMDMxMjQsMTEuNzczNDM4IGMgMC4yODEyNSwwLjI4MTI1IDAuNDIxODc1LDAuNjA5Mzc1IDAuNDIxODc1LDEuMDMxMjUgMCwwLjM3NSAtMC4xNDA2MjUsMC43NSAtMC40MjE4NzUsMS4wMzEyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42MDkzNzUsMC4zNzUgLTEuMDMxMjUsMC4zNzUgLTAuMzc1LDAgLTAuNzUsLTAuMTQwNjI1IC0xLjAzMTI1LC0wLjM3NSAwLDAgLTMuMTg3NDk4MSwtMy42NTYyNSAtMy4xODc0OTgxLC0zLjY1NjI1IDAsMCAtMy4xNDA2MjUsMy42NTYyNSAtMy4xNDA2MjUsMy42NTYyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42NTYyNSwwLjM3NSAtMS4wMzEyNSwwLjM3NSAtMC40MjE4NzUsMCAtMC43NSwtMC4xNDA2MjUgLTEuMDMxMjUsLTAuMzc1IC0wLjI4MTI1LC0wLjI4MTI1IC0wLjM3NSwtMC42NTYyNSAtMC4zNzUsLTEuMDMxMjUgMCwtMC40MjE4NzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLDAgMy4zMjgxMjUsLTMuNzUwMDAwNSAzLjMyODEyNSwtMy43NTAwMDA1IDAsMCAtMy4zMjgxMjUsLTMuNzk2ODc1IC0zLjMyODEyNSwtMy43OTY4NzUgLTAuMjgxMjUsLTAuMjgxMjUgLTAuMzc1LC0wLjYwOTM3NSAtMC4zNzUsLTEuMDMxMjUgMCwtMC4zNzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjYwOTM3NSwtMC4zNzUgMS4wMzEyNSwtMC4zNzUgMC4zNzUsMCAwLjc1LDAuMTQwNjI1IDEuMDMxMjUsMC4zNzUgMCwwIDMuMTQwNjI1LDMuNjU2MjUgMy4xNDA2MjUsMy42NTYyNSAwLDAgMy4xODc0OTgxLC0zLjY1NjI1IDMuMTg3NDk4MSwtMy42NTYyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjY1NjI1LC0wLjM3NSAxLjAzMTI1LC0wLjM3NSAwLjQyMTg3NSwwIDAuNzUsMC4xNDA2MjUgMS4wMzEyNSwwLjM3NSAwLjI4MTI1LDAuMjgxMjUgMC40MjE4NzUsMC42NTYyNSAwLjQyMTg3NSwxLjAzMTI1IDAsMC40MjE4NzUgLTAuMTQwNjI1LDAuNzUgLTAuNDIxODc1LDEuMDMxMjUgMCwwIC0zLjMyODEyMzEsMy43OTY4NzUgLTMuMzI4MTIzMSwzLjc5Njg3NSAwLDAgMy4zMjgxMjMxLDMuNzUwMDAwNSAzLjMyODEyMzEsMy43NTAwMDA1IiBmaWxsPSIjZmZmIi8+Cjwvc3ZnPgo=',
remoteStorageIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
remoteStorageIconCiphered: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xNiAwbDAuMTI1IDYuMzc1YzIuMDk4IDAuMDY3IDMuNzUgMS43NTk1IDMuNzUgMy44NzV2MS45NjloMS45MzcgMC4wMzJsOC00LjIxOS0xMy44NDQtOHpsLTEzLjg0NCA4IDggNC4yMTloMC4wMzIgMS45MDZ2LTEuOTY5YzAtMi4xMTU1IDEuNjgzLTMuODA4IDMuNzgxLTMuODc1bDAuMTI1LTYuMzc1em0tMTMuODQ0IDh2MTZsNy45OTk4LTQuODQ0di02LjA5NGwtNy45OTk4LTUuMDYyem0wIDE2bDEzLjg0NCA4LTAuMzc1LTEwLjA2MmgtNS40Njl2LTIuMzQ0bC03Ljk5OTggNC40MDZ6bTEzLjg0NCA4bDEzLjg0NC04LTgtNC40MDZ2Mi4zNDRoLTUuNDY5bC0wLjM3NSAxMC4wNjJ6bTEzLjg0NC04di0xNmwtOCA1LjA2MnY2LjA5NGw4IDQuODQ0em0tMTMuOTY5LTE3Yy0xLjczNSAwLjA2NjYtMy4xMjUgMS40OTg3LTMuMTI1IDMuMjV2MS45NjloMy4wMzFsMC4wOTQtNS4yMTl6bTAuMjUgMGwwLjA5NCA1LjIxOWgzLjAzMXYtMS45NjljMC0xLjc1MTMtMS4zOS0zLjE4MzQtMy4xMjUtMy4yNXptLTQuNzUgNS44NDRsNC4zNDQgMi4yODEgMC4wMzEtMi4yODFoLTQuMzc1em00Ljg3NSAwbDAuMDMxIDIuMjgxIDQuMzQ0LTIuMjgxaC00LjM3NXptLTUuNDM4IDAuNjI1djUuMzEybDQuMjgyLTIuNTkzLTQuMjgyLTIuNzE5em0xMC4zNzYgMGwtNC4yODIgMi43MTkgNC4yODIgMi41OTN2LTUuMzEyem0tNS43ODIgMy4yMTlsLTQuNTk0IDIuNTMxdjIuMDYyaDQuNzgybC0wLjE4OC00LjU5M3ptMS4xODggMGwtMC4xODggNC41OTNoNC43ODJ2LTIuMDYybC00LjU5NC0yLjUzMXoiIGZpbGw9InVybCgjYSkiLz4KPC9zdmc+Cg==',
remoteStorageIconError: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2U5MDAwMCIgc3RvcC1vcGFjaXR5PSIuNzYwNzgiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZTkwMDAwIiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
remoteStorageIconOffline: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iIzY5Njk2OSIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjNjc2NzY3IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
syncIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDg3LjUgMTAwIiB4bWw6c3BhY2U9InByZXNlcnZlIiBoZWlnaHQ9IjE2IiB2aWV3Qm94PSIwIDAgMTUuOTk5OTk5IDE2IiB3aWR0aD0iMTYiIHZlcnNpb249IjEuMSIgeT0iMHB4IiB4PSIwcHgiIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC01LjUxMTIgLTc2LjUyNSkiIGRpc3BsYXk9Im5vbmUiPgoJPHBhdGggZGlzcGxheT0iaW5saW5lIiBkPSJtNTEuNDczIDQyLjI1NS0yLjIwNSAyLjIxMmMxLjQ3OCAxLjQ3NyAyLjI5NSAzLjQ0MiAyLjI5NSA1LjUzMyAwIDQuMzA5LTMuNTA0IDcuODEyLTcuODEyIDcuODEydi0xLjU2MmwtMy4xMjUgMy4xMjUgMy4xMjQgMy4xMjV2LTEuNTYyYzYuMDI5IDAgMTAuOTM4LTQuOTA2IDEwLjkzOC0xMC45MzggMC0yLjkyNy0xLjE0MS01LjY3Ni0zLjIxNS03Ljc0NXoiLz4KCTxwYXRoIGRpc3BsYXk9ImlubGluZSIgZD0ibTQ2Ljg3NSA0MC42MjUtMy4xMjUtMy4xMjV2MS41NjJjLTYuMDMgMC0xMC45MzggNC45MDctMTAuOTM4IDEwLjkzOCAwIDIuOTI3IDEuMTQxIDUuNjc2IDMuMjE3IDcuNzQ1bDIuMjAzLTIuMjEyYy0xLjQ3Ny0xLjQ3OS0yLjI5NC0zLjQ0Mi0yLjI5NC01LjUzMyAwLTQuMzA5IDMuNTA0LTcuODEyIDcuODEyLTcuODEydjEuNTYybDMuMTI1LTMuMTI1eiIvPgo8L2c+CjxwYXRoIGZpbGw9IiNmZmYiIGQ9Im0xMCAwbC0wLjc1IDEuOTA2MmMtMS4wMDc4LTAuMjk0Mi0zLjQ1ODYtMC43NzA4LTUuNjU2MiAwLjkzNzYgMC0wLjAwMDItMy45MzAyIDIuNTk0MS0yLjA5MzggNy41OTQybDEuNjU2Mi0wLjcxOTJzLTEuNTM5OS0zLjExMjIgMS42ODc2LTUuNTMxM2MwIDAgMS42OTU3LTEuMTMzOSAzLjY4NzQtMC41OTM3bC0wLjcxODcgMS44MTI0IDMuODEyNS0xLjYyNS0xLjYyNS0zLjc4MTJ6Ii8+PHBhdGggZmlsbD0iI2ZmZiIgZD0ibTE0IDUuNTYyNWwtMS42NTYgMC43MTg3czEuNTQxIDMuMTEzNS0xLjY4OCA1LjUzMDhjMCAwLTEuNzI3MiAxLjEzNS0zLjcxODUgMC41OTRsMC43NS0xLjgxMi0zLjgxMjUgMS41OTQgMS41OTM4IDMuODEyIDAuNzgxMi0xLjkwNmMxLjAxMTMgMC4yOTUgMy40NjE1IDAuNzY2IDUuNjU2LTAuOTM4IDAgMCAzLjkyOC0yLjU5NCAyLjA5NC03LjU5MzV6Ii8+Cjwvc3ZnPgo=',
widget: '<div class="rs-bubble rs-hidden"> <div class="rs-bubble-text remotestorage-initial remotestorage-error remotestorage-authing remotestorage-offline"> <span class="rs-status-text">{{view_connect}}</span> </div> <div class="rs-bubble-expandable"> <!-- error --> <div class="remotestorage-error"> <pre class="rs-status-text rs-error-msg">{{ERROR_MSG}}</pre> <button class="remotestorage-reset">{{view_get_me_out}}</button> <p class="rs-centered-text rs-error-plz-report">{{view_error_plz_report}}</p> </div> <!-- connected --> <div class="rs-bubble-text remotestorage-connected"> <strong class="userAddress">{{USER_ADDRESS}}</strong> <p class="remotestorage-unauthorized">{{view_unauthorized}}</p> <p class="remotestorage-invalid-key">{{view_invalid_key}}</p> <form novalidate class="remotestorage-cipher-form"> <input placeholder="Secret key" name="userSecretKey" novalidate> <button class="rs-cipher" name="rs-cipher" title="cipher" disabled="disabled"> <img> </button> <button class="rs-nocipher" name="rs-nocipher" title="no cipher"> <img> </button> </form> </div> <div class="rs-content remotestorage-connected"> <button class="rs-sync" title="sync"><img></button> <button class="rs-disconnect" title="disconnect"><img></button> </div> <!-- initial --> <form novalidate class="remotestorage-initial"> <input type="email" placeholder="[email protected]" name="userAddress" novalidate> <button class="connect" name="connect" title="connect" disabled="disabled"> <img> </button> </form> <div class="rs-info-msg remotestorage-initial">{{view_info}}</div> </div> </div> <img class="rs-dropbox rs-backends rs-action" alt="Connect to Dropbox"> <img class="rs-googledrive rs-backends rs-action" alt="Connect to Google Drive"> <img class="rs-cube rs-action"> ',
widgetCss: '/** encoding:utf-8 **/ /* RESET */ #remotestorage-widget{text-align:left;}#remotestorage-widget input, #remotestorage-widget button{font-size:11px;}#remotestorage-widget form input[type=email]{margin-bottom:0;/* HTML5 Boilerplate */}#remotestorage-widget form input[type=submit]{margin-top:0;/* HTML5 Boilerplate */}/* /RESET */ #remotestorage-widget, #remotestorage-widget *{-moz-box-sizing:border-box;box-sizing:border-box;}#remotestorage-widget{position:absolute;right:10px;top:10px;font:normal 16px/100% sans-serif !important;user-select:none;-webkit-user-select:none;-moz-user-select:-moz-none;cursor:default;z-index:10000;}#remotestorage-widget .rs-bubble{background:rgba(80, 80, 80, .7);border-radius:5px 15px 5px 5px;color:white;font-size:0.8em;padding:5px;position:absolute;right:3px;top:9px;min-height:24px;white-space:nowrap;text-decoration:none;}.rs-bubble .rs-bubble-text{padding-right:32px;/* make sure the bubble doesn\'t "jump" when initially opening. */ min-width:182px;}#remotestorage-widget .rs-action{cursor:pointer;}/* less obtrusive cube when connected */ #remotestorage-widget.remotestorage-state-connected .rs-cube, #remotestorage-widget.remotestorage-state-busy .rs-cube{opacity:.3;-webkit-transition:opacity .3s ease;-moz-transition:opacity .3s ease;-ms-transition:opacity .3s ease;-o-transition:opacity .3s ease;transition:opacity .3s ease;}#remotestorage-widget.remotestorage-state-connected:hover .rs-cube, #remotestorage-widget.remotestorage-state-busy:hover .rs-cube, #remotestorage-widget.remotestorage-state-connected .rs-bubble:not(.rs-hidden) + .rs-cube{opacity:1 !important;}#remotestorage-widget .rs-backends{position:relative;top:5px;right:0;}#remotestorage-widget .rs-cube{position:relative;top:5px;right:0;}/* pulsing animation for cube when loading */ #remotestorage-widget .rs-cube.remotestorage-loading{-webkit-animation:remotestorage-loading .5s ease-in-out infinite alternate;-moz-animation:remotestorage-loading .5s ease-in-out infinite alternate;-o-animation:remotestorage-loading .5s ease-in-out infinite alternate;-ms-animation:remotestorage-loading .5s ease-in-out infinite alternate;animation:remotestorage-loading .5s ease-in-out infinite alternate;}@-webkit-keyframes remotestorage-loading{to{opacity:.7}}@-moz-keyframes remotestorage-loading{to{opacity:.7}}@-o-keyframes remotestorage-loading{to{opacity:.7}}@-ms-keyframes remotestorage-loading{to{opacity:.7}}@keyframes remotestorage-loading{to{opacity:.7}}#remotestorage-widget a{text-decoration:underline;color:inherit;}#remotestorage-widget form{margin-top:.7em;position:relative;}#remotestorage-widget form input{display:table-cell;vertical-align:top;border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:2em;}#remotestorage-widget form input:disabled{color:#999;background:#444 !important;cursor:default !important;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget form input[type=email], #remotestorage-widget form input[type=password]{background:#000;width:100%;height:26px;padding:0 30px 0 5px;border-top:1px solid #111;border-bottom:1px solid #999;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget button:focus, #remotestorage-widget input:focus{box-shadow:0 0 4px #ccc;}#remotestorage-widget form input[type=email]::-webkit-input-placeholder, #remotestorage-widget form input[type=password]::-webkit-input-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-moz-placeholder, #remotestorage-widget form input[type=password]:-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]::-moz-placeholder, #remotestorage-widget form input[type=password]::-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-ms-input-placeholder, #remotestorage-widget form input[type=password]:-ms-input-placeholder{color:#999;}#remotestorage-widget form input[type=submit]{background:#000;cursor:pointer;padding:0 5px;}#remotestorage-widget form input[type=submit]:hover{background:#333;}#remotestorage-widget .rs-info-msg{font-size:10px;color:#eee;margin-top:0.7em;white-space:normal;}#remotestorage-widget .rs-info-msg.last-synced-message{display:inline;white-space:nowrap;margin-bottom:.7em}#remotestorage-widget .rs-info-msg a:hover, #remotestorage-widget .rs-info-msg a:active{color:#fff;}#remotestorage-widget button img{vertical-align:baseline;}#remotestorage-widget button{border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:26px;width:26px;background:#000;cursor:pointer;margin:0;padding:5px;}#remotestorage-widget button:hover{background:#333;}#remotestorage-widget .rs-bubble button.connect, #remotestorage-widget .rs-bubble button.rs-cipher, #remotestorage-widget .rs-bubble button.rs-nocipher{display:block;background:none;position:absolute;right:0;top:0;opacity:1;/* increase clickable area of connect, rs-cipher & rs-nocipher buttons */ margin:-5px;padding:10px;width:36px;height:36px;}#remotestorage-widget .rs-bubble button.rs-cipher{width:46px;}#remotestorage-widget .rs-bubble button.rs-nocipher{height:26px;margin:0;padding:4px 5px 5px;right:-32px;width:26px;}#remotestorage-widget .rs-bubble button.connect:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-cipher:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-nocipher:not([disabled]):hover{background:rgba(150,150,150,.5);}#remotestorage-widget .rs-bubble button.connect[disabled], #remotestorage-widget .rs-bubble button.rs-cipher[disabled]{opacity:.5;cursor:default !important;}#remotestorage-widget .rs-bubble button.rs-sync{position:relative;left:-5px;bottom:-5px;padding:4px 4px 0 4px;background:#555;}#remotestorage-widget .rs-bubble button.rs-sync:hover{background:#444;}#remotestorage-widget .rs-bubble button.rs-disconnect{background:#721;position:absolute;right:0;bottom:0;padding:4px 4px 0 4px;}#remotestorage-widget .rs-bubble button.rs-disconnect:hover{background:#921;}#remotestorage-widget .remotestorage-error-info{color:#f92;}#remotestorage-widget .remotestorage-reset{width:100%;background:#721;}#remotestorage-widget .remotestorage-reset:hover{background:#921;}#remotestorage-widget .rs-bubble .rs-content{margin-top:7px;}#remotestorage-widget pre{user-select:initial;-webkit-user-select:initial;-moz-user-select:text;max-width:27em;margin-top:1em;overflow:auto;}#remotestorage-widget .rs-centered-text{text-align:center;}#remotestorage-widget .rs-bubble.rs-hidden{padding-bottom:2px;border-radius:5px 15px 15px 5px;}#remotestorage-widget .rs-error-msg{min-height:5em;}.rs-bubble.rs-hidden .rs-bubble-expandable{display:none;}.remotestorage-state-connected .rs-bubble.rs-hidden{display:none;}.remotestorage-connected{display:none;}.remotestorage-state-connected .remotestorage-connected{display:block;}.remotestorage-cipher-form{display:none;}.remotestorage-cipher .remotestorage-cipher-form{display:block;}.remotestorage-invalid-key{display:none;}.remotestorage-invalid-key.remotestorage-cipher-error{display:block;}.remotestorage-initial{display:none;}.remotestorage-state-initial .remotestorage-initial{display:block;}.remotestorage-error{display:none;}.remotestorage-state-error .remotestorage-error{display:block;}.remotestorage-state-authing .remotestorage-authing{display:block;}.remotestorage-state-offline .remotestorage-connected, .remotestorage-state-offline .remotestorage-offline{display:block;}.remotestorage-unauthorized{display:none;}.remotestorage-state-unauthorized .rs-bubble.rs-hidden{display:none;}.remotestorage-state-unauthorized .remotestorage-connected, .remotestorage-state-unauthorized .remotestorage-unauthorized{display:block;}.remotestorage-state-unauthorized .rs-sync{display:none;}.remotestorage-state-busy .rs-bubble.rs-hidden{display:none;}.remotestorage-state-busy .rs-bubble{display:block;}.remotestorage-state-busy .remotestorage-connected{display:block;}.remotestorage-state-authing .rs-bubble-expandable{display:none;}'
};
/** FILE: src/widget.js **/
(function (window) {
var hasLocalStorage;
var LS_STATE_KEY = 'remotestorage:widget:state';
// states allowed to immediately jump into after a reload.
var VALID_ENTRY_STATES = {
initial: true,
connected: true,
offline: true
};
/**
* Class: RemoteStorage.Widget
*
* The widget controller that communicates with the view and listens to
* its remoteStorage instance.
*
* While listening to the events emitted by its remoteStorage it sets
* corresponding states of the view.
*
* - connected -> connected
* - disconnected -> initial
* - connecting -> authing
* - authing -> authing
* - wire-busy -> busy
* - wire-done -> connected
* - error -> one of initial, offline, unauthorized, or error
**/
RemoteStorage.Widget = function (remoteStorage) {
var self = this;
var requestsToFlashFor = 0;
// setting event listeners on rs events to put
// the widget into corresponding states
this.rs = remoteStorage;
this.rs.remote.on('connected', stateSetter(this, 'connected'));
this.rs.on('disconnected', stateSetter(this, 'initial'));
this.rs.on('connecting', stateSetter(this, 'authing'));
this.rs.on('authing', stateSetter(this, 'authing'));
this.rs.on('error', errorsHandler(this));
if (this.rs.remote) {
this.rs.remote.on('wire-busy', function (evt) {
if (flashFor(evt)) {
requestsToFlashFor++;
stateSetter(self, 'busy')();
}
});
this.rs.remote.on('wire-done', function (evt) {
if (flashFor(evt)) {
requestsToFlashFor--;
}
if (requestsToFlashFor <= 0 && evt.success) {
stateSetter(self, 'connected')();
}
});
}
if (hasLocalStorage) {
var state = localStorage[LS_STATE_KEY];
if (state && VALID_ENTRY_STATES[state]) {
this._rememberedState = state;
}
}
};
RemoteStorage.Widget.prototype = {
/**
* Method: display
*
* Displays the widget via the view.display method
*
* Parameters:
*
* options
**/
display: function (options) {
if (typeof(options) === 'string') {
options = { domID: options };
} else if (typeof(options) === 'undefined') {
options = {};
}
if (! this.view) {
this.setView(new RemoteStorage.Widget.View(this.rs));
}
this.view.display(options);
return this;
},
linkWidgetToSync: function () {
if (typeof(this.rs.sync) === 'object' && typeof(this.rs.sync.sync) === 'function') {
this.view.on('sync', this.rs.sync.sync.bind(this.rs.sync));
} else {
RemoteStorage.log('[Widget] typeof this.rs.sync check fail', this.rs.sync);
setTimeout(this.linkWidgetToSync.bind(this), 1000);
}
},
/**
* Method: setView(view)
*
* Sets the view and initializes event listeners to react on
* widget (widget.view) events
**/
setView: function (view) {
this.view = view;
this.view.on('connect', function (options) {
if (typeof(options) === 'string') {
// options is simply a useraddress
this.rs.connect(options);
} else if (options.special) {
this.rs[options.special].connect(options);
}
}.bind(this));
this.view.on('secret-entered', function (secretKey) {
this.view.setUserSecretKey(secretKey);
stateSetter(this, 'ciphered')();
}.bind(this));
this.view.on('secret-cancelled', function () {
stateSetter(this, 'notciphered')();
}.bind(this));
this.view.on('disconnect', this.rs.disconnect.bind(this.rs));
this.linkWidgetToSync();
try {
this.view.on('reset', function (){
var location = RemoteStorage.Authorize.getLocation();
this.rs.on('disconnected', location.reload.bind(location));
this.rs.disconnect();
}.bind(this));
} catch(e) {
if (!(e.message && e.message.match(/Unknown event/))) { // ignored. (the 0.7 widget-view interface didn't have a 'reset' event)
throw e;
}
}
if (this._rememberedState) {
setTimeout(stateSetter(this, this._rememberedState), 0);
delete this._rememberedState;
}
}
};
/**
* Method: displayWidget
*
* Same as <display>
**/
RemoteStorage.prototype.displayWidget = function (options) {
return this.widget.display(options);
};
RemoteStorage.Widget._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (! remoteStorage.widget) {
remoteStorage.widget = new RemoteStorage.Widget(remoteStorage);
}
};
RemoteStorage.Widget._rs_supported = function (remoteStorage) {
return typeof(document) !== 'undefined';
};
function stateSetter(widget, state, message) {
RemoteStorage.log('[Widget] Producing stateSetter for', state);
return function () {
RemoteStorage.log('[Widget] Setting state', state, message);
if (hasLocalStorage) {
localStorage[LS_STATE_KEY] = state;
}
if (widget.view) {
if (widget.rs.remote) {
widget.view.setUserAddress(widget.rs.remote.userAddress);
}
widget.view.setState(state, message);
} else {
widget._rememberedState = state;
}
};
}
function errorsHandler(widget) {
return function (error) {
var s;
if (error instanceof RemoteStorage.DiscoveryError) {
console.error('Discovery failed', error, '"' + error.message + '"');
s = stateSetter(widget, 'initial', error.message);
} else if (error instanceof RemoteStorage.SyncError) {
s = stateSetter(widget, 'offline');
} else if (error instanceof RemoteStorage.Unauthorized) {
s = stateSetter(widget, 'unauthorized');
} else {
RemoteStorage.log('[Widget] Unknown error');
s = stateSetter(widget, 'error', [error]);
}
s.apply();
};
}
function flashFor(evt) {
if (evt.method === 'GET' && evt.isFolder) {
return false;
}
return true;
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/view.js **/
(function (window){
var t = RemoteStorage.I18n.translate;
/**
* Class: RemoteStorage.Widget.View
*
* Controls the visible widget
*
* States:
*
* initial - not connected
* authing - in auth flow
* connected - connected to remote storage, not syncing at the moment
* ciphered - connected, with cipher
* notciphered - connected, without cipher
* busy - connected, syncing at the moment
* offline - connected, but no network connectivity
* error - connected, but sync error happened
* unauthorized - connected, but request returned 401
**/
RemoteStorage.Widget.View = function (remoteStorage) {
this.rs = remoteStorage;
if (typeof(document) === 'undefined') {
throw "Widget not supported";
}
RemoteStorage.eventHandling(this,
'connect',
'secret-entered',
'secret-cancelled',
'disconnect',
'sync',
'display',
'reset');
// Re-binding the event so they can be called from the window
for (var event in this.events){
this.events[event] = this.events[event].bind(this);
}
this.hideBubbleOnBodyClick = function (event) {
for (var p = event.target; p !== document.body; p = p.parentElement) {
if (p.id === 'remotestorage-widget') {
return;
}
}
this.hideBubble();
}.bind(this);
};
RemoteStorage.Widget.View.prototype = {
connectGdrive: function () {
this._emit('connect', { special: 'googledrive' });
},
connectDropbox: function (){
this._emit('connect', { special: 'dropbox'});
},
/**
* Method: setState
*
* Call the function that applies the state to the widget
*
* Parameters:
*
* state
* args
**/
setState: function (state, message) {
RemoteStorage.log('[View] widget.view.setState(',state,',',message,');');
var s = this.states[state];
if (typeof(s) === 'undefined') {
throw new Error("Bad State assigned to view: " + state);
}
s.apply(this, [message]);
},
/**
* Method: setUserAddress
*
* Set user address of the input field
**/
setUserAddress: function (addr) {
this.userAddress = addr || '';
var el;
if (this.div && (el = this.div.querySelector('form.remotestorage-initial').userAddress)) {
el.value = this.userAddress;
}
},
/**
* Method: setUserSecretKey
*
* Set user secret key
**/
setUserSecretKey: function (secretKey) {
this.userSecretKey = secretKey;
},
/**
* Method: toggleBubble
*
* Show the bubble when hidden and the other way around
**/
toggleBubble: function (event) {
if (this.bubble.className.search('rs-hidden') < 0) {
this.hideBubble(event);
} else {
this.showBubble(event);
}
},
/**
* Method: hideBubble
*
* Hide the bubble
**/
hideBubble: function (){
addClass(this.bubble, 'rs-hidden');
document.body.removeEventListener('click', this.hideBubbleOnBodyClick);
},
/**
* Method: showBubble
*
* Show the bubble
**/
showBubble: function (event){
removeClass(this.bubble, 'rs-hidden');
if (typeof(event) !== 'undefined') {
stopPropagation(event);
}
document.body.addEventListener('click', this.hideBubbleOnBodyClick);
if (this.div.querySelector('.remotestorage-connected').classList.contains('remotestorage-cipher') && !this.userSecretKey) {
this.bubble.querySelector('form.remotestorage-cipher-form').userSecretKey.focus();
} else {
this.bubble.querySelector('form.remotestorage-initial').userAddress.focus();
}
},
/**
* Method: display
*
* Draw the widget inside of the dom element with the id options.domID
*
* Parameters:
*
* options
*
* Returns:
*
* The widget div
**/
display: function (options) {
if (typeof this.div !== 'undefined') {
return this.div;
}
var element = document.createElement('div');
var style = document.createElement('style');
style.innerHTML = RemoteStorage.Assets.widgetCss;
element.id = "remotestorage-widget";
element.innerHTML = RemoteStorage.Assets.widget;
element.appendChild(style);
if (options.domID) {
var parent = document.getElementById(options.domID);
if (! parent) {
throw "Failed to find target DOM element with id=\"" + options.domID + "\"";
}
parent.appendChild(element);
} else {
document.body.appendChild(element);
}
// Sync button
setupButton(element, 'rs-sync', 'syncIcon', this.events.sync);
// Disconnect button
setupButton(element, 'rs-disconnect', 'disconnectIcon', this.events.disconnect);
// Get me out of here
setupButton(element, 'remotestorage-reset', undefined, this.events.reset);
// Connect button
var connectButton = setupButton(element, 'connect', 'connectIcon', this.events.connect);
// Handle connectButton state
this.form = element.querySelector('form.remotestorage-initial');
var el = this.form.userAddress;
el.addEventListener('load', handleButtonState);
el.addEventListener('keyup', handleButtonState);
if (this.userAddress) {
el.value = this.userAddress;
}
if (options.encryption) {
this.cipher = true;
var secretKeyInput = element.querySelector('form.remotestorage-cipher-form').userSecretKey;
// This is to avoid the 'password field on an insecured page' warning, when not used and on http (not https)
secretKeyInput.type = 'password';
// Cipher button
var cipherButton = setupButton(element, 'rs-cipher', 'cipherIcon', this.events['secret-entered']);
// Handle cipherButton state
secretKeyInput.addEventListener('load', handleButtonState);
secretKeyInput.addEventListener('keyup', handleButtonState);
// No cipher button
setupButton(element, 'rs-nocipher', 'nocipherIcon', this.events['secret-cancelled']);
}
// The cube
this.cube = setupButton(element, 'rs-cube', 'remoteStorageIcon', this.toggleBubble.bind(this));
// Google Drive and Dropbox icons
setupButton(element, 'rs-dropbox', 'dropbox', this.connectDropbox.bind(this));
setupButton(element, 'rs-googledrive', 'googledrive', this.connectGdrive.bind(this));
var bubbleDontCatch = { INPUT: true, BUTTON: true, IMG: true };
var eventListener = function (event) {
if (! bubbleDontCatch[event.target.tagName] && ! (this.div.classList.contains('remotestorage-state-unauthorized') )) {
this.showBubble(event);
}
}.bind(this);
this.bubble = setupButton(element, 'rs-bubble', undefined, eventListener);
this.hideBubble();
this.div = element;
this.states.initial.call(this);
this.events.display.call(this);
return this.div;
},
states: {
initial: function (message) {
var cube = this.cube;
var info = message || t("view_info");
cube.src = RemoteStorage.Assets.remoteStorageIcon;
this._renderTranslatedInitialContent();
if (message) {
cube.src = RemoteStorage.Assets.remoteStorageIconError;
removeClass(this.cube, 'remotestorage-loading');
this.showBubble();
// Show the red error cube for 5 seconds, then show the normal orange one again
setTimeout(function (){
cube.src = RemoteStorage.Assets.remoteStorageIcon;
},2000);
} else {
this.hideBubble();
}
this.div.className = "remotestorage-state-initial";
if (this.userSecretKey) {
delete this.userSecretKey;
}
// Google Drive and Dropbox icons
var backends = 1;
if (this._activateBackend('dropbox')) { backends += 1; }
if (this._activateBackend('googledrive')) { backends += 1; }
this.div.querySelector('.rs-bubble-text').style.paddingRight = backends*32+8+'px';
// If address not empty connect button enabled
var cb = this.div.querySelector('.connect');
if (this.form.userAddress.value) {
cb.removeAttribute('disabled');
}
var infoEl = this.div.querySelector('.rs-info-msg');
infoEl.innerHTML = info;
if (message) {
infoEl.classList.add('remotestorage-error-info');
} else {
infoEl.classList.remove('remotestorage-error-info');
}
},
authing: function () {
this.div.removeEventListener('click', this.events.connect);
this.div.className = "remotestorage-state-authing";
this.div.querySelector('.rs-status-text').innerHTML = t("view_connecting", this.userAddress);
addClass(this.cube, 'remotestorage-loading');
},
connected: function () {
var cube = this.cube;
this.div.className = "remotestorage-state-connected";
this.div.querySelector('.userAddress').innerHTML = this.userAddress;
cube.src = RemoteStorage.Assets.remoteStorageIcon;
removeClass(cube, 'remotestorage-loading');
if (this.cipher) {
if (this.userSecretKey) {
if (this.userSecretKeyError) {
cube.src = RemoteStorage.Assets.remoteStorageIconError;
addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
addClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
this.showBubble();
// Show the red error cube for 5 seconds, then show the normal orange one again
setTimeout(function (){
cube.src = RemoteStorage.Assets.remoteStorageIcon;
},5000);
} else {
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
cube.src = RemoteStorage.Assets.remoteStorageIconCiphered;
}
} else {
addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.showBubble();
}
}
var icons = {
googledrive: this.div.querySelector('.rs-googledrive'),
dropbox: this.div.querySelector('.rs-dropbox')
};
icons.googledrive.style.display = icons.dropbox.style.display = 'none';
if (icons[this.rs.backend]) {
icons[this.rs.backend].style.display = 'inline-block';
this.div.querySelector('.rs-bubble-text').style.paddingRight = 2*32+8+'px';
} else {
this.div.querySelector('.rs-bubble-text').style.paddingRight = 32+8+'px';
}
},
ciphered: function () {
this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value = '';
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.cube.src = RemoteStorage.Assets.remoteStorageIconCiphered;
this.hideBubble();
},
notciphered: function () {
this.cipher = false;
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.hideBubble();
},
busy: function () {
this.div.className = "remotestorage-state-busy";
addClass(this.cube, 'remotestorage-loading'); //TODO needs to be undone when is that neccesary
},
offline: function () {
this.div.className = "remotestorage-state-offline";
this.cube.src = RemoteStorage.Assets.remoteStorageIconOffline;
this.div.querySelector('.rs-status-text').innerHTML = t("view_offline");
},
error: function (err) {
var errorMsg = err;
this.div.className = "remotestorage-state-error";
this.div.querySelector('.rs-bubble-text').innerHTML = '<strong>'+t('view_error_occured')+'</strong>';
//FIXME I don't know what an DOMError is and my browser doesn't know too(how to handle this?)
if (err instanceof Error /*|| err instanceof DOMError*/) {
errorMsg = err.message + '\n\n' +
err.stack;
}
this.div.querySelector('.rs-error-msg').textContent = errorMsg;
this.cube.src = RemoteStorage.Assets.remoteStorageIconError;
this.showBubble();
},
unauthorized: function () {
this.div.className = "remotestorage-state-unauthorized";
this.cube.src = RemoteStorage.Assets.remoteStorageIconError;
this.showBubble();
this.div.addEventListener('click', this.events.connect);
}
},
events: {
/**
* Event: connect
*
* Emitted when the connect button is clicked
**/
connect: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('connect', this.div.querySelector('form.remotestorage-initial').userAddress.value);
},
/**
* Event: secret-entered
*
* Emitted when the cipher button is clicked
**/
'secret-entered': function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('secret-entered', this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value);
},
/**
* Event: secret-cancelled
*
* Emitted when the nocipher button is clicked
**/
'secret-cancelled': function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('secret-cancelled');
},
/**
* Event: sync
*
* Emitted when the sync button is clicked
**/
sync: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('sync');
},
/**
* Event: disconnect
*
* Emitted when the disconnect button is clicked
**/
disconnect: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('disconnect');
},
/**
* Event: reset
*
* Emitted after crash triggers disconnect
**/
reset: function (event){
event.preventDefault();
var result = window.confirm(t('view_confirm_reset'));
if (result){
this._emit('reset');
}
},
/**
* Event: display
*
* Emitted when finished displaying the widget
**/
display : function (event) {
if (event) {
event.preventDefault();
}
this._emit('display');
}
},
_renderTranslatedInitialContent: function () {
this.div.querySelector('.rs-status-text').innerHTML = t("view_connect");
this.div.querySelector('.remotestorage-reset').innerHTML = t("view_get_me_out");
this.div.querySelector('.rs-error-plz-report').innerHTML = t("view_error_plz_report");
this.div.querySelector('.remotestorage-unauthorized').innerHTML = t("view_unauthorized");
this.div.querySelector('.remotestorage-invalid-key').innerHTML = t("view_invalid_key");
},
_activateBackend: function activateBackend(backendName) {
var className = 'rs-' + backendName;
if (this.rs.apiKeys[backendName]) {
this.div.querySelector('.' + className).style.display = 'inline-block';
return true;
} else {
this.div.querySelector('.' + className).style.display = 'none';
return false;
}
}
};
function removeClass(el, className) {
return el.classList.remove(className);
}
function addClass(el, className) {
return el.classList.add(className);
}
function stopPropagation(event) {
if (typeof(event.stopPropagation) === 'function') {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
function setupButton(parent, className, iconName, eventListener) {
var element = parent.querySelector('.' + className);
if (typeof iconName !== 'undefined') {
var img = element.querySelector('img');
(img || element).src = RemoteStorage.Assets[iconName];
}
element.addEventListener('click', eventListener);
return element;
}
function handleButtonState(event) {
if (event.target.value) {
event.target.nextElementSibling.removeAttribute('disabled');
} else {
event.target.nextElementSibling.setAttribute('disabled','disabled');
}
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: node_modules/tv4/tv4.js **/
/*
Author: Geraint Luff and others
Year: 2013
This code is released into the "public domain" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code.
If you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory.
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module !== 'undefined' && module.exports){
// CommonJS. Define export.
module.exports = factory();
} else {
// Browser globals
global.tv4 = factory();
}
}(this, function () {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
throw new TypeError('Object.keys called on non-object');
}
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
})();
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
if (arguments.length !== 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Grungey Object.isFrozen hack
if (!Object.isFrozen) {
Object.isFrozen = function (obj) {
var key = "tv4_test_frozen_key";
while (obj.hasOwnProperty(key)) {
key += Math.random();
}
try {
obj[key] = true;
delete obj[key];
return false;
} catch (e) {
return true;
}
};
}
// Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed
var uriTemplateGlobalModifiers = {
"+": true,
"#": true,
".": true,
"/": true,
";": true,
"?": true,
"&": true
};
var uriTemplateSuffices = {
"*": true
};
function notReallyPercentEncode(string) {
return encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {
return "%" + doubleEncoded.substring(3);
});
}
function uriTemplateSubstitution(spec) {
var modifier = "";
if (uriTemplateGlobalModifiers[spec.charAt(0)]) {
modifier = spec.charAt(0);
spec = spec.substring(1);
}
var separator = "";
var prefix = "";
var shouldEscape = true;
var showVariables = false;
var trimEmptyString = false;
if (modifier === '+') {
shouldEscape = false;
} else if (modifier === ".") {
prefix = ".";
separator = ".";
} else if (modifier === "/") {
prefix = "/";
separator = "/";
} else if (modifier === '#') {
prefix = "#";
shouldEscape = false;
} else if (modifier === ';') {
prefix = ";";
separator = ";";
showVariables = true;
trimEmptyString = true;
} else if (modifier === '?') {
prefix = "?";
separator = "&";
showVariables = true;
} else if (modifier === '&') {
prefix = "&";
separator = "&";
showVariables = true;
}
var varNames = [];
var varList = spec.split(",");
var varSpecs = [];
var varSpecMap = {};
for (var i = 0; i < varList.length; i++) {
var varName = varList[i];
var truncate = null;
if (varName.indexOf(":") !== -1) {
var parts = varName.split(":");
varName = parts[0];
truncate = parseInt(parts[1], 10);
}
var suffices = {};
while (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {
suffices[varName.charAt(varName.length - 1)] = true;
varName = varName.substring(0, varName.length - 1);
}
var varSpec = {
truncate: truncate,
name: varName,
suffices: suffices
};
varSpecs.push(varSpec);
varSpecMap[varName] = varSpec;
varNames.push(varName);
}
var subFunction = function (valueFunction) {
var result = "";
var startIndex = 0;
for (var i = 0; i < varSpecs.length; i++) {
var varSpec = varSpecs[i];
var value = valueFunction(varSpec.name);
if (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) {
startIndex++;
continue;
}
if (i === startIndex) {
result += prefix;
} else {
result += (separator || ",");
}
if (Array.isArray(value)) {
if (showVariables) {
result += varSpec.name + "=";
}
for (var j = 0; j < value.length; j++) {
if (j > 0) {
result += varSpec.suffices['*'] ? (separator || ",") : ",";
if (varSpec.suffices['*'] && showVariables) {
result += varSpec.name + "=";
}
}
result += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, "%21") : notReallyPercentEncode(value[j]);
}
} else if (typeof value === "object") {
if (showVariables && !varSpec.suffices['*']) {
result += varSpec.name + "=";
}
var first = true;
for (var key in value) {
if (!first) {
result += varSpec.suffices['*'] ? (separator || ",") : ",";
}
first = false;
result += shouldEscape ? encodeURIComponent(key).replace(/!/g, "%21") : notReallyPercentEncode(key);
result += varSpec.suffices['*'] ? '=' : ",";
result += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, "%21") : notReallyPercentEncode(value[key]);
}
} else {
if (showVariables) {
result += varSpec.name;
if (!trimEmptyString || value !== "") {
result += "=";
}
}
if (varSpec.truncate != null) {
value = value.substring(0, varSpec.truncate);
}
result += shouldEscape ? encodeURIComponent(value).replace(/!/g, "%21"): notReallyPercentEncode(value);
}
}
return result;
};
subFunction.varNames = varNames;
return {
prefix: prefix,
substitution: subFunction
};
}
function UriTemplate(template) {
if (!(this instanceof UriTemplate)) {
return new UriTemplate(template);
}
var parts = template.split("{");
var textParts = [parts.shift()];
var prefixes = [];
var substitutions = [];
var varNames = [];
while (parts.length > 0) {
var part = parts.shift();
var spec = part.split("}")[0];
var remainder = part.substring(spec.length + 1);
var funcs = uriTemplateSubstitution(spec);
substitutions.push(funcs.substitution);
prefixes.push(funcs.prefix);
textParts.push(remainder);
varNames = varNames.concat(funcs.substitution.varNames);
}
this.fill = function (valueFunction) {
var result = textParts[0];
for (var i = 0; i < substitutions.length; i++) {
var substitution = substitutions[i];
result += substitution(valueFunction);
result += textParts[i + 1];
}
return result;
};
this.varNames = varNames;
this.template = template;
}
UriTemplate.prototype = {
toString: function () {
return this.template;
},
fillFromObject: function (obj) {
return this.fill(function (varName) {
return obj[varName];
});
}
};
var ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) {
this.missing = [];
this.missingMap = {};
this.formatValidators = parent ? Object.create(parent.formatValidators) : {};
this.schemas = parent ? Object.create(parent.schemas) : {};
this.collectMultiple = collectMultiple;
this.errors = [];
this.handleError = collectMultiple ? this.collectError : this.returnError;
if (checkRecursive) {
this.checkRecursive = true;
this.scanned = [];
this.scannedFrozen = [];
this.scannedFrozenSchemas = [];
this.scannedFrozenValidationErrors = [];
this.validatedSchemasKey = 'tv4_validation_id';
this.validationErrorsKey = 'tv4_validation_errors_id';
}
if (trackUnknownProperties) {
this.trackUnknownProperties = true;
this.knownPropertyPaths = {};
this.unknownPropertyPaths = {};
}
this.errorReporter = errorReporter || defaultErrorReporter('en');
if (typeof this.errorReporter === 'string') {
throw new Error('debug');
}
this.definedKeywords = {};
if (parent) {
for (var key in parent.definedKeywords) {
this.definedKeywords[key] = parent.definedKeywords[key].slice(0);
}
}
};
ValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) {
this.definedKeywords[keyword] = this.definedKeywords[keyword] || [];
this.definedKeywords[keyword].push(keywordFunction);
};
ValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) {
var error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors);
error.message = this.errorReporter(error, data, schema);
return error;
};
ValidatorContext.prototype.returnError = function (error) {
return error;
};
ValidatorContext.prototype.collectError = function (error) {
if (error) {
this.errors.push(error);
}
return null;
};
ValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) {
for (var i = startIndex; i < this.errors.length; i++) {
this.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath);
}
return this;
};
ValidatorContext.prototype.banUnknownProperties = function (data, schema) {
for (var unknownPath in this.unknownPropertyPaths) {
var error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, "", null, data, schema);
var result = this.handleError(error);
if (result) {
return result;
}
}
return null;
};
ValidatorContext.prototype.addFormat = function (format, validator) {
if (typeof format === 'object') {
for (var key in format) {
this.addFormat(key, format[key]);
}
return this;
}
this.formatValidators[format] = validator;
};
ValidatorContext.prototype.resolveRefs = function (schema, urlHistory) {
if (schema['$ref'] !== undefined) {
urlHistory = urlHistory || {};
if (urlHistory[schema['$ref']]) {
return this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema);
}
urlHistory[schema['$ref']] = true;
schema = this.getSchema(schema['$ref'], urlHistory);
}
return schema;
};
ValidatorContext.prototype.getSchema = function (url, urlHistory) {
var schema;
if (this.schemas[url] !== undefined) {
schema = this.schemas[url];
return this.resolveRefs(schema, urlHistory);
}
var baseUrl = url;
var fragment = "";
if (url.indexOf('#') !== -1) {
fragment = url.substring(url.indexOf("#") + 1);
baseUrl = url.substring(0, url.indexOf("#"));
}
if (typeof this.schemas[baseUrl] === 'object') {
schema = this.schemas[baseUrl];
var pointerPath = decodeURIComponent(fragment);
if (pointerPath === "") {
return this.resolveRefs(schema, urlHistory);
} else if (pointerPath.charAt(0) !== "/") {
return undefined;
}
var parts = pointerPath.split("/").slice(1);
for (var i = 0; i < parts.length; i++) {
var component = parts[i].replace(/~1/g, "/").replace(/~0/g, "~");
if (schema[component] === undefined) {
schema = undefined;
break;
}
schema = schema[component];
}
if (schema !== undefined) {
return this.resolveRefs(schema, urlHistory);
}
}
if (this.missing[baseUrl] === undefined) {
this.missing.push(baseUrl);
this.missing[baseUrl] = baseUrl;
this.missingMap[baseUrl] = baseUrl;
}
};
ValidatorContext.prototype.searchSchemas = function (schema, url) {
if (Array.isArray(schema)) {
for (var i = 0; i < schema.length; i++) {
this.searchSchemas(schema[i], url);
}
} else if (schema && typeof schema === "object") {
if (typeof schema.id === "string") {
if (isTrustedUrl(url, schema.id)) {
if (this.schemas[schema.id] === undefined) {
this.schemas[schema.id] = schema;
}
}
}
for (var key in schema) {
if (key !== "enum") {
if (typeof schema[key] === "object") {
this.searchSchemas(schema[key], url);
} else if (key === "$ref") {
var uri = getDocumentUri(schema[key]);
if (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) {
this.missingMap[uri] = uri;
}
}
}
}
}
};
ValidatorContext.prototype.addSchema = function (url, schema) {
//overload
if (typeof url !== 'string' || typeof schema === 'undefined') {
if (typeof url === 'object' && typeof url.id === 'string') {
schema = url;
url = schema.id;
}
else {
return;
}
}
if (url === getDocumentUri(url) + "#") {
// Remove empty fragment
url = getDocumentUri(url);
}
this.schemas[url] = schema;
delete this.missingMap[url];
normSchema(schema, url);
this.searchSchemas(schema, url);
};
ValidatorContext.prototype.getSchemaMap = function () {
var map = {};
for (var key in this.schemas) {
map[key] = this.schemas[key];
}
return map;
};
ValidatorContext.prototype.getSchemaUris = function (filterRegExp) {
var list = [];
for (var key in this.schemas) {
if (!filterRegExp || filterRegExp.test(key)) {
list.push(key);
}
}
return list;
};
ValidatorContext.prototype.getMissingUris = function (filterRegExp) {
var list = [];
for (var key in this.missingMap) {
if (!filterRegExp || filterRegExp.test(key)) {
list.push(key);
}
}
return list;
};
ValidatorContext.prototype.dropSchemas = function () {
this.schemas = {};
this.reset();
};
ValidatorContext.prototype.reset = function () {
this.missing = [];
this.missingMap = {};
this.errors = [];
};
ValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) {
var topLevel;
schema = this.resolveRefs(schema);
if (!schema) {
return null;
} else if (schema instanceof ValidationError) {
this.errors.push(schema);
return schema;
}
var startErrorCount = this.errors.length;
var frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null;
if (this.checkRecursive && data && typeof data === 'object') {
topLevel = !this.scanned.length;
if (data[this.validatedSchemasKey]) {
var schemaIndex = data[this.validatedSchemasKey].indexOf(schema);
if (schemaIndex !== -1) {
this.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]);
return null;
}
}
if (Object.isFrozen(data)) {
frozenIndex = this.scannedFrozen.indexOf(data);
if (frozenIndex !== -1) {
var frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema);
if (frozenSchemaIndex !== -1) {
this.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]);
return null;
}
}
}
this.scanned.push(data);
if (Object.isFrozen(data)) {
if (frozenIndex === -1) {
frozenIndex = this.scannedFrozen.length;
this.scannedFrozen.push(data);
this.scannedFrozenSchemas.push([]);
}
scannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length;
this.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema;
this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = [];
} else {
if (!data[this.validatedSchemasKey]) {
try {
Object.defineProperty(data, this.validatedSchemasKey, {
value: [],
configurable: true
});
Object.defineProperty(data, this.validationErrorsKey, {
value: [],
configurable: true
});
} catch (e) {
//IE 7/8 workaround
data[this.validatedSchemasKey] = [];
data[this.validationErrorsKey] = [];
}
}
scannedSchemasIndex = data[this.validatedSchemasKey].length;
data[this.validatedSchemasKey][scannedSchemasIndex] = schema;
data[this.validationErrorsKey][scannedSchemasIndex] = [];
}
}
var errorCount = this.errors.length;
var error = this.validateBasic(data, schema, dataPointerPath)
|| this.validateNumeric(data, schema, dataPointerPath)
|| this.validateString(data, schema, dataPointerPath)
|| this.validateArray(data, schema, dataPointerPath)
|| this.validateObject(data, schema, dataPointerPath)
|| this.validateCombinations(data, schema, dataPointerPath)
|| this.validateHypermedia(data, schema, dataPointerPath)
|| this.validateFormat(data, schema, dataPointerPath)
|| this.validateDefinedKeywords(data, schema, dataPointerPath)
|| null;
if (topLevel) {
while (this.scanned.length) {
var item = this.scanned.pop();
delete item[this.validatedSchemasKey];
}
this.scannedFrozen = [];
this.scannedFrozenSchemas = [];
}
if (error || errorCount !== this.errors.length) {
while ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) {
var dataPart = (dataPathParts && dataPathParts.length) ? "" + dataPathParts.pop() : null;
var schemaPart = (schemaPathParts && schemaPathParts.length) ? "" + schemaPathParts.pop() : null;
if (error) {
error = error.prefixWith(dataPart, schemaPart);
}
this.prefixErrors(errorCount, dataPart, schemaPart);
}
}
if (scannedFrozenSchemaIndex !== null) {
this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount);
} else if (scannedSchemasIndex !== null) {
data[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount);
}
return this.handleError(error);
};
ValidatorContext.prototype.validateFormat = function (data, schema) {
if (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) {
return null;
}
var errorMessage = this.formatValidators[schema.format].call(null, data, schema);
if (typeof errorMessage === 'string' || typeof errorMessage === 'number') {
return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema);
} else if (errorMessage && typeof errorMessage === 'object') {
return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || "?"}, errorMessage.dataPath || '', errorMessage.schemaPath || "/format", null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) {
for (var key in this.definedKeywords) {
if (typeof schema[key] === 'undefined') {
continue;
}
var validationFunctions = this.definedKeywords[key];
for (var i = 0; i < validationFunctions.length; i++) {
var func = validationFunctions[i];
var result = func(data, schema[key], schema, dataPointerPath);
if (typeof result === 'string' || typeof result === 'number') {
return this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key);
} else if (result && typeof result === 'object') {
var code = result.code;
if (typeof code === 'string') {
if (!ErrorCodes[code]) {
throw new Error('Undefined error code (use defineError): ' + code);
}
code = ErrorCodes[code];
} else if (typeof code !== 'number') {
code = ErrorCodes.KEYWORD_CUSTOM;
}
var messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || "?"};
var schemaPath = result.schemaPath || ("/" + key.replace(/~/g, '~0').replace(/\//g, '~1'));
return this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema);
}
}
}
return null;
};
function recursiveCompare(A, B) {
if (A === B) {
return true;
}
if (A && B && typeof A === "object" && typeof B === "object") {
if (Array.isArray(A) !== Array.isArray(B)) {
return false;
} else if (Array.isArray(A)) {
if (A.length !== B.length) {
return false;
}
for (var i = 0; i < A.length; i++) {
if (!recursiveCompare(A[i], B[i])) {
return false;
}
}
} else {
var key;
for (key in A) {
if (B[key] === undefined && A[key] !== undefined) {
return false;
}
}
for (key in B) {
if (A[key] === undefined && B[key] !== undefined) {
return false;
}
}
for (key in A) {
if (!recursiveCompare(A[key], B[key])) {
return false;
}
}
}
return true;
}
return false;
}
ValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) {
var error;
if (error = this.validateType(data, schema, dataPointerPath)) {
return error.prefixWith(null, "type");
}
if (error = this.validateEnum(data, schema, dataPointerPath)) {
return error.prefixWith(null, "type");
}
return null;
};
ValidatorContext.prototype.validateType = function validateType(data, schema) {
if (schema.type === undefined) {
return null;
}
var dataType = typeof data;
if (data === null) {
dataType = "null";
} else if (Array.isArray(data)) {
dataType = "array";
}
var allowedTypes = schema.type;
if (!Array.isArray(allowedTypes)) {
allowedTypes = [allowedTypes];
}
for (var i = 0; i < allowedTypes.length; i++) {
var type = allowedTypes[i];
if (type === dataType || (type === "integer" && dataType === "number" && (data % 1 === 0))) {
return null;
}
}
return this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join("/")}, '', '', null, data, schema);
};
ValidatorContext.prototype.validateEnum = function validateEnum(data, schema) {
if (schema["enum"] === undefined) {
return null;
}
for (var i = 0; i < schema["enum"].length; i++) {
var enumVal = schema["enum"][i];
if (recursiveCompare(data, enumVal)) {
return null;
}
}
return this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema);
};
ValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) {
return this.validateMultipleOf(data, schema, dataPointerPath)
|| this.validateMinMax(data, schema, dataPointerPath)
|| this.validateNaN(data, schema, dataPointerPath)
|| null;
};
var CLOSE_ENOUGH_LOW = Math.pow(2, -51);
var CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW;
ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {
var multipleOf = schema.multipleOf || schema.divisibleBy;
if (multipleOf === undefined) {
return null;
}
if (typeof data === "number") {
var remainder = (data/multipleOf)%1;
if (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {
return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) {
if (typeof data !== "number") {
return null;
}
if (schema.minimum !== undefined) {
if (data < schema.minimum) {
return this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema);
}
if (schema.exclusiveMinimum && data === schema.minimum) {
return this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema);
}
}
if (schema.maximum !== undefined) {
if (data > schema.maximum) {
return this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema);
}
if (schema.exclusiveMaximum && data === schema.maximum) {
return this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateNaN = function validateNaN(data, schema) {
if (typeof data !== "number") {
return null;
}
if (isNaN(data) === true || data === Infinity || data === -Infinity) {
return this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) {
return this.validateStringLength(data, schema, dataPointerPath)
|| this.validateStringPattern(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) {
if (typeof data !== "string") {
return null;
}
if (schema.minLength !== undefined) {
if (data.length < schema.minLength) {
return this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema);
}
}
if (schema.maxLength !== undefined) {
if (data.length > schema.maxLength) {
return this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) {
if (typeof data !== "string" || (typeof schema.pattern !== "string" && !(schema.pattern instanceof RegExp))) {
return null;
}
var regexp;
if (schema.pattern instanceof RegExp) {
regexp = schema.pattern;
}
else {
var body, flags = '';
// Check for regular expression literals
// @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5
var literal = schema.pattern.match(/^\/(.+)\/([img]*)$/);
if (literal) {
body = literal[1];
flags = literal[2];
}
else {
body = schema.pattern;
}
regexp = new RegExp(body, flags);
}
if (!regexp.test(data)) {
return this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) {
if (!Array.isArray(data)) {
return null;
}
return this.validateArrayLength(data, schema, dataPointerPath)
|| this.validateArrayUniqueItems(data, schema, dataPointerPath)
|| this.validateArrayItems(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) {
var error;
if (schema.minItems !== undefined) {
if (data.length < schema.minItems) {
error = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
if (schema.maxItems !== undefined) {
if (data.length > schema.maxItems) {
error = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) {
if (schema.uniqueItems) {
for (var i = 0; i < data.length; i++) {
for (var j = i + 1; j < data.length; j++) {
if (recursiveCompare(data[i], data[j])) {
var error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
}
}
return null;
};
ValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) {
if (schema.items === undefined) {
return null;
}
var error, i;
if (Array.isArray(schema.items)) {
for (i = 0; i < data.length; i++) {
if (i < schema.items.length) {
if (error = this.validateAll(data[i], schema.items[i], [i], ["items", i], dataPointerPath + "/" + i)) {
return error;
}
} else if (schema.additionalItems !== undefined) {
if (typeof schema.additionalItems === "boolean") {
if (!schema.additionalItems) {
error = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema));
if (this.handleError(error)) {
return error;
}
}
} else if (error = this.validateAll(data[i], schema.additionalItems, [i], ["additionalItems"], dataPointerPath + "/" + i)) {
return error;
}
}
}
} else {
for (i = 0; i < data.length; i++) {
if (error = this.validateAll(data[i], schema.items, [i], ["items"], dataPointerPath + "/" + i)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) {
if (typeof data !== "object" || data === null || Array.isArray(data)) {
return null;
}
return this.validateObjectMinMaxProperties(data, schema, dataPointerPath)
|| this.validateObjectRequiredProperties(data, schema, dataPointerPath)
|| this.validateObjectProperties(data, schema, dataPointerPath)
|| this.validateObjectDependencies(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) {
var keys = Object.keys(data);
var error;
if (schema.minProperties !== undefined) {
if (keys.length < schema.minProperties) {
error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
if (schema.maxProperties !== undefined) {
if (keys.length > schema.maxProperties) {
error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) {
if (schema.required !== undefined) {
for (var i = 0; i < schema.required.length; i++) {
var key = schema.required[i];
if (data[key] === undefined) {
var error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
}
return null;
};
ValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) {
var error;
for (var key in data) {
var keyPointerPath = dataPointerPath + "/" + key.replace(/~/g, '~0').replace(/\//g, '~1');
var foundMatch = false;
if (schema.properties !== undefined && schema.properties[key] !== undefined) {
foundMatch = true;
if (error = this.validateAll(data[key], schema.properties[key], [key], ["properties", key], keyPointerPath)) {
return error;
}
}
if (schema.patternProperties !== undefined) {
for (var patternKey in schema.patternProperties) {
var regexp = new RegExp(patternKey);
if (regexp.test(key)) {
foundMatch = true;
if (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], ["patternProperties", patternKey], keyPointerPath)) {
return error;
}
}
}
}
if (!foundMatch) {
if (schema.additionalProperties !== undefined) {
if (this.trackUnknownProperties) {
this.knownPropertyPaths[keyPointerPath] = true;
delete this.unknownPropertyPaths[keyPointerPath];
}
if (typeof schema.additionalProperties === "boolean") {
if (!schema.additionalProperties) {
error = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null);
if (this.handleError(error)) {
return error;
}
}
} else {
if (error = this.validateAll(data[key], schema.additionalProperties, [key], ["additionalProperties"], keyPointerPath)) {
return error;
}
}
} else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) {
this.unknownPropertyPaths[keyPointerPath] = true;
}
} else if (this.trackUnknownProperties) {
this.knownPropertyPaths[keyPointerPath] = true;
delete this.unknownPropertyPaths[keyPointerPath];
}
}
return null;
};
ValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) {
var error;
if (schema.dependencies !== undefined) {
for (var depKey in schema.dependencies) {
if (data[depKey] !== undefined) {
var dep = schema.dependencies[depKey];
if (typeof dep === "string") {
if (data[dep] === undefined) {
error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
if (this.handleError(error)) {
return error;
}
}
} else if (Array.isArray(dep)) {
for (var i = 0; i < dep.length; i++) {
var requiredKey = dep[i];
if (data[requiredKey] === undefined) {
error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
if (this.handleError(error)) {
return error;
}
}
}
} else {
if (error = this.validateAll(data, dep, [], ["dependencies", depKey], dataPointerPath)) {
return error;
}
}
}
}
}
return null;
};
ValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) {
return this.validateAllOf(data, schema, dataPointerPath)
|| this.validateAnyOf(data, schema, dataPointerPath)
|| this.validateOneOf(data, schema, dataPointerPath)
|| this.validateNot(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) {
if (schema.allOf === undefined) {
return null;
}
var error;
for (var i = 0; i < schema.allOf.length; i++) {
var subSchema = schema.allOf[i];
if (error = this.validateAll(data, subSchema, [], ["allOf", i], dataPointerPath)) {
return error;
}
}
return null;
};
ValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) {
if (schema.anyOf === undefined) {
return null;
}
var errors = [];
var startErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
}
var errorAtEnd = true;
for (var i = 0; i < schema.anyOf.length; i++) {
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var subSchema = schema.anyOf[i];
var errorCount = this.errors.length;
var error = this.validateAll(data, subSchema, [], ["anyOf", i], dataPointerPath);
if (error === null && errorCount === this.errors.length) {
this.errors = this.errors.slice(0, startErrorCount);
if (this.trackUnknownProperties) {
for (var knownKey in this.knownPropertyPaths) {
oldKnownPropertyPaths[knownKey] = true;
delete oldUnknownPropertyPaths[knownKey];
}
for (var unknownKey in this.unknownPropertyPaths) {
if (!oldKnownPropertyPaths[unknownKey]) {
oldUnknownPropertyPaths[unknownKey] = true;
}
}
// We need to continue looping so we catch all the property definitions, but we don't want to return an error
errorAtEnd = false;
continue;
}
return null;
}
if (error) {
errors.push(error.prefixWith(null, "" + i).prefixWith(null, "anyOf"));
}
}
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (errorAtEnd) {
errors = errors.concat(this.errors.slice(startErrorCount));
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ANY_OF_MISSING, {}, "", "/anyOf", errors, data, schema);
}
};
ValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) {
if (schema.oneOf === undefined) {
return null;
}
var validIndex = null;
var errors = [];
var startErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
}
for (var i = 0; i < schema.oneOf.length; i++) {
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var subSchema = schema.oneOf[i];
var errorCount = this.errors.length;
var error = this.validateAll(data, subSchema, [], ["oneOf", i], dataPointerPath);
if (error === null && errorCount === this.errors.length) {
if (validIndex === null) {
validIndex = i;
} else {
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, "", "/oneOf", null, data, schema);
}
if (this.trackUnknownProperties) {
for (var knownKey in this.knownPropertyPaths) {
oldKnownPropertyPaths[knownKey] = true;
delete oldUnknownPropertyPaths[knownKey];
}
for (var unknownKey in this.unknownPropertyPaths) {
if (!oldKnownPropertyPaths[unknownKey]) {
oldUnknownPropertyPaths[unknownKey] = true;
}
}
}
} else if (error) {
errors.push(error);
}
}
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (validIndex === null) {
errors = errors.concat(this.errors.slice(startErrorCount));
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ONE_OF_MISSING, {}, "", "/oneOf", errors, data, schema);
} else {
this.errors = this.errors.slice(0, startErrorCount);
}
return null;
};
ValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) {
if (schema.not === undefined) {
return null;
}
var oldErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var error = this.validateAll(data, schema.not, null, null, dataPointerPath);
var notErrors = this.errors.slice(oldErrorCount);
this.errors = this.errors.slice(0, oldErrorCount);
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (error === null && notErrors.length === 0) {
return this.createError(ErrorCodes.NOT_PASSED, {}, "", "/not", null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) {
if (!schema.links) {
return null;
}
var error;
for (var i = 0; i < schema.links.length; i++) {
var ldo = schema.links[i];
if (ldo.rel === "describedby") {
var template = new UriTemplate(ldo.href);
var allPresent = true;
for (var j = 0; j < template.varNames.length; j++) {
if (!(template.varNames[j] in data)) {
allPresent = false;
break;
}
}
if (allPresent) {
var schemaUrl = template.fillFromObject(data);
var subSchema = {"$ref": schemaUrl};
if (error = this.validateAll(data, subSchema, [], ["links", i], dataPointerPath)) {
return error;
}
}
}
}
};
// parseURI() and resolveUrl() are from https://gist.github.com/1088850
// - released as public domain by author ("Yaffle") - see comments on gist
function parseURI(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);
}
function resolveUrl(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;
}
function getDocumentUri(uri) {
return uri.split('#')[0];
}
function normSchema(schema, baseUri) {
if (schema && typeof schema === "object") {
if (baseUri === undefined) {
baseUri = schema.id;
} else if (typeof schema.id === "string") {
baseUri = resolveUrl(baseUri, schema.id);
schema.id = baseUri;
}
if (Array.isArray(schema)) {
for (var i = 0; i < schema.length; i++) {
normSchema(schema[i], baseUri);
}
} else {
if (typeof schema['$ref'] === "string") {
schema['$ref'] = resolveUrl(baseUri, schema['$ref']);
}
for (var key in schema) {
if (key !== "enum") {
normSchema(schema[key], baseUri);
}
}
}
}
}
function defaultErrorReporter(language) {
language = language || 'en';
var errorMessages = languages[language];
return function (error) {
var messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code];
if (typeof messageTemplate !== 'string') {
return "Unknown error code " + error.code + ": " + JSON.stringify(error.messageParams);
}
var messageParams = error.params;
// Adapted from Crockford's supplant()
return messageTemplate.replace(/\{([^{}]*)\}/g, function (whole, varName) {
var subValue = messageParams[varName];
return typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole;
});
};
}
var ErrorCodes = {
INVALID_TYPE: 0,
ENUM_MISMATCH: 1,
ANY_OF_MISSING: 10,
ONE_OF_MISSING: 11,
ONE_OF_MULTIPLE: 12,
NOT_PASSED: 13,
// Numeric errors
NUMBER_MULTIPLE_OF: 100,
NUMBER_MINIMUM: 101,
NUMBER_MINIMUM_EXCLUSIVE: 102,
NUMBER_MAXIMUM: 103,
NUMBER_MAXIMUM_EXCLUSIVE: 104,
NUMBER_NOT_A_NUMBER: 105,
// String errors
STRING_LENGTH_SHORT: 200,
STRING_LENGTH_LONG: 201,
STRING_PATTERN: 202,
// Object errors
OBJECT_PROPERTIES_MINIMUM: 300,
OBJECT_PROPERTIES_MAXIMUM: 301,
OBJECT_REQUIRED: 302,
OBJECT_ADDITIONAL_PROPERTIES: 303,
OBJECT_DEPENDENCY_KEY: 304,
// Array errors
ARRAY_LENGTH_SHORT: 400,
ARRAY_LENGTH_LONG: 401,
ARRAY_UNIQUE: 402,
ARRAY_ADDITIONAL_ITEMS: 403,
// Custom/user-defined errors
FORMAT_CUSTOM: 500,
KEYWORD_CUSTOM: 501,
// Schema structure
CIRCULAR_REFERENCE: 600,
// Non-standard validation options
UNKNOWN_PROPERTY: 1000
};
var ErrorCodeLookup = {};
for (var key in ErrorCodes) {
ErrorCodeLookup[ErrorCodes[key]] = key;
}
var ErrorMessagesDefault = {
INVALID_TYPE: "Invalid type: {type} (expected {expected})",
ENUM_MISMATCH: "No enum match for: {value}",
ANY_OF_MISSING: "Data does not match any schemas from \"anyOf\"",
ONE_OF_MISSING: "Data does not match any schemas from \"oneOf\"",
ONE_OF_MULTIPLE: "Data is valid against more than one schema from \"oneOf\": indices {index1} and {index2}",
NOT_PASSED: "Data matches schema from \"not\"",
// Numeric errors
NUMBER_MULTIPLE_OF: "Value {value} is not a multiple of {multipleOf}",
NUMBER_MINIMUM: "Value {value} is less than minimum {minimum}",
NUMBER_MINIMUM_EXCLUSIVE: "Value {value} is equal to exclusive minimum {minimum}",
NUMBER_MAXIMUM: "Value {value} is greater than maximum {maximum}",
NUMBER_MAXIMUM_EXCLUSIVE: "Value {value} is equal to exclusive maximum {maximum}",
NUMBER_NOT_A_NUMBER: "Value {value} is not a valid number",
// String errors
STRING_LENGTH_SHORT: "String is too short ({length} chars), minimum {minimum}",
STRING_LENGTH_LONG: "String is too long ({length} chars), maximum {maximum}",
STRING_PATTERN: "String does not match pattern: {pattern}",
// Object errors
OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({propertyCount}), minimum {minimum}",
OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({propertyCount}), maximum {maximum}",
OBJECT_REQUIRED: "Missing required property: {key}",
OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed",
OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {missing} (due to key: {key})",
// Array errors
ARRAY_LENGTH_SHORT: "Array is too short ({length}), minimum {minimum}",
ARRAY_LENGTH_LONG: "Array is too long ({length}), maximum {maximum}",
ARRAY_UNIQUE: "Array items are not unique (indices {match1} and {match2})",
ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed",
// Format errors
FORMAT_CUSTOM: "Format validation failed ({message})",
KEYWORD_CUSTOM: "Keyword failed: {key} ({message})",
// Schema structure
CIRCULAR_REFERENCE: "Circular $refs: {urls}",
// Non-standard validation options
UNKNOWN_PROPERTY: "Unknown property (not in schema)"
};
function ValidationError(code, params, dataPath, schemaPath, subErrors) {
Error.call(this);
if (code === undefined) {
throw new Error ("No error code supplied: " + schemaPath);
}
this.message = '';
this.params = params;
this.code = code;
this.dataPath = dataPath || "";
this.schemaPath = schemaPath || "";
this.subErrors = subErrors || null;
var err = new Error(this.message);
this.stack = err.stack || err.stacktrace;
if (!this.stack) {
try {
throw err;
}
catch(err) {
this.stack = err.stack || err.stacktrace;
}
}
}
ValidationError.prototype = Object.create(Error.prototype);
ValidationError.prototype.constructor = ValidationError;
ValidationError.prototype.name = 'ValidationError';
ValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) {
if (dataPrefix !== null) {
dataPrefix = dataPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
this.dataPath = "/" + dataPrefix + this.dataPath;
}
if (schemaPrefix !== null) {
schemaPrefix = schemaPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
this.schemaPath = "/" + schemaPrefix + this.schemaPath;
}
if (this.subErrors !== null) {
for (var i = 0; i < this.subErrors.length; i++) {
this.subErrors[i].prefixWith(dataPrefix, schemaPrefix);
}
}
return this;
};
function isTrustedUrl(baseUrl, testUrl) {
if(testUrl.substring(0, baseUrl.length) === baseUrl){
var remainder = testUrl.substring(baseUrl.length);
if ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === "/")
|| remainder.charAt(0) === "#"
|| remainder.charAt(0) === "?") {
return true;
}
}
return false;
}
var languages = {};
function createApi(language) {
var globalContext = new ValidatorContext();
var currentLanguage;
var customErrorReporter;
var api = {
setErrorReporter: function (reporter) {
if (typeof reporter === 'string') {
return this.language(reporter);
}
customErrorReporter = reporter;
return true;
},
addFormat: function () {
globalContext.addFormat.apply(globalContext, arguments);
},
language: function (code) {
if (!code) {
return currentLanguage;
}
if (!languages[code]) {
code = code.split('-')[0]; // fall back to base language
}
if (languages[code]) {
currentLanguage = code;
return code; // so you can tell if fall-back has happened
}
return false;
},
addLanguage: function (code, messageMap) {
var key;
for (key in ErrorCodes) {
if (messageMap[key] && !messageMap[ErrorCodes[key]]) {
messageMap[ErrorCodes[key]] = messageMap[key];
}
}
var rootCode = code.split('-')[0];
if (!languages[rootCode]) { // use for base language if not yet defined
languages[code] = messageMap;
languages[rootCode] = messageMap;
} else {
languages[code] = Object.create(languages[rootCode]);
for (key in messageMap) {
if (typeof languages[rootCode][key] === 'undefined') {
languages[rootCode][key] = messageMap[key];
}
languages[code][key] = messageMap[key];
}
}
return this;
},
freshApi: function (language) {
var result = createApi();
if (language) {
result.language(language);
}
return result;
},
validate: function (data, schema, checkRecursive, banUnknownProperties) {
var def = defaultErrorReporter(currentLanguage);
var errorReporter = customErrorReporter ? function (error, data, schema) {
return customErrorReporter(error, data, schema) || def(error, data, schema);
} : def;
var context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties);
if (typeof schema === "string") {
schema = {"$ref": schema};
}
context.addSchema("", schema);
var error = context.validateAll(data, schema, null, null, "");
if (!error && banUnknownProperties) {
error = context.banUnknownProperties(data, schema);
}
this.error = error;
this.missing = context.missing;
this.valid = (error === null);
return this.valid;
},
validateResult: function () {
var result = {};
this.validate.apply(result, arguments);
return result;
},
validateMultiple: function (data, schema, checkRecursive, banUnknownProperties) {
var def = defaultErrorReporter(currentLanguage);
var errorReporter = customErrorReporter ? function (error, data, schema) {
return customErrorReporter(error, data, schema) || def(error, data, schema);
} : def;
var context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties);
if (typeof schema === "string") {
schema = {"$ref": schema};
}
context.addSchema("", schema);
context.validateAll(data, schema, null, null, "");
if (banUnknownProperties) {
context.banUnknownProperties(data, schema);
}
var result = {};
result.errors = context.errors;
result.missing = context.missing;
result.valid = (result.errors.length === 0);
return result;
},
addSchema: function () {
return globalContext.addSchema.apply(globalContext, arguments);
},
getSchema: function () {
return globalContext.getSchema.apply(globalContext, arguments);
},
getSchemaMap: function () {
return globalContext.getSchemaMap.apply(globalContext, arguments);
},
getSchemaUris: function () {
return globalContext.getSchemaUris.apply(globalContext, arguments);
},
getMissingUris: function () {
return globalContext.getMissingUris.apply(globalContext, arguments);
},
dropSchemas: function () {
globalContext.dropSchemas.apply(globalContext, arguments);
},
defineKeyword: function () {
globalContext.defineKeyword.apply(globalContext, arguments);
},
defineError: function (codeName, codeNumber, defaultMessage) {
if (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {
throw new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');
}
if (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {
throw new Error('Code number must be an integer > 10000');
}
if (typeof ErrorCodes[codeName] !== 'undefined') {
throw new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);
}
if (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {
throw new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);
}
ErrorCodes[codeName] = codeNumber;
ErrorCodeLookup[codeNumber] = codeName;
ErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;
for (var langCode in languages) {
var language = languages[langCode];
if (language[codeName]) {
language[codeNumber] = language[codeNumber] || language[codeName];
}
}
},
reset: function () {
globalContext.reset();
this.error = null;
this.missing = [];
this.valid = true;
},
missing: [],
error: null,
valid: true,
normSchema: normSchema,
resolveUrl: resolveUrl,
getDocumentUri: getDocumentUri,
errorCodes: ErrorCodes
};
api.language(language || 'en');
return api;
}
var tv4 = createApi();
tv4.addLanguage('en-gb', ErrorMessagesDefault);
//legacy property
tv4.tv4 = tv4;
return tv4; // used by _header.js to globalise.
}));
/** FILE: lib/Math.uuid.js **/
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:[email protected]
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
********
Changes within remoteStorage.js:
2012-10-31:
- added AMD wrapper <[email protected]>
- moved extensions for Math object into exported object.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
Math.uuid = function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
/** FILE: src/baseclient.js **/
(function (global) {
function deprecate(thing, replacement) {
console.log('WARNING: ' + thing + ' is deprecated. Use ' +
replacement + ' instead.');
}
var RS = RemoteStorage;
/**
* Class: RemoteStorage.BaseClient
*
* Provides a high-level interface to access data below a given root path.
*
* A BaseClient deals with three types of data: folders, objects and files.
*
* <getListing> returns a mapping of all items within a folder. Items that
* end with a forward slash ("/") are child folders. For instance:
* {
* 'folder/': true,
* 'document.txt': true
* }
*
* <getObject> / <storeObject> operate on JSON objects. Each object has a type.
*
* <getFile> / <storeFile> operates on files. Each file has a MIME type.
*
* <remove> operates on either objects or files (but not folders, folders are
* created and removed implictly).
*/
RS.BaseClient = function (storage, base) {
if (base[base.length - 1] !== '/') {
throw "Not a folder: " + base;
}
if (base === '/') {
// allow absolute and relative paths for the root scope.
this.makePath = function (path) {
return (path[0] === '/' ? '' : '/') + path;
};
}
/**
* Property: storage
*
* The <RemoteStorage> instance this <BaseClient> operates on.
*/
this.storage = storage;
/**
* Property: base
*
* Base path this <BaseClient> operates on.
*
* For the module's privateClient this would be /<moduleName>/, for the
* corresponding publicClient /public/<moduleName>/.
*/
this.base = base;
var parts = this.base.split('/');
if (parts.length > 2) {
this.moduleName = parts[1];
} else {
this.moduleName = 'root';
}
// Defined in baseclient/types.js
/**
* Property: schemas
*
* Contains schema objects of all types known to the BaseClient instance
**/
/**
* Event: change
*
* Emitted when a node changes
*
* Arguments:
* event - Event object containing information about the changed node
*
* (start code)
* {
* path: path, // Absolute path of the changed node, from the storage root
* relativePath: relativePath, // Path of the changed node, relative to this baseclient's scope root
* origin: 'window', 'local', 'remote', or 'conflict' // emitted by user action within the app, local data store, remote sync, or versioning conflicts
* oldValue: oldBody, // Old body of the changed node (local version in conflicts; undefined if creation)
* newValue: newBody, // New body of the changed node (remote version in conflicts; undefined if deletion)
* lastCommonValue: lastCommonValue, //most recent known common ancestor body of 'yours' and 'theirs' in case of conflict
* oldContentType: oldContentType, // Old contentType of the changed node ('yours' for conflicts; undefined if creation)
* newContentType: newContentType, // New contentType of the changed node ('theirs' for conflicts; undefined if deletion)
* lastCommonContentType: lastCommonContentType // Most recent known common ancestor contentType of 'yours' and 'theirs' in case of conflict
* }
* (end code)
*
* Example of an event with origin 'local' (fired on page load):
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'local',
* oldValue: undefined,
* newValue: 'white',
* oldContentType: undefined,
* newContentType: 'text/plain'
* }
* (end code)
*
* Example of a conflict:
* Say you changed 'color.txt' from 'white' to 'blue'; if you have set `RemoteStorage.config.changeEvents.window` to `true`,
* then you will receive:
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'window',
* oldValue: 'white',
* newValue: 'blue',
* oldContentType: 'text/plain',
* newContentType: 'text/plain'
* }
* (end code)
*
* But when this change is pushed out by asynchronous synchronization, this change may rejected by the
* server, if the remote version has in the meantime changed from 'white' to for instance 'red'; this will then lead to a change
* event with origin 'conflict' (usually a few seconds after the event with origin 'window', if you had that activated). Note
* that since you already changed it from 'white' to 'blue' in the local version a few seconds ago, `oldValue` is now your local
* value of 'blue':
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'conflict',
* oldValue: 'blue',
* newValue: 'red',
* lastCommonValue: 'white',
* oldContentType: 'text/plain,
* newContentType: 'text/plain'
* lastCommonContentType: 'text/plain'
* }
* (end code)
*
* In practice, you should always redraw your views to display the content of the `newValue` field when a change event is received,
* regardless of its origin. Events with origin 'local' are fired conveniently during the page load, so that you can fill your views
* when the page loads. Events with origin 'window' are fired whenever you change a value by calling a method on the baseClient;
* these are disabled by default. Events with origin 'remote' are fired when remote changes are discovered during sync (only for caching
* startegies 'SEEN' and 'ALL'). Events with origin 'conflict' are fired when a conflict occurs while pushing out your local changes to
* the remote store in asynchronous synchronization (see example above).
**/
RS.eventHandling(this, 'change');
this.on = this.on.bind(this);
storage.onChange(this.base, this._fireChange.bind(this));
};
RS.BaseClient.prototype = {
extend: function (object) {
for (var key in object) {
this[key] = object[key];
}
return this;
},
/**
* Method: scope
*
* Returns a new <BaseClient> operating on a subpath of the current <base> path.
*/
scope: function (path) {
return new RS.BaseClient(this.storage, this.makePath(path));
},
// folder operations
/**
* Method: getListing
*
* Get a list of child nodes below a given path.
*
* The callback semantics of getListing are identical to those of getObject.
*
* Parameters:
* path - The path to query. It MUST end with a forward slash.
* maxAge - Either false or the maximum age of cached listing in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
*
* A promise for an object, representing child nodes. If the maxAge
* requirement cannot be met because of network problems, this promise
* will be rejected. If the maxAge requirement is set to false or the
* library is in offline state, the promise will always be fulfilled with
* data from the local store.
*
* Keys ending in a forward slash represent *folder nodes*, while all
* other keys represent *data nodes*.
*
* For spec versions <= 01, the data node information will contain only
* the item's ETag. For later spec versions, it will also contain the
* content type and -length of the item.
*
* Example:
* (start code)
* client.getListing('', false).then(function (listing) {
* // listing is for instance:
* // {
* // 'folder/': true,
* // 'document.txt': true
* // }
* });
* (end code)
*/
getListing: function (path, maxAge) {
if (typeof(path) !== 'string') {
path = '';
} else if (path.length > 0 && path[path.length - 1] !== '/') {
return Promise.reject("Not a folder: " + path);
}
return this.storage.get(this.makePath(path), maxAge).then(
function (r) {
return (r.statusCode === 404) ? {} : r.body;
}
);
},
/**
* Method: getAll
*
* Get all objects directly below a given path.
*
* Parameters:
* path - Path to the folder.
* maxAge - Either false or the maximum age of cached objects in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for an object in the form { path : object, ... }. If the
* maxAge requirement cannot be met because of network problems, this
* promise will be rejected. If the maxAge requirement is set to false,
* the promise will always be fulfilled with data from the local store.
*
* For items that are not JSON-stringified objects (e.g. stored using
* `storeFile` instead of `storeObject`), the object's value is filled in
* with `true`.
*
* Example:
* (start code)
* client.getAll('', false).then(function (objects) {
* for (var key in objects) {
* console.log('- ' + key + ': ', objects[key]);
* }
* });
* (end code)
*/
getAll: function (path, maxAge) {
if (typeof(path) !== 'string') {
path = '';
} else if (path.length > 0 && path[path.length - 1] !== '/') {
return Promise.reject("Not a folder: " + path);
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
if (r.statusCode === 404) { return {}; }
if (typeof(r.body) === 'object') {
var keys = Object.keys(r.body);
if (keys.length === 0) {
// treat this like 404. it probably means a folder listing that
// has changes that haven't been pushed out yet.
return {};
}
var calls = keys.map(function (key) {
return this.storage.get(this.makePath(path + key), maxAge)
.then(function (o) {
if (typeof(o.body) === 'string') {
try {
o.body = JSON.parse(o.body);
} catch (e) {
}
}
if (typeof(o.body) === 'object') {
r.body[key] = o.body;
}
});
}.bind(this));
return Promise.all(calls).then(function () {
return r.body;
});
}
}.bind(this));
},
// file operations
/**
* Method: getFile
*
* Get the file at the given path. A file is raw data, as opposed to
* a JSON object (use <getObject> for that).
*
* Except for the return value structure, getFile works exactly like
* getObject.
*
* Parameters:
* path - See getObject.
* maxAge - Either false or the maximum age of cached file in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for an object:
*
* mimeType - String representing the MIME Type of the document.
* data - Raw data of the document (either a string or an ArrayBuffer)
*
* If the maxAge requirement cannot be met because of network problems, this
* promise will be rejected. If the maxAge requirement is set to false, the
* promise will always be fulfilled with data from the local store.
*
* Example:
* (start code)
* // Display an image:
* client.getFile('path/to/some/image', false).then(function (file) {
* var blob = new Blob([file.data], { type: file.mimeType });
* var targetElement = document.findElementById('my-image-element');
* targetElement.src = window.URL.createObjectURL(blob);
* });
* (end code)
*/
getFile: function (path, maxAge) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.getFile must be a string');
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
return {
data: r.body,
contentType: r.contentType,
revision: r.revision // (this is new)
};
});
},
/**
* Method: storeFile
*
* Store raw data at a given path.
*
* Parameters:
* mimeType - MIME media type of the data being stored
* path - path relative to the module root. MAY NOT end in a forward slash.
* data - string, ArrayBuffer or ArrayBufferView of raw data to store
*
* The given mimeType will later be returned, when retrieving the data
* using <getFile>.
*
* Example (UTF-8 data):
* (start code)
* client.storeFile('text/html', 'index.html', '<h1>Hello World!</h1>');
* (end code)
*
* Example (Binary data):
* (start code)
* // MARKUP:
* <input type="file" id="file-input">
* // CODE:
* var input = document.getElementById('file-input');
* var file = input.files[0];
* var fileReader = new FileReader();
*
* fileReader.onload = function () {
* client.storeFile(file.type, file.name, fileReader.result);
* };
*
* fileReader.readAsArrayBuffer(file);
* (end code)
*
*/
storeFile: function (mimeType, path, body) {
if (typeof(mimeType) !== 'string') {
return Promise.reject('Argument \'mimeType\' of baseClient.storeFile must be a string');
}
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.storeFile must be a string');
}
if (typeof(body) !== 'string' && typeof(body) !== 'object') {
return Promise.reject('Argument \'body\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView');
}
if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {
console.warn('WARNING: Editing a document to which only read access (\'r\') was claimed');
}
return this.storage.put(this.makePath(path), body, mimeType).then(function (r) {
if (r.statusCode === 200 || r.statusCode === 201) {
return r.revision;
} else {
return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode);
}
}.bind(this));
},
// object operations
/**
* Method: getObject
*
* Get a JSON object from given path.
*
* Parameters:
* path - Relative path from the module root (without leading slash).
* maxAge - Either false or the maximum age of cached object in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for the object. If the maxAge requirement cannot be met
* because of network problems, this promise will be rejected. If the
* maxAge requirement is set to false, the promise will always be
* fulfilled with data from the local store.
*
* Example:
* (start code)
* client.getObject('/path/to/object', false).
* then(function (object) {
* // object is either an object or null
* });
* (end code)
*/
getObject: function (path, maxAge) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.getObject must be a string');
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
if (typeof(r.body) === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2
return r.body;
} else if (typeof(r.body) === 'string') {
try {
return JSON.parse(r.body);
} catch (e) {
throw "Not valid JSON: " + this.makePath(path);
}
} else if (typeof(r.body) !== 'undefined' && r.statusCode === 200) {
return Promise.reject("Not an object: " + this.makePath(path));
}
}.bind(this));
},
/**
* Method: storeObject
*
* Store object at given path. Triggers synchronization.
*
* Parameters:
*
* type - unique type of this object within this module. See description below.
* path - path relative to the module root.
* object - an object to be saved to the given node. It must be serializable as JSON.
*
* Returns:
* A promise to store the object. The promise fails with a ValidationError, when validations fail.
*
*
* What about the type?:
*
* A great thing about having data on the web, is to be able to link to
* it and rearrange it to fit the current circumstances. To facilitate
* that, eventually you need to know how the data at hand is structured.
* For documents on the web, this is usually done via a MIME type. The
* MIME type of JSON objects however, is always application/json.
* To add that extra layer of "knowing what this object is", remoteStorage
* aims to use <JSON-LD at http://json-ld.org/>.
* A first step in that direction, is to add a *@context attribute* to all
* JSON data put into remoteStorage.
* Now that is what the *type* is for.
*
* Within remoteStorage.js, @context values are built using three components:
* http://remotestorage.io/spec/modules/ - A prefix to guarantee uniqueness
* the module name - module names should be unique as well
* the type given here - naming this particular kind of object within this module
*
* In retrospect that means, that whenever you introduce a new "type" in calls to
* storeObject, you should make sure that once your code is in the wild, future
* versions of the code are compatible with the same JSON structure.
*
* How to define types?:
*
* See <declareType> for examples.
*/
storeObject: function (typeAlias, path, object) {
if (typeof(typeAlias) !== 'string') {
return Promise.reject('Argument \'typeAlias\' of baseClient.storeObject must be a string');
}
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.storeObject must be a string');
}
if (typeof(object) !== 'object') {
return Promise.reject('Argument \'object\' of baseClient.storeObject must be an object');
}
this._attachType(object, typeAlias);
try {
var validationResult = this.validate(object);
if (! validationResult.valid) {
return Promise.reject(validationResult);
}
} catch(exc) {
return Promise.reject(exc);
}
return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then(function (r) {
if (r.statusCode === 200 || r.statusCode === 201) {
return r.revision;
} else {
return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode);
}
}.bind(this));
},
// generic operations
/**
* Method: remove
*
* Remove node at given path from storage. Triggers synchronization.
*
* Parameters:
* path - Path relative to the module root.
*/
remove: function (path) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.remove must be a string');
}
if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {
console.warn('WARNING: Removing a document to which only read access (\'r\') was claimed');
}
return this.storage.delete(this.makePath(path));
},
cache: function (path, strategy) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.cache must be a string';
}
if (strategy === false) {
deprecate('caching strategy <false>', '<"FLUSH">');
strategy = 'FLUSH';
} else if (strategy === undefined) {
strategy = 'ALL';
} else if (typeof(strategy) !== 'string') {
deprecate('that caching strategy', '<"ALL">');
strategy = 'ALL';
}
if (strategy !== 'FLUSH' &&
strategy !== 'SEEN' &&
strategy !== 'ALL') {
throw 'Argument \'strategy\' of baseclient.cache must be one of '
+ '["FLUSH", "SEEN", "ALL"]';
}
this.storage.caching.set(this.makePath(path), strategy);
return this;
},
flush: function (path) {
return this.storage.local.flush(path);
},
makePath: function (path) {
return this.base + (path || '');
},
_fireChange: function (event) {
if (RemoteStorage.config.changeEvents[event.origin]) {
['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) {
if ((!event[fieldNamePrefix+'ContentType'])
|| (/^application\/(.*)json(.*)/.exec(event[fieldNamePrefix+'ContentType']))) {
if (typeof(event[fieldNamePrefix+'Value']) === 'string') {
try {
event[fieldNamePrefix+'Value'] = JSON.parse(event[fieldNamePrefix+'Value']);
} catch(e) {
}
}
}
});
this._emit('change', event);
}
},
_cleanPath: RemoteStorage.util.cleanPath,
/**
* Method: getItemURL
*
* Retrieve full URL of item
*
* Parameters:
* path - Path relative to the module root.
*/
getItemURL: function (path) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.getItemURL must be a string';
}
if (this.storage.connected) {
path = this._cleanPath( this.makePath(path) );
return this.storage.remote.href + path;
} else {
return undefined;
}
},
uuid: function () {
return Math.uuid();
}
};
/**
* Method: RS#scope
*
* Returns a new <RS.BaseClient> scoped to the given path.
*
* Parameters:
* path - Root path of new BaseClient.
*
*
* Example:
* (start code)
*
* var foo = remoteStorage.scope('/foo/');
*
* // PUTs data "baz" to path /foo/bar
* foo.storeFile('text/plain', 'bar', 'baz');
*
* var something = foo.scope('something/');
*
* // GETs listing from path /foo/something/bla/
* something.getListing('bla/');
*
* (end code)
*
*/
RS.BaseClient._rs_init = function () {
RS.prototype.scope = function (path) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.scope must be a string';
}
if (!this.access.checkPathPermission(path, 'r')) {
var escapedPath = path.replace(/(['\\])/g, '\\$1');
console.warn('WARNING: please call remoteStorage.access.claim(\'' + escapedPath + '\', \'r\') (read only) or remoteStorage.access.claim(\'' + escapedPath + '\', \'rw\') (read/write) first');
}
return new RS.BaseClient(this, path);
};
};
/* e.g.:
remoteStorage.defineModule('locations', function (priv, pub) {
return {
exports: {
features: priv.scope('features/').defaultType('feature'),
collections: priv.scope('collections/').defaultType('feature-collection');
}
};
});
*/
// Defined in baseclient/types.js
/**
* Method: declareType
*
* Declare a remoteStorage object type using a JSON schema. See
* <RemoteStorage.BaseClient.Types>
**/
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/baseclient/types.js **/
(function(global) {
/**
* Class: RemoteStorage.BaseClient.Types
*
* - Manages and validates types of remoteStorage objects, using JSON-LD and
* JSON Schema
* - Adds schema declaration/validation methods to BaseClient instances.
**/
RemoteStorage.BaseClient.Types = {
// <alias> -> <uri>
uris: {},
// <uri> -> <schema>
schemas: {},
// <uri> -> <alias>
aliases: {},
declare: function(moduleName, alias, uri, schema) {
var fullAlias = moduleName + '/' + alias;
if (schema.extends) {
var extendedAlias;
var parts = schema.extends.split('/');
if (parts.length === 1) {
extendedAlias = moduleName + '/' + parts.shift();
} else {
extendedAlias = parts.join('/');
}
var extendedUri = this.uris[extendedAlias];
if (! extendedUri) {
throw "Type '" + fullAlias + "' tries to extend unknown schema '" + extendedAlias + "'";
}
schema.extends = this.schemas[extendedUri];
}
this.uris[fullAlias] = uri;
this.aliases[uri] = fullAlias;
this.schemas[uri] = schema;
},
resolveAlias: function(alias) {
return this.uris[alias];
},
getSchema: function(uri) {
return this.schemas[uri];
},
inScope: function(moduleName) {
var ml = moduleName.length;
var schemas = {};
for (var alias in this.uris) {
if (alias.substr(0, ml + 1) === moduleName + '/') {
var uri = this.uris[alias];
schemas[uri] = this.schemas[uri];
}
}
return schemas;
}
};
var SchemaNotFound = function(uri) {
var error = new Error("Schema not found: " + uri);
error.name = "SchemaNotFound";
return error;
};
SchemaNotFound.prototype = Error.prototype;
RemoteStorage.BaseClient.Types.SchemaNotFound = SchemaNotFound;
/**
* Class: RemoteStorage.BaseClient
**/
RemoteStorage.BaseClient.prototype.extend({
/**
* Method: declareType
*
* Declare a remoteStorage object type using a JSON schema.
*
* Parameters:
* alias - A type alias/shortname
* uri - (optional) JSON-LD URI of the schema. Automatically generated if none given
* schema - A JSON Schema object describing the object type
*
* Example:
*
* (start code)
* client.declareType('todo-item', {
* "type": "object",
* "properties": {
* "id": {
* "type": "string"
* },
* "title": {
* "type": "string"
* },
* "finished": {
* "type": "boolean"
* "default": false
* },
* "createdAt": {
* "type": "date"
* }
* },
* "required": ["id", "title"]
* })
* (end code)
*
* Visit <http://json-schema.org> for details on how to use JSON Schema.
**/
declareType: function(alias, uri, schema) {
if (! schema) {
schema = uri;
uri = this._defaultTypeURI(alias);
}
RemoteStorage.BaseClient.Types.declare(this.moduleName, alias, uri, schema);
},
/**
* Method: validate
*
* Validate an object against the associated schema.
*
* Parameters:
* object - Object to validate. Must have a @context property.
*
* Returns:
* An object containing information about validation errors
**/
validate: function(object) {
var schema = RemoteStorage.BaseClient.Types.getSchema(object['@context']);
if (schema) {
return tv4.validateResult(object, schema);
} else {
throw new SchemaNotFound(object['@context']);
}
},
_defaultTypeURI: function(alias) {
return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias);
},
_attachType: function(object, alias) {
object['@context'] = RemoteStorage.BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias);
}
});
// Documented in baseclient.js
Object.defineProperty(RemoteStorage.BaseClient.prototype, 'schemas', {
configurable: true,
get: function() {
return RemoteStorage.BaseClient.Types.inScope(this.moduleName);
}
});
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/modules.js **/
(function () {
RemoteStorage.MODULES = {};
/*
* Method: RemoteStorage.defineModule
*
* Method for defining a new remoteStorage data module
*
* Parameters:
* moduleName - Name of the module
* builder - Builder function defining the module
*
* The module builder function should return an object containing another
* object called exports, which will be exported to any <RemoteStorage>
* instance under the module's name. So when defining a locations module,
* like in the example below, it would be accessible via
* `remoteStorage.locations`, which would in turn have a `features` and a
* `collections` property.
*
* The function receives a private and a public client, which are both
* instances of <RemoteStorage.BaseClient>. In the following example, the
* scope of privateClient is `/locations` and the scope of publicClient is
* `/public/locations`.
*
* Example:
* (start code)
* RemoteStorage.defineModule('locations', function (privateClient, publicClient) {
* return {
* exports: {
* features: privateClient.scope('features/').defaultType('feature'),
* collections: privateClient.scope('collections/').defaultType('feature-collection')
* }
* };
* });
* (end code)
*/
RemoteStorage.defineModule = function (moduleName, builder) {
RemoteStorage.MODULES[moduleName] = builder;
Object.defineProperty(RemoteStorage.prototype, moduleName, {
configurable: true,
get: function () {
var instance = this._loadModule(moduleName);
Object.defineProperty(this, moduleName, {
value: instance
});
return instance;
}
});
if (moduleName.indexOf('-') !== -1) {
var camelizedName = moduleName.replace(/\-[a-z]/g, function (s) {
return s[1].toUpperCase();
});
Object.defineProperty(RemoteStorage.prototype, camelizedName, {
get: function () {
return this[moduleName];
}
});
}
};
RemoteStorage.prototype._loadModule = function (moduleName) {
var builder = RemoteStorage.MODULES[moduleName];
if (builder) {
var module = builder(new RemoteStorage.BaseClient(this, '/' + moduleName + '/'),
new RemoteStorage.BaseClient(this, '/public/' + moduleName + '/'));
return module.exports;
} else {
throw "Unknown module: " + moduleName;
}
};
RemoteStorage.prototype.defineModule = function (moduleName) {
console.log("remoteStorage.defineModule is deprecated, use RemoteStorage.defineModule instead!");
RemoteStorage.defineModule.apply(RemoteStorage, arguments);
};
})();
/** FILE: src/debug/inspect.js **/
(function() {
function loadTable(table, storage, paths) {
table.setAttribute('border', '1');
table.style.margin = '8px';
table.style.color = 'white';
table.innerHTML = '';
var thead = document.createElement('thead');
table.appendChild(thead);
var titleRow = document.createElement('tr');
thead.appendChild(titleRow);
['Path', 'Content-Type', 'Revision'].forEach(function(label) {
var th = document.createElement('th');
th.textContent = label;
thead.appendChild(th);
});
var tbody = document.createElement('tbody');
table.appendChild(tbody);
function renderRow(tr, path, contentType, revision) {
[path, contentType, revision].forEach(function(value) {
var td = document.createElement('td');
td.textContent = value || '';
tr.appendChild(td);
});
}
function loadRow(path) {
if (storage.connected === false) { return; }
function processRow(status, body, contentType, revision) {
if (status === 200) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
renderRow(tr, path, contentType, revision);
if (path[path.length - 1] === '/') {
for (var key in body) {
loadRow(path + key);
}
}
}
}
storage.get(path).then(processRow);
}
paths.forEach(loadRow);
}
function renderWrapper(title, table, storage, paths) {
var wrapper = document.createElement('div');
//wrapper.style.display = 'inline-block';
var heading = document.createElement('h2');
heading.textContent = title;
wrapper.appendChild(heading);
var updateButton = document.createElement('button');
updateButton.textContent = "Refresh";
updateButton.onclick = function() { loadTable(table, storage, paths); };
wrapper.appendChild(updateButton);
if (storage.reset) {
var resetButton = document.createElement('button');
resetButton.textContent = "Reset";
resetButton.onclick = function() {
storage.reset(function(newStorage) {
storage = newStorage;
loadTable(table, storage, paths);
});
};
wrapper.appendChild(resetButton);
}
wrapper.appendChild(table);
loadTable(table, storage, paths);
return wrapper;
}
function renderLocalChanges(local) {
var wrapper = document.createElement('div');
//wrapper.style.display = 'inline-block';
var heading = document.createElement('h2');
heading.textContent = "Outgoing changes";
wrapper.appendChild(heading);
var updateButton = document.createElement('button');
updateButton.textContent = "Refresh";
wrapper.appendChild(updateButton);
var list = document.createElement('ul');
list.style.fontFamily = 'courier';
wrapper.appendChild(list);
function updateList() {
list.innerHTML = '';
local.forAllNodes(function(node) {
if (node.local && node.local.body) {
var el = document.createElement('li');
el.textContent = JSON.stringify(node.local);
list.appendChild(el);
}
});
}
updateButton.onclick = updateList;
updateList();
return wrapper;
}
RemoteStorage.prototype.inspect = function() {
var widget = document.createElement('div');
widget.id = 'remotestorage-inspect';
widget.style.position = 'absolute';
widget.style.top = 0;
widget.style.left = 0;
widget.style.background = 'black';
widget.style.color = 'white';
widget.style.border = 'groove 5px #ccc';
var controls = document.createElement('div');
controls.style.position = 'absolute';
controls.style.top = 0;
controls.style.left = 0;
var heading = document.createElement('strong');
heading.textContent = " remotestorage.js inspector ";
controls.appendChild(heading);
var syncButton;
if (this.local) {
syncButton = document.createElement('button');
syncButton.textContent = "Synchronize";
controls.appendChild(syncButton);
}
var closeButton = document.createElement('button');
closeButton.textContent = "Close";
closeButton.onclick = function() {
document.body.removeChild(widget);
};
controls.appendChild(closeButton);
widget.appendChild(controls);
var remoteRootPaths = [];
for (var path in this.caching._rootPaths) {
if (this.caching._rootPaths.hasOwnProperty(path)) {
remoteRootPaths.push(path);
}
}
var remoteTable = document.createElement('table');
var localTable = document.createElement('table');
widget.appendChild(renderWrapper("Remote", remoteTable, this.remote, remoteRootPaths));
if (this.local) {
widget.appendChild(renderWrapper("Local", localTable, this.local, ['/']));
widget.appendChild(renderLocalChanges(this.local));
syncButton.onclick = function() {
this.log('sync clicked');
this.sync.sync().then(function() {
this.log('SYNC FINISHED');
loadTable(localTable, this.local, ['/']);
}.bind(this), function(err) {
console.error("SYNC FAILED", err, err.stack);
});
}.bind(this);
}
document.body.appendChild(widget);
};
})();
/** FILE: src/googledrive.js **/
(function (global) {
/**
* Class: RemoteStorage.GoogleDrive
*
* WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE
*
* To use this backend, you need to specify the app's client ID like so:
*
* (start code)
*
* remoteStorage.setApiKeys('googledrive', {
* clientId: 'your-client-id'
* });
*
* (end code)
*
* An client ID can be obtained by registering your app in the Google
* Developers Console: https://developers.google.com/drive/web/auth/web-client
*
* Docs: https://developers.google.com/drive/web/auth/web-client#create_a_client_id_and_client_secret
**/
var RS = RemoteStorage;
var BASE_URL = 'https://www.googleapis.com';
var AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
var AUTH_SCOPE = 'https://www.googleapis.com/auth/drive';
var GD_DIR_MIME_TYPE = 'application/vnd.google-apps.folder';
var RS_DIR_MIME_TYPE = 'application/json; charset=UTF-8';
var isFolder = RemoteStorage.util.isFolder;
function buildQueryString(params) {
return Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
function fileNameFromMeta(meta) {
return encodeURIComponent(meta.title) + (meta.mimeType === GD_DIR_MIME_TYPE ? '/' : '');
}
function metaTitleFromFileName(filename) {
if (filename.substr(-1) === '/') {
filename = filename.substr(0, filename.length - 1);
}
return decodeURIComponent(filename);
}
function parentPath(path) {
return path.replace(/[^\/]+\/?$/, '');
}
function baseName(path) {
var parts = path.split('/');
if (path.substr(-1) === '/') {
return parts[parts.length-2]+'/';
} else {
return parts[parts.length-1];
}
}
var Cache = function (maxAge) {
this.maxAge = maxAge;
this._items = {};
};
Cache.prototype = {
get: function (key) {
var item = this._items[key];
var now = new Date().getTime();
return (item && item.t >= (now - this.maxAge)) ? item.v : undefined;
},
set: function (key, value) {
this._items[key] = {
v: value,
t: new Date().getTime()
};
}
};
RS.GoogleDrive = function (remoteStorage, clientId) {
RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected');
this.rs = remoteStorage;
this.clientId = clientId;
this._fileIdCache = new Cache(60 * 5); // ids expire after 5 minutes (is this a good idea?)
};
RS.GoogleDrive.prototype = {
connected: false,
online: true,
configure: function (settings) { // Settings parameter compatible with WireClient
if (settings.token) {
localStorage['remotestorage:googledrive:token'] = settings.token;
this.token = settings.token;
this.connected = true;
this._emit('connected');
} else {
this.connected = false;
delete this.token;
delete localStorage['remotestorage:googledrive:token'];
}
},
connect: function () {
this.rs.setBackend('googledrive');
RS.Authorize(this.rs, AUTH_URL, AUTH_SCOPE, String(RS.Authorize.getLocation()), this.clientId);
},
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
get: function (path, options) {
if (path.substr(-1) === '/') {
return this._getFolder(path, options);
} else {
return this._getFile(path, options);
}
},
put: function (path, body, contentType, options) {
var self = this;
function putDone(response) {
if (response.status >= 200 && response.status < 300) {
var meta = JSON.parse(response.responseText);
var etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes});
} else if (response.status === 412) {
return Promise.resolve({statusCode: 412, revision: 'conflict'});
} else {
return Promise.reject("PUT failed with status " + response.status + " (" + response.responseText + ")");
}
}
return self._getFileId(path).then(function (id) {
if (id) {
if (options && (options.ifNoneMatch === '*')) {
return putDone({ status: 412 });
}
return self._updateFile(id, path, body, contentType, options).then(putDone);
} else {
return self._createFile(path, body, contentType, options).then(putDone);
}
});
},
'delete': function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
if (!id) {
// File doesn't exist. Ignore.
return Promise.resolve({statusCode: 200});
}
return self._getMeta(id).then(function (meta) {
var etagWithoutQuotes;
if ((typeof meta === 'object') && (typeof meta.etag === 'string')) {
etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
}
if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) {
return {statusCode: 412, revision: etagWithoutQuotes};
}
return self._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {
if (response.status === 200 || response.status === 204) {
return {statusCode: 200};
} else {
return Promise.reject("Delete failed: " + response.status + " (" + response.responseText + ")");
}
});
});
});
},
_updateFile: function (id, path, body, contentType, options) {
var self = this;
var metadata = {
mimeType: contentType
};
var headers = {
'Content-Type': 'application/json; charset=UTF-8'
};
if (options && options.ifMatch) {
headers['If-Match'] = '"' + options.ifMatch + '"';
}
return self._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', {
body: JSON.stringify(metadata),
headers: headers
}).then(function (response) {
if (response.status === 412) {
return (response);
} else {
return self._request('PUT', response.getResponseHeader('Location'), {
body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body
});
}
});
},
_createFile: function (path, body, contentType, options) {
var self = this;
return self._getParentId(path).then(function (parentId) {
var fileName = baseName(path);
var metadata = {
title: metaTitleFromFileName(fileName),
mimeType: contentType,
parents: [{
kind: "drive#fileLink",
id: parentId
}]
};
return self._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', {
body: JSON.stringify(metadata),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(function (response) {
return self._request('POST', response.getResponseHeader('Location'), {
body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body
});
});
});
},
_getFile: function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
return self._getMeta(id).then(function (meta) {
var etagWithoutQuotes;
if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') {
etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
}
if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) {
return Promise.resolve({statusCode: 304});
}
var options2 = {};
if (!meta.downloadUrl) {
if (meta.exportLinks && meta.exportLinks['text/html']) {
// Documents that were generated inside GoogleDocs have no
// downloadUrl, but you can export them to text/html instead:
meta.mimeType += ';export=text/html';
meta.downloadUrl = meta.exportLinks['text/html'];
} else {
// empty file
return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes});
}
}
if (meta.mimeType.match(/charset=binary/)) {
options2.responseType = 'blob';
}
return self._request('GET', meta.downloadUrl, options2).then(function (response) {
var body = response.response;
if (meta.mimeType.match(/^application\/json/)) {
try {
body = JSON.parse(body);
} catch(e) {}
}
return Promise.resolve({statusCode: 200, body: body, contentType: meta.mimeType, revision: etagWithoutQuotes});
});
});
});
},
_getFolder: function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
var query, fields, data, i, etagWithoutQuotes, itemsMap;
if (! id) {
return Promise.resolve({statusCode: 404});
}
query = '\'' + id + '\' in parents';
fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title)';
return self._request('GET', BASE_URL + '/drive/v2/files?'
+ 'q=' + encodeURIComponent(query)
+ '&fields=' + encodeURIComponent(fields)
+ '&maxResults=1000',
{})
.then(function (response) {
if (response.status !== 200) {
return Promise.reject('request failed or something: ' + response.status);
}
try {
data = JSON.parse(response.responseText);
} catch(e) {
return Promise.reject('non-JSON response from GoogleDrive');
}
itemsMap = {};
for (var i = 0, len = data.items.length; i < len; i++) {
etagWithoutQuotes = data.items[i].etag.substring(1, data.items[i].etag.length-1);
if (data.items[i].mimeType === GD_DIR_MIME_TYPE) {
self._fileIdCache.set(path + data.items[i].title + '/', data.items[i].id);
itemsMap[data.items[i].title + '/'] = {
ETag: etagWithoutQuotes
};
} else {
self._fileIdCache.set(path + data.items[i].title, data.items[i].id);
itemsMap[data.items[i].title] = {
ETag: etagWithoutQuotes,
'Content-Type': data.items[i].mimeType,
'Content-Length': data.items[i].fileSize
};
}
}
// FIXME: add revision of folder!
return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined});
});
});
},
_getParentId: function (path) {
var foldername = parentPath(path);
var self = this;
return self._getFileId(foldername).then(function (parentId) {
if (parentId) {
return Promise.resolve(parentId);
} else {
return self._createFolder(foldername);
}
});
},
_createFolder: function (path) {
var self = this;
return self._getParentId(path).then(function (parentId) {
return self._request('POST', BASE_URL + '/drive/v2/files', {
body: JSON.stringify({
title: metaTitleFromFileName(baseName(path)),
mimeType: GD_DIR_MIME_TYPE,
parents: [{
id: parentId
}]
}),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(function (response) {
var meta = JSON.parse(response.responseText);
return Promise.resolve(meta.id);
});
});
},
_getFileId: function (path) {
var self = this;
var id;
if (path === '/') {
// "root" is a special alias for the fileId of the root folder
return Promise.resolve('root');
} else if ((id = this._fileIdCache.get(path))) {
// id is cached.
return Promise.resolve(id);
}
// id is not cached (or file doesn't exist).
// load parent folder listing to propagate / update id cache.
return self._getFolder(parentPath(path)).then(function () {
id = self._fileIdCache.get(path);
if (!id) {
if (path.substr(-1) === '/') {
return self._createFolder(path).then(function () {
return self._getFileId(path);
});
} else {
return Promise.resolve();
}
return;
}
return Promise.resolve(id);
});
},
_getMeta: function (id) {
return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {
if (response.status === 200) {
return Promise.resolve(JSON.parse(response.responseText));
} else {
return Promise.reject("request (getting metadata for " + id + ") failed with status: " + response.status);
}
});
},
_request: function (method, url, options) {
var self = this;
if (! options.headers) { options.headers = {}; }
options.headers['Authorization'] = 'Bearer ' + self.token;
this._emit('wire-busy', {
method: method,
isFolder: isFolder(url)
});
return RS.WireClient.request.call(this, method, url, options).then(function(xhr) {
// Google tokens expire from time to time...
if (xhr && xhr.status === 401) {
self.connect();
return;
} else {
if (!self.online) {
self.online = true;
self.rs._emit('network-online');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(url),
success: true
});
return Promise.resolve(xhr);
}
}, function(error) {
if (self.online) {
self.online = false;
self.rs._emit('network-offline');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(url),
success: false
});
return Promise.reject(error);
});
}
};
RS.GoogleDrive._rs_init = function (remoteStorage) {
var config = remoteStorage.apiKeys.googledrive;
if (config) {
remoteStorage.googledrive = new RS.GoogleDrive(remoteStorage, config.clientId);
if (remoteStorage.backend === 'googledrive') {
remoteStorage._origRemote = remoteStorage.remote;
remoteStorage.remote = remoteStorage.googledrive;
}
}
};
RS.GoogleDrive._rs_supported = function (rs) {
return true;
};
RS.GoogleDrive._rs_cleanup = function (remoteStorage) {
remoteStorage.setBackend(undefined);
if (remoteStorage._origRemote) {
remoteStorage.remote = remoteStorage._origRemote;
delete remoteStorage._origRemote;
}
};
})(this);
/** FILE: src/dropbox.js **/
(function (global) {
var RS = RemoteStorage;
/**
* File: Dropbox
*
* WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE
*
* Dropbox backend for RemoteStorage.js
* This file exposes a get/put/delete interface which is compatible with
* <RemoteStorage.WireClient>.
*
* When remoteStorage.backend is set to 'dropbox', this backend will
* initialize and replace remoteStorage.remote with remoteStorage.dropbox.
*
* In order to ensure compatibility with the public folder, <BaseClient.getItemURL>
* gets hijacked to return the Dropbox public share URL.
*
* To use this backend, you need to specify the Dropbox app key like so:
*
* (start code)
*
* remoteStorage.setApiKeys('dropbox', {
* appKey: 'your-app-key'
* });
*
* (end code)
*
* An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps
*
* Known issues:
*
* - Storing files larger than 150MB is not yet supported
* - Listing and deleting folders with more than 10'000 files will cause problems
* - Content-Type is not fully supported due to limitations of the Dropbox API
* - Dropbox preserves cases but is not case-sensitive
* - getItemURL is asynchronous which means getIetmURL returns useful values
* after the syncCycle
*/
var hasLocalStorage;
var AUTH_URL = 'https://www.dropbox.com/1/oauth2/authorize';
var SETTINGS_KEY = 'remotestorage:dropbox';
var PATH_PREFIX = '/remotestorage';
var isFolder = RemoteStorage.util.isFolder;
/**
* Function: getDropboxPath(path)
*
* Map a local path to a path in DropBox.
*/
var getDropboxPath = function (path) {
return RS.WireClient.cleanPath(PATH_PREFIX + '/' + path);
};
var encodeQuery = function (obj) {
var pairs = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
};
/**
* class: LowerCaseCache
*
* A cache which automatically converts all keys to lower case and can
* propagate changes up to parent folders.
*
* By default the set and delete methods are aliased to justSet and justDelete.
*
* Parameters:
*
* defaultValue - the value that is returned for all keys that don't exist
* in the cache
*/
function LowerCaseCache(defaultValue){
this.defaultValue = defaultValue;
this._storage = { };
this.set = this.justSet;
this.delete = this.justDelete;
}
LowerCaseCache.prototype = {
/**
* Method: get
*
* Get a value from the cache or defaultValue, if the key is not in the
* cache.
*/
get : function (key) {
key = key.toLowerCase();
var stored = this._storage[key];
if (typeof stored === 'undefined'){
stored = this.defaultValue;
this._storage[key] = stored;
}
return stored;
},
/**
* Method: propagateSet
*
* Set a value and also update the parent folders with that value.
*/
propagateSet : function (key, value) {
key = key.toLowerCase();
if (this._storage[key] === value) {
return value;
}
this._propagate(key, value);
this._storage[key] = value;
return value;
},
/**
* Method: propagateDelete
*
* Delete a value and propagate the changes to the parent folders.
*/
propagateDelete : function (key) {
key = key.toLowerCase();
this._propagate(key, this._storage[key]);
return delete this._storage[key];
},
_activatePropagation: function (){
this.set = this.propagateSet;
this.delete = this.propagateDelete;
return true;
},
/**
* Method: justSet
*
* Set a value without propagating.
*/
justSet : function (key, value) {
key = key.toLowerCase();
this._storage[key] = value;
return value;
},
/**
* Method: justDelete
*
* Delete a value without propagating.
*/
justDelete : function (key, value) {
key = key.toLowerCase();
return delete this._storage[key];
},
_propagate: function (key, rev){
var folders = key.split('/').slice(0,-1);
var path = '';
for (var i = 0, len = folders.length; i < len; i++){
path += folders[i]+'/';
if (!rev) {
rev = this._storage[path]+1;
}
this._storage[path] = rev;
}
}
};
var onErrorCb;
/**
* Class: RemoteStorage.Dropbox
*/
RS.Dropbox = function (rs) {
this.rs = rs;
this.connected = false;
this.rs = rs;
var self = this;
onErrorCb = function (error){
if (error instanceof RemoteStorage.Unauthorized) {
// Delete all the settings - see the documentation of wireclient.configure
self.configure({
userAddress: null,
href: null,
storageApi: null,
token: null,
options: null
});
}
};
RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected');
rs.on('error', onErrorCb);
this.clientId = rs.apiKeys.dropbox.appKey;
this._revCache = new LowerCaseCache('rev');
this._itemRefs = {};
this._metadataCache = {};
if (hasLocalStorage){
var settings;
try {
settings = JSON.parse(localStorage[SETTINGS_KEY]);
} catch(e){}
if (settings) {
this.configure(settings);
}
try {
this._itemRefs = JSON.parse(localStorage[ SETTINGS_KEY+':shares' ]);
} catch(e) { }
}
if (this.connected) {
setTimeout(this._emit.bind(this), 0, 'connected');
}
};
RS.Dropbox.prototype = {
online: true,
/**
* Method: connect
*
* Set the backed to 'dropbox' and start the authentication flow in order
* to obtain an API token from Dropbox.
*/
connect: function () {
// TODO handling when token is already present
this.rs.setBackend('dropbox');
if (this.token){
hookIt(this.rs);
} else {
RS.Authorize(this.rs, AUTH_URL, '', String(RS.Authorize.getLocation()), this.clientId);
}
},
/**
* Method : configure(settings)
* Accepts its parameters according to the <RemoteStorage.WireClient>.
* Sets the connected flag
**/
configure: function (settings) {
// We only update this.userAddress if settings.userAddress is set to a string or to null:
if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }
// Same for this.token. If only one of these two is set, we leave the other one at its existing value:
if (typeof settings.token !== 'undefined') { this.token = settings.token; }
if (this.token) {
this.connected = true;
if ( !this.userAddress ){
this.info().then(function (info){
this.userAddress = info.display_name;
this.rs.widget.view.setUserAddress(this.userAddress);
this._emit('connected');
}.bind(this));
}
} else {
this.connected = false;
}
if (hasLocalStorage){
localStorage[SETTINGS_KEY] = JSON.stringify({
userAddress: this.userAddress,
token: this.token
});
}
},
/**
* Method: stopWaitingForToken
*
* Stop waiting for the token and emit not-connected
*/
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
/**
* Method: _getFolder
*
* Get all items in a folder.
*
* Parameters:
*
* path - path of the folder to get, with leading slash
* options - not used
*
* Returns:
*
* statusCode - HTTP status code
* body - array of the items found
* contentType - 'application/json; charset=UTF-8'
* revision - revision of the folder
*/
_getFolder: function (path, options) {
// FIXME simplify promise handling
var url = 'https://api.dropbox.com/1/metadata/auto' + getDropboxPath(path);
var revCache = this._revCache;
var self = this;
return this._request('GET', url, {}).then(function (resp) {
var status = resp.status;
if (status === 304) {
return Promise.resolve({statusCode: status});
}
var listing, body, mime, rev;
try{
body = JSON.parse(resp.responseText);
} catch (e) {
return Promise.reject(e);
}
rev = self._revCache.get(path);
mime = 'application/json; charset=UTF-8';
if (body.contents) {
listing = body.contents.reduce(function (m, item) {
var itemName = item.path.split('/').slice(-1)[0] + ( item.is_dir ? '/' : '' );
if (item.is_dir){
m[itemName] = { ETag: revCache.get(path+itemName) };
} else {
m[itemName] = { ETag: item.rev };
}
return m;
}, {});
}
return Promise.resolve({statusCode: status, body: listing, contentType: mime, revision: rev});
});
},
/**
* Method: get
*
* Compatible with <RemoteStorage.WireClient.get>
*
* Checks for the path in _revCache and decides based on that if file has
* changed. Calls _getFolder is the path points to a folder.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
get: function (path, options) {
if (! this.connected) { return Promise.reject("not connected (path: " + path + ")"); }
var url = 'https://api-content.dropbox.com/1/files/auto' + getDropboxPath(path);
var self = this;
var savedRev = this._revCache.get(path);
if (savedRev === null) {
// file was deleted server side
return Promise.resolve({statusCode: 404});
}
if (options && options.ifNoneMatch &&
savedRev && (savedRev === options.ifNoneMatch)) {
// nothing changed.
return Promise.resolve({statusCode: 304});
}
//use _getFolder for folders
if (path.substr(-1) === '/') { return this._getFolder(path, options); }
return this._request('GET', url, {}).then(function (resp) {
var status = resp.status;
var meta, body, mime, rev;
if (status !== 200) {
return Promise.resolve({statusCode: status});
}
body = resp.responseText;
try {
meta = JSON.parse( resp.getResponseHeader('x-dropbox-metadata') );
} catch(e) {
return Promise.reject(e);
}
mime = meta.mime_type; //resp.getResponseHeader('Content-Type');
rev = meta.rev;
self._revCache.set(path, rev);
self._shareIfNeeded(path); // The shared link expires every 4 hours
// handling binary
if (!resp.getResponseHeader('Content-Type') ||
resp.getResponseHeader('Content-Type').match(/charset=binary/)) {
var pending = Promise.defer();
RS.WireClient.readBinaryData(resp.response, mime, function (result) {
pending.resolve({
statusCode: status,
body: result,
contentType: mime,
revision: rev
});
});
return pending.promise;
}
// handling json (always try)
if (mime && mime.search('application/json') >= 0 || true) {
try {
body = JSON.parse(body);
mime = 'application/json; charset=UTF-8';
} catch(e) {
//Failed parsing Json, assume it is something else then
}
}
return Promise.resolve({statusCode: status, body: body, contentType: mime, revision: rev});
});
},
/**
* Method: put
*
* Compatible with <RemoteStorage.WireClient>
*
* Checks for the path in _revCache and decides based on that if file has
* changed.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
put: function (path, body, contentType, options) {
var self = this;
if (!this.connected) {
throw new Error("not connected (path: " + path + ")");
}
//check if file has changed and return 412
var savedRev = this._revCache.get(path);
if (options && options.ifMatch &&
savedRev && (savedRev !== options.ifMatch)) {
return Promise.resolve({statusCode: 412, revision: savedRev});
}
if (options && (options.ifNoneMatch === '*') &&
savedRev && (savedRev !== 'rev')) {
return Promise.resolve({statusCode: 412, revision: savedRev});
}
if ((!contentType.match(/charset=/)) &&
(body instanceof ArrayBuffer || RS.WireClient.isArrayBufferView(body))) {
contentType += '; charset=binary';
}
if (body.length > 150 * 1024 * 1024) {
//https://www.dropbox.com/developers/core/docs#chunked-upload
return Promise.reject(new Error("Cannot upload file larger than 150MB"));
}
var result;
var needsMetadata = options && (options.ifMatch || (options.ifNoneMatch === '*'));
var uploadParams = {
body: body,
contentType: contentType,
path: path
};
if (needsMetadata) {
result = this._getMetadata(path).then(function (metadata) {
if (options && (options.ifNoneMatch === '*') && metadata) {
// if !!metadata === true, the file exists
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
return self._uploadSimple(uploadParams);
});
} else {
result = self._uploadSimple(uploadParams);
}
return result.then(function (ret) {
self._shareIfNeeded(path);
return ret;
});
},
/**
* Method: delete
*
* Compatible with <RemoteStorage.WireClient.delete>
*
* Checks for the path in _revCache and decides based on that if file has
* changed.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
'delete': function (path, options) {
var self = this;
if (!this.connected) {
throw new Error("not connected (path: " + path + ")");
}
//check if file has changed and return 412
var savedRev = this._revCache.get(path);
if (options && options.ifMatch && savedRev && (options.ifMatch !== savedRev)) {
return Promise.resolve({ statusCode: 412, revision: savedRev });
}
if (options && options.ifMatch) {
return this._getMetadata(path).then(function (metadata) {
if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
return self._deleteSimple(path);
});
}
return self._deleteSimple(path);
},
/**
* Method: _shareIfNeeded
*
* Calls share, if the provided path resides in a public folder.
*/
_shareIfNeeded: function (path) {
if (path.match(/^\/public\/.*[^\/]$/) && this._itemRefs[path] === undefined) {
this.share(path);
}
},
/**
* Method: share
*
* Gets a publicly-accessible URL for the path from Dropbox and stores it
* in _itemRefs.
*
* Returns:
*
* A promise for the URL
*/
share: function (path) {
var self = this;
var url = 'https://api.dropbox.com/1/media/auto' + getDropboxPath(path);
return this._request('POST', url, {}).then(function (response) {
if (response.status !== 200) {
return Promise.reject(new Error('Invalid Dropbox API response status when sharing "' + path + '":' + response.status));
}
try {
response = JSON.parse(response.responseText);
} catch (e) {
return Promise.reject(new Error('Invalid Dropbox API response when sharing "' + path + '": ' + response.responseText));
}
self._itemRefs[path] = response.url;
if (hasLocalStorage) {
localStorage[SETTINGS_KEY + ':shares'] = JSON.stringify(self._itemRefs);
}
return Promise.resolve(url);
}, function (error) {
err.message = 'Sharing dropbox file or folder ("' + path + '") failed.' + err.message;
return Promise.reject(error);
});
},
/**
* Method: info
*
* Fetches the user's info from dropbox and returns a promise for it.
*
* Returns:
*
* A promise to the user's info
*/
info: function () {
var url = 'https://api.dropbox.com/1/account/info';
// requesting user info(mainly for userAdress)
return this._request('GET', url, {}).then(function (resp){
try {
var info = JSON.parse(resp.responseText);
return Promise.resolve(info);
} catch (e) {
return Promise.reject(e);
}
});
},
/**
* Method: _request
*
* Make a HTTP request.
*
* Options:
*
* headers - an object containing the request headers
*
* Parameters:
*
* method - the method to use
* url - the URL to make the request to
* options - see above
*/
_request: function (method, url, options) {
var self = this;
if (! options.headers) { options.headers = {}; }
options.headers['Authorization'] = 'Bearer ' + this.token;
this._emit('wire-busy', {
method: method,
isFolder: isFolder(url)
});
return RS.WireClient.request.call(this, method, url, options).then(function(xhr) {
// 503 means retry this later
if (xhr && xhr.status === 503) {
if (self.online) {
self.online = false;
self.rs._emit('network-offline');
}
return global.setTimeout(self._request(method, url, options), 3210);
} else {
if (!self.online) {
self.online = true;
self.rs._emit('network-online');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(url),
success: true
});
return Promise.resolve(xhr);
}
}, function(error) {
if (self.online) {
self.online = false;
self.rs._emit('network-offline');
}
self._emit('wire-done', {
method: method,
isFolder: isFolder(url),
success: false
});
return Promise.reject(error);
});
},
/**
* Method: fetchDelta
*
* Fetches the revision of all the files from dropbox API and puts them
* into _revCache. These values can then be used to determine if something
* has changed.
*/
fetchDelta: function () {
// TODO: Handle `has_more`
var args = Array.prototype.slice.call(arguments);
var self = this;
var body = { path_prefix: PATH_PREFIX };
if (self._deltaCursor) {
body.cursor = self._deltaCursor;
}
return self._request('POST', 'https://api.dropbox.com/1/delta', {
body: encodeQuery(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response) {
// break if status != 200
if (response.status !== 200 ) {
if (response.status === 400) {
self.rs._emit('error', new RemoteStorage.Unauthorized());
return Promise.resolve(args);
} else {
return Promise.reject("dropbox.fetchDelta returned "+response.status+response.responseText);
}
return;
}
var delta;
try {
delta = JSON.parse(response.responseText);
} catch(error) {
RS.log('fetchDeltas can not parse response',error);
return Promise.reject("can not parse response of fetchDelta : "+error.message);
}
// break if no entries found
if (!delta.entries) {
return Promise.reject('dropbox.fetchDeltas failed, no entries found');
}
// Dropbox sends the complete state
if (delta.reset) {
self._revCache = new LowerCaseCache('rev');
}
//saving the cursor for requesting further deltas in relation to the cursor position
if (delta.cursor) {
self._deltaCursor = delta.cursor;
}
//updating revCache
delta.entries.forEach(function (entry) {
var path = entry[0].substr(PATH_PREFIX.length);
var rev;
if (!entry[1]){
rev = null;
} else {
if (entry[1].is_dir) {
return;
}
rev = entry[1].rev;
}
self._revCache.set(path, rev);
});
return Promise.resolve(args);
}, function (err) {
this.rs.log('fetchDeltas', err);
this.rs._emit('error', new RemoteStorage.SyncError('fetchDeltas failed.' + err));
return Promise.resolve(args);
}.bind(this)).then(function () {
if (self._revCache) {
var args = Array.prototype.slice.call(arguments);
self._revCache._activatePropagation();
return Promise.resolve(args);
}
});
},
/**
* Method: _getMetadata
*
* Gets metadata for a path (can point to either a file or a folder).
*
* Options:
*
* list - if path points to a folder, specifies whether to list the
* metadata of the folder's children. False by default.
*
* Parameters:
*
* path - the path to get metadata for
* options - see above
*
* Returns:
*
* A promise for the metadata
*/
_getMetadata: function (path, options) {
var self = this;
var cached = this._metadataCache[path];
var url = 'https://api.dropbox.com/1/metadata/auto' + getDropboxPath(path);
url += '?list=' + ((options && options.list) ? 'true' : 'false');
if (cached && cached.hash) {
url += '&hash=' + encodeURIComponent(cached.hash);
}
return this._request('GET', url, {}).then(function (resp) {
if (resp.status === 304) {
return Promise.resolve(cached);
} else if (resp.status === 200) {
var response = JSON.parse(resp.responseText);
self._metadataCache[path] = response;
return Promise.resolve(response);
} else {
// The file doesn't exist
return Promise.resolve();
}
});
},
/**
* Method: _uploadSimple
*
* Upload a simple file (the size is no more than 150MB).
*
* Parameters:
*
* ifMatch - same as for get
* path - path of the file
* body - contents of the file to upload
* contentType - mime type of the file
*
* Returns:
*
* statusCode - HTTP status code
* revision - revision of the newly-created file, if any
*/
_uploadSimple: function (params) {
var self = this;
var url = 'https://api-content.dropbox.com/1/files_put/auto' + getDropboxPath(params.path) + '?';
if (params && params.ifMatch) {
url += "parent_rev=" + encodeURIComponent(params.ifMatch);
}
return self._request('PUT', url, {
body: params.body,
headers: {
'Content-Type': params.contentType
}
}).then(function (resp) {
if (resp.status !== 200) {
return Promise.resolve({ statusCode: resp.status });
}
var response;
try {
response = JSON.parse(resp.responseText);
} catch (e) {
return Promise.reject(e);
}
// Conflict happened. Delete the copy created by dropbox
if (response.path !== getDropboxPath(params.path)) {
var deleteUrl = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(response.path);
self._request('POST', deleteUrl, {});
return self._getMetadata(params.path).then(function (metadata) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
});
}
self._revCache.propagateSet(params.path, response.rev);
return Promise.resolve({ statusCode: resp.status });
});
},
/**
* Method: _deleteSimple
*
* Deletes a file or a folder. If the folder contains more than 10'000 items
* (recursively) then the operation may not complete successfully. If that
* is the case, an Error gets thrown.
*
* Parameters:
*
* path - the path to delete
*
* Returns:
*
* statusCode - HTTP status code
*/
_deleteSimple: function (path) {
var self = this;
var url = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(getDropboxPath(path));
return self._request('POST', url, {}).then(function (resp) {
if (resp.status === 406) {
// Too many files would be involved in the operation for it to
// complete successfully.
// TODO: Handle this somehow
return Promise.reject(new Error("Cannot delete '" + path + "': too many files involved"));
}
if (resp.status === 200 || resp.status === 404) {
self._revCache.delete(path);
delete self._itemRefs[path];
}
return Promise.resolve({ statusCode: resp.status });
});
}
};
// Hooking and unhooking the sync
function hookSync(rs) {
if (rs._dropboxOrigSync) { return; } // already hooked
rs._dropboxOrigSync = rs.sync.sync.bind(rs.sync);
rs.sync.sync = function () {
return this.dropbox.fetchDelta.apply(this.dropbox, arguments).
then(rs._dropboxOrigSync, function (err) {
rs._emit('error', new RemoteStorage.SyncError(err));
return Promise.reject(err);
});
}.bind(rs);
}
function unHookSync(rs) {
if (! rs._dropboxOrigSync) { return; } // not hooked
rs.sync.sync = rs._dropboxOrigSync;
delete rs._dropboxOrigSync;
}
// Hooking and unhooking getItemURL
function hookGetItemURL(rs) {
if (rs._origBaseClientGetItemURL) { return; }
rs._origBaseClientGetItemURL = RS.BaseClient.prototype.getItemURL;
RS.BaseClient.prototype.getItemURL = function (path){
var ret = rs.dropbox._itemRefs[path];
return ret ? ret : '';
};
}
function unHookGetItemURL(rs){
if (! rs._origBaseClientGetItemURL) { return; }
RS.BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;
delete rs._origBaseClientGetItemURL;
}
function hookRemote(rs){
if (rs._origRemote) { return; }
rs._origRemote = rs.remote;
rs.remote = rs.dropbox;
}
function unHookRemote(rs){
if (rs._origRemote) {
rs.remote = rs._origRemote;
delete rs._origRemote;
}
}
function hookIt(rs){
hookRemote(rs);
if (rs.sync) {
hookSync(rs);
} else {
// when sync is not available yet, we wait for the remote to be connected,
// at which point sync should be available as well
rs.on('connected', function() {
if (rs.sync) {
hookSync(rs);
}
});
}
hookGetItemURL(rs);
}
function unHookIt(rs){
unHookRemote(rs);
unHookSync(rs);
unHookGetItemURL(rs);
}
RS.Dropbox._rs_init = function (rs) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if ( rs.apiKeys.dropbox ) {
rs.dropbox = new RS.Dropbox(rs);
}
if (rs.backend === 'dropbox') {
hookIt(rs);
}
};
RS.Dropbox._rs_supported = function () {
return true;
};
RS.Dropbox._rs_cleanup = function (rs) {
unHookIt(rs);
if (hasLocalStorage){
delete localStorage[SETTINGS_KEY];
}
rs.removeEventListener('error', onErrorCb);
rs.setBackend(undefined);
};
})(this);
remoteStorage = new RemoteStorage(); |
src/component/bootstrap/AlertSuccess.js | MortalFlesh/Dashboard | import React from "react";
import PropTypes from "prop-types";
class AlertSuccess extends React.PureComponent {
render() {
return (
<div className="alert alert-success" role="alert">
{this.props.children}
</div>
);
}
}
AlertSuccess.propTypes = {
children: PropTypes.oneOfType([
PropTypes.array,
PropTypes.element,
PropTypes.string,
]).isRequired
};
export default AlertSuccess;
|
src/routes/contact/index.js | koistya/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Contact from './Contact';
const title = 'Contact Us';
export default {
path: '/contact',
action() {
return {
title,
component: <Contact title={title} />,
};
},
};
|
imports/plugins/included/social/client/components/twitter.js | evereveofficial/reaction | import React, { Component, PropTypes } from "react";
import Helmet from "react-helmet";
import classnames from "classnames";
import { Translation } from "/imports/plugins/core/ui/client/components";
export function getTwitterMeta(props) {
const title = props.title || document.title;
const preferredUrl = props.url || location.origin + location.pathname;
const url = encodeURIComponent(preferredUrl);
const username = props.settings.username;
const description = props.settings.description;
const meta = [
{ property: "twitter:card", content: "summary" },
{ property: "twitter:creator", content: username },
{ property: "twitter:url", content: url },
{ property: "twitter:title", content: title },
{ property: "twitter:description", content: description }
];
if (props.media) {
let media;
if (!/^http(s?):\/\/+/.test(props.media)) {
media = location.origin + props.media;
}
meta.push({
property: "twitter:image",
content: media
});
}
}
class TwitterSocialButton extends Component {
handleClick = (event) => {
event.preventDefault();
if (window) {
window.open(this.url, "twitter_window", "width=750, height=650");
}
}
get url() {
const props = this.props;
const preferredUrl = props.url || location.origin + location.pathname;
const url = encodeURIComponent(preferredUrl);
const base = "https://twitter.com/intent/tweet";
const text = props.settings.description;
const username = props.settings.username;
let href = base + "?url=" + url + "&text=" + text;
if (username) {
href += "&via=" + username;
}
return href;
}
renderText() {
if (this.props.showText) {
return (
<Translation defaultValue="Share on Twitter" i18nKey="social.shareOnTwitter" />
);
}
return null;
}
render() {
const iconClassNames = classnames({
"fa": true,
"fa-twitter": this.props.altIcon !== true,
"fa-twitter-alt": this.props.altIcon,
[this.props.size]: this.props.size
});
return (
<a className="btn btn-flat twitter-share" aria-label="Share to Twitter" href="#" onClick={this.handleClick}
target="_blank"
>
<Helmet
meta={getTwitterMeta(this.props)}
/>
<i className={iconClassNames} />
{this.renderText()}
</a>
);
}
}
TwitterSocialButton.propTypes = {
altIcon: PropTypes.bool,
showText: PropTypes.bool,
size: PropTypes.string
};
export default TwitterSocialButton;
|
antd-mobile-custom/antd-mobile/lib/image-picker/PropsType.js | forwk1990/wechart-checkin | // import React from 'react';
"use strict"; |
src/js/components/icons/base/Info.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-info`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'info');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M15,17.0002864 C15,14.0000003 19,12.0005727 19,8.00028636 C19,4.00000002 16,1.00028636 12,1.00028636 C8,1.00028636 5,4.00000002 5,8.00028636 C5,12.0005727 9,14.0000003 9,17.0002864 C9,20.0005725 9,20 9,20 C9,22.0000003 10,22.9999997 12,23 C14,23.0000003 15,22.0000003 15,20 C15,20 15,20.0005725 15,17.0002864 Z M9,18 L15,18"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Info';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/Checkbox.js | pandoraui/react-ui | "use strict"
import React from 'react'
import classnames from 'classnames'
import { requireCss } from './themes'
requireCss('checkbox')
class Checkbox extends React.Component {
static displayName = "Checkbox"
static propTypes = {
checked: React.PropTypes.bool,
children: React.PropTypes.any,
className: React.PropTypes.string,
index: React.PropTypes.number,
onChange: React.PropTypes.func,
readOnly: React.PropTypes.bool,
style: React.PropTypes.object,
text: React.PropTypes.any,
value: React.PropTypes.any
}
componentWillReceiveProps (nextProps) {
if (nextProps.checked !== this.props.checked) {
this.setState({ checked: nextProps.checked })
}
}
state = {
checked: !!this.props.checked
}
handleChange (event) {
if (this.props.readOnly) {
return
}
this.setState({ checked: event.target.checked })
if (this.props.onChange) {
this.props.onChange(event.target.checked, this.props.value, this.props.index)
}
}
getValue () {
return this.refs.input.checked ? (this.props.value || true) : false
}
setValue (value) {
var checked = value === true || value === 1 || value === this.state.value
this.setState({ checked: checked })
}
render () {
return (
<label style={this.props.style} className={ classnames(this.props.className, "rct-checkbox") }>
<input ref="input"
type="checkbox"
disabled={this.props.readOnly}
onChange={this.handleChange.bind(this)}
checked={this.state.checked}
value={this.props.value}
/>
{this.props.text}
{this.props.children}
</label>
)
}
}
require('./FormControl').register(
'checkbox',
function (props) {
return <Checkbox {...props} />
},
Checkbox
)
export default Checkbox
|
ajax/libs/aui/7.5.0/aui/js/aui-experimental.js | joeyparrish/cdnjs | /*!
* @atlassian/aui - Atlassian User Interface Framework
* @version v7.5.0
* @link https://docs.atlassian.com/aui/latest/
* @license SEE LICENSE IN LICENSE.md
* @author Atlassian Pty Ltd.
*/
// src/js/aui/polyfills/placeholder.js
(typeof window === 'undefined' ? global : window).__452d3f8e5d643ab60faf3f564b8276d8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(function () {
if ('placeholder' in document.createElement('input')) {
return;
}
function applyDefaultText(input) {
var value = String(input.value).trim();
if (!value.length) {
input.value = input.getAttribute('placeholder');
(0, _jquery2.default)(input).addClass('aui-placeholder-shown');
}
}
(0, _skate2.default)('placeholder', {
type: _skate2.default.type.ATTRIBUTE,
events: {
blur: applyDefaultText,
focus: function focus(input) {
if (input.value === input.getAttribute('placeholder')) {
input.value = '';
(0, _jquery2.default)(input).removeClass('aui-placeholder-shown');
}
}
},
created: applyDefaultText
});
})();
return module.exports;
}).call(this);
// src/js/aui/banner.js
(typeof window === 'undefined' ? global : window).__e7296db63088f504f190097510a8efb3 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _template = __916a0948cf0486bc703577fb47b747c1;
var _template2 = _interopRequireDefault(_template);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ID_BANNER_CONTAINER = 'header';
function banner(options) {
var $banner = renderBannerElement(options);
pruneBannerContainer();
insertBanner($banner);
return $banner[0];
}
function renderBannerElement(options) {
var html = '<div class="aui-banner aui-banner-{type}" role="banner">' + '{body}' + '</div>';
var $banner = (0, _jquery2.default)((0, _template2.default)(html).fill({
'type': 'error',
'body:html': options.body || ''
}).toString());
return $banner;
}
function pruneBannerContainer() {
var $container = findContainer();
var $allBanners = $container.find('.aui-banner');
$allBanners.get().forEach(function (banner) {
var isBannerAriaHidden = banner.getAttribute('aria-hidden') === 'true';
if (isBannerAriaHidden) {
(0, _jquery2.default)(banner).remove();
}
});
}
function findContainer() {
return (0, _jquery2.default)('#' + ID_BANNER_CONTAINER);
}
function insertBanner($banner) {
var $bannerContainer = findContainer();
if (!$bannerContainer.length) {
throw new Error('You must implement the application header');
}
$banner.prependTo($bannerContainer);
(0, _animation.recomputeStyle)($banner);
$banner.attr('aria-hidden', 'false');
}
(0, _amdify2.default)('aui/banner', banner);
(0, _globalize2.default)('banner', banner);
exports.default = banner;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/button.js
(typeof window === 'undefined' ? global : window).__133851082a1337b5710e5a2aa98258e9 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _isBusy(button) {
return button.hasAttribute('aria-busy') && button.getAttribute('aria-busy') === 'true';
}
function isInputNode(button) {
return button.nodeName === 'INPUT';
}
(0, _skate2.default)('aui-button', {
type: _skate2.default.type.CLASSNAME,
prototype: {
/**
* Adds a spinner to the button and hides the text
*
* @returns {HTMLElement}
*/
busy: function busy() {
if (isInputNode(this) || _isBusy(this)) {
logger.warn('It is not valid to call busy() on an input button.');
return this;
}
(0, _jquery2.default)(this).spin();
this.setAttribute('aria-busy', true);
this.setAttribute('busy', '');
return this;
},
/**
* Removes the spinner and shows the tick on the button
*
* @returns {HTMLElement}
*/
idle: function idle() {
if (isInputNode(this) || !_isBusy(this)) {
logger.warn('It is not valid to call idle() on an input button.');
return this;
}
(0, _jquery2.default)(this).spinStop();
this.removeAttribute('aria-busy');
this.removeAttribute('busy');
return this;
},
/**
* Removes the spinner and shows the tick on the button
*
* @returns {Boolean}
*/
isBusy: function isBusy() {
if (isInputNode(this)) {
logger.warn('It is not valid to call isBusy() on an input button.');
return false;
}
return _isBusy(this);
}
}
});
(0, _amdify2.default)('aui/button');
return module.exports;
}).call(this);
// src/js-vendor/jquery/jquery.tipsy.js
(typeof window === 'undefined' ? global : window).__dbb945ae8033589d400f8c63e7d01524 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [[email protected]]
// released under the MIT license
//
// Modified by Atlassian
// https://github.com/atlassian/tipsy/tree/9095e37c7570c14acf0dbf040bb2466a0e2f23d4
(function($) {
function maybeCall(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
};
function isElementInDOM(ele) {
while (ele = ele.parentNode) {
if (ele == document) return true;
}
return false;
};
var tipsyIDcounter = 0;
function tipsyID() {
var tipsyID = tipsyIDcounter++;
return "tipsyuid" + tipsyID;
};
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = true;
this.fixTitle();
};
Tipsy.prototype = {
show: function() {
// if element is not in the DOM then don't show the Tipsy and return early
if (!isElementInDOM(this.$element[0])) {
return;
}
var title = this.getTitle();
if (title && this.enabled) {
var $tip = this.tip();
$tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
$tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
$tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
var that = this;
function tipOver() {
that.hoverTooltip = true;
}
function tipOut() {
if (that.hoverState == 'in') return; // If field is still focused.
that.hoverTooltip = false;
if (that.options.trigger != 'manual') {
var eventOut = that.options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy';
that.$element.trigger(eventOut);
}
}
if (this.options.hoverable) {
$tip.hover(tipOver, tipOut);
}
if (this.options.className) {
$tip.addClass(maybeCall(this.options.className, this.$element[0]));
}
var pos = $.extend({}, this.$element.offset(), {
width: this.$element[0].getBoundingClientRect().width,
height: this.$element[0].getBoundingClientRect().height
});
var tipCss = {};
var actualWidth = $tip[0].offsetWidth,
actualHeight = $tip[0].offsetHeight;
var gravity = maybeCall(this.options.gravity, this.$element[0]);
if (gravity.length === 2) {
if (gravity.charAt(1) === 'w') {
tipCss.left = pos.left + pos.width / 2 - 15;
} else {
tipCss.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
switch (gravity.charAt(0)) {
case 'n':
// left could already be set if gravity is 'nw' or 'ne'
if (typeof tipCss.left === 'undefined') {
tipCss.left = pos.left + pos.width / 2 - actualWidth / 2;
}
tipCss.top = pos.top + pos.height + this.options.offset;
break;
case 's':
// left could already be set if gravity is 'sw' or 'se'
if (typeof tipCss.left === 'undefined') {
tipCss.left = pos.left + pos.width / 2 - actualWidth / 2;
// We need to apply the left positioning and then recalculate the tooltip height
// If the tooltip is positioned close to the right edge of the window, it could cause
// the tooltip text to overflow and change height.
$tip.css(tipCss);
actualHeight = $tip[0].offsetHeight;
}
tipCss.top = pos.top - actualHeight - this.options.offset;
break;
case 'e':
tipCss.left = pos.left - actualWidth - this.options.offset;
tipCss.top = pos.top + pos.height / 2 - actualHeight / 2;
break;
case 'w':
tipCss.left = pos.left + pos.width + this.options.offset;
tipCss.top = pos.top + pos.height / 2 - actualHeight / 2;
break;
}
$tip.css(tipCss).addClass('tipsy-' + gravity);
$tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
if (this.options.fade) {
$tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
} else {
$tip.css({visibility: 'visible', opacity: this.options.opacity});
}
if (this.options.aria) {
var $tipID = tipsyID();
$tip.attr("id", $tipID);
this.$element.attr("aria-describedby", $tipID);
}
}
},
destroy: function(){
this.$element.removeData('tipsy');
this.unbindHandlers();
this.hide();
},
unbindHandlers: function() {
if(this.options.live){
$(this.$element.context).off('.tipsy');
} else {
this.$element.unbind('.tipsy');
}
},
hide: function() {
if (this.options.fade) {
this.tip().stop().fadeOut(function() { $(this).remove(); });
} else {
this.tip().remove();
}
if (this.options.aria) {
this.$element.removeAttr("aria-describedby");
}
},
fixTitle: function() {
var $e = this.$element;
if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
$e.attr('original-title', $e.attr('title') || '').removeAttr('title');
}
},
getTitle: function() {
var title, $e = this.$element, o = this.options;
this.fixTitle();
var title, o = this.options;
if (typeof o.title == 'string') {
title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
} else if (typeof o.title == 'function') {
title = o.title.call($e[0]);
}
title = ('' + title).replace(/(^\s*|\s*$)/, "");
return title || o.fallback;
},
tip: function() {
if (!this.$tip) {
this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>').attr("role","tooltip");
this.$tip.data('tipsy-pointee', this.$element[0]);
}
return this.$tip;
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide();
this.$element = null;
this.options = null;
}
},
enable: function() { this.enabled = true; },
disable: function() { this.enabled = false; },
toggleEnabled: function() { this.enabled = !this.enabled; }
};
$.fn.tipsy = function(options) {
if (options === true) {
return this.data('tipsy');
} else if (typeof options == 'string') {
var tipsy = this.data('tipsy');
if (tipsy) tipsy[options]();
return this;
}
options = $.extend({}, $.fn.tipsy.defaults, options);
if (options.hoverable) {
options.delayOut = options.delayOut || 20;
}
function get(ele) {
var tipsy = $.data(ele, 'tipsy');
if (!tipsy) {
tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
$.data(ele, 'tipsy', tipsy);
}
return tipsy;
}
function enter() {
var tipsy = get(this);
tipsy.hoverState = 'in';
if (options.delayIn == 0) {
tipsy.show();
} else {
tipsy.fixTitle();
setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
}
};
function leave() {
var tipsy = get(this);
tipsy.hoverState = 'out';
if (options.delayOut == 0) {
tipsy.hide();
} else {
setTimeout(function() { if (tipsy.hoverState == 'out' && !tipsy.hoverTooltip) tipsy.hide(); }, options.delayOut);
}
};
if (!options.live) this.each(function() { get(this); });
if (options.trigger != 'manual') {
var eventIn = options.trigger == 'hover' ? 'mouseenter.tipsy focus.tipsy' : 'focus.tipsy',
eventOut = options.trigger == 'hover' ? 'mouseleave.tipsy blur.tipsy' : 'blur.tipsy';
if (options.live) {
$(this.context).on(eventIn, this.selector, enter).on(eventOut, this.selector, leave);
} else {
this.bind(eventIn, enter).bind(eventOut, leave);
}
}
return this;
};
$.fn.tipsy.defaults = {
aria: false,
className: null,
delayIn: 0,
delayOut: 0,
fade: false,
fallback: '',
gravity: 'n',
html: false,
live: false,
hoverable: false,
offset: 0,
opacity: 0.8,
title: 'title',
trigger: 'hover'
};
$.fn.tipsy.revalidate = function() {
$('.tipsy').each(function() {
var pointee = $.data(this, 'tipsy-pointee');
if (!pointee || !isElementInDOM(pointee)) {
$(this).remove();
}
});
};
// Overwrite this method to provide options on a per-element basis.
// For example, you could store the gravity in a 'tipsy-gravity' attribute:
// return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
// (remember - do not modify 'options' in place!)
$.fn.tipsy.elementOptions = function(ele, options) {
return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
};
$.fn.tipsy.autoNS = function() {
return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
};
$.fn.tipsy.autoWE = function() {
return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
};
/**
* yields a closure of the supplied parameters, producing a function that takes
* no arguments and is suitable for use as an autogravity function like so:
*
* @param margin (int) - distance from the viewable region edge that an
* element should be before setting its tooltip's gravity to be away
* from that edge.
* @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
* if there are no viewable region edges effecting the tooltip's
* gravity. It will try to vary from this minimally, for example,
* if 'sw' is preferred and an element is near the right viewable
* region edge, but not the top edge, it will set the gravity for
* that element's tooltip to be 'se', preserving the southern
* component.
*/
$.fn.tipsy.autoBounds = function(margin, prefer) {
return function() {
var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
boundTop = $(document).scrollTop() + margin,
boundLeft = $(document).scrollLeft() + margin,
$this = $(this);
if ($this.offset().top < boundTop) dir.ns = 'n';
if ($this.offset().left < boundLeft) dir.ew = 'w';
if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
return dir.ns + (dir.ew ? dir.ew : '');
}
};
})(jQuery);
return module.exports;
}).call(this);
// src/js/aui/tooltip.js
(typeof window === 'undefined' ? global : window).__6999efc8461cc8bcf32a985dbca81aa1 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function handleStringOption($self, options, stringOption) {
// Pass string values straight to tipsy
$self.tipsy(stringOption);
if (stringOption === 'destroy') {
if (options.live) {
(0, _jquery2.default)($self.context).off('.tipsy', $self.selector);
} else {
$self.unbind('.tipsy');
}
}
return $self;
}
function bindTooltip($self, options) {
$self.tipsy(options);
var hideOnClick = options && options.hideOnClick && (options.trigger === 'hover' || !options.trigger && $self.tipsy.defaults.trigger === 'hover');
if (hideOnClick) {
var onClick = function onClick() {
(0, _jquery2.default)(this).tipsy('hide');
};
if (options.live) {
(0, _jquery2.default)($self.context).on('click.tipsy', $self.selector, onClick);
} else {
$self.bind('click.tipsy', onClick);
}
}
return $self;
}
_jquery2.default.fn.tooltip = function (options) {
var allOptions = _jquery2.default.extend({}, _jquery2.default.fn.tooltip.defaults, options);
// Handle live option
if (allOptions.live) {
if (typeof options === 'string') {
handleStringOption(this, allOptions, options);
} else {
bindTooltip(this, allOptions);
}
return this;
}
// If not live, bind each object in the collection
return this.each(function () {
var $this = (0, _jquery2.default)(this);
if (typeof options === 'string') {
handleStringOption($this, allOptions, options);
} else {
bindTooltip($this, allOptions);
}
return $this;
});
};
_jquery2.default.fn.tooltip.defaults = {
opacity: 1.0,
offset: 1,
delayIn: 500,
hoverable: true,
hideOnClick: true,
aria: true
};
return module.exports;
}).call(this);
// src/js/aui/checkbox-multiselect.js
(typeof window === 'undefined' ? global : window).__bf3c38e4a0e7481b849a297fccf30258 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__66a09fadeaffb2f1300bfa557f5294cd;
__6999efc8461cc8bcf32a985dbca81aa1;
__be3e01199078cdf5ded88dda6a8fbec9;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var templates = {
dropdown: function dropdown(items) {
function createSection() {
return (0, _jquery2.default)('<div class="aui-dropdown2-section">');
}
// clear items section
var $clearItemsSection = createSection();
(0, _jquery2.default)('<button />').attr({
type: 'button',
'data-aui-checkbox-multiselect-clear': '',
class: 'aui-button aui-button-link'
}).text(AJS.I18n.getText('aui.checkboxmultiselect.clear.selected')).appendTo($clearItemsSection);
// list of items
var $section = createSection();
var $itemList = (0, _jquery2.default)('<ul />').appendTo($section);
_jquery2.default.each(items, function (idx, item) {
var $li = (0, _jquery2.default)('<li />').attr({
class: item.styleClass || ''
}).appendTo($itemList);
var $a = (0, _jquery2.default)('<a />').text(item.label).attr('data-value', item.value).addClass('aui-dropdown2-checkbox aui-dropdown2-interactive').appendTo($li);
if (item.icon) {
(0, _jquery2.default)('<span />').addClass('aui-icon').css('backgroundImage', 'url(' + item.icon + ')")').appendTo($a);
}
if (item.selected) {
$a.addClass('aui-dropdown2-checked');
}
});
return (0, _jquery2.default)('<div />').append($clearItemsSection).append($section).html();
},
furniture: function furniture(name, optionsHtml) {
var dropdownId = name + '-dropdown';
var $select = (0, _jquery2.default)('<select />').attr({
name: name,
multiple: 'multiple'
}).html(optionsHtml);
var $dropdown = (0, _jquery2.default)('<div>').attr({
id: dropdownId,
class: 'aui-checkbox-multiselect-dropdown aui-dropdown2 aui-style-default'
});
var $button = (0, _jquery2.default)('<button />').attr({
class: 'aui-checkbox-multiselect-btn aui-button aui-dropdown2-trigger',
type: 'button',
'aria-owns': dropdownId,
'aria-haspopup': true
});
return (0, _jquery2.default)('<div />').append($select).append($button).append($dropdown).html();
}
};
/**
* Handles when user clicks an item in the dropdown list. Either selects or unselects the corresponding
* option in the <select>.
* @private
*/
function handleDropdownSelection(e) {
var $a = (0, _jquery2.default)(e.target);
var value = $a.attr('data-value');
updateOption(this, value, $a.hasClass('aui-dropdown2-checked'));
}
/**
* Selects or unselects the <option> corresponding the given value.
* @private
* @param component - Checkbox MultiSelect web component
* @param value - value of option to update
* @param {Boolean} selected - select or unselect it.
*/
function updateOption(component, value, selected) {
var $toUpdate = component.$select.find('option').filter(function () {
var $this = (0, _jquery2.default)(this);
return $this.attr('value') === value && $this.prop('selected') !== selected;
});
if ($toUpdate.length) {
$toUpdate.prop('selected', selected);
component.$select.trigger('change');
}
}
/**
* Enables 'clear all' button if there are any selected <option>s, otherwise disables it.
* @private
*/
function updateClearAll(component) {
component.$dropdown.find('[data-aui-checkbox-multiselect-clear]').prop('disabled', function () {
return getSelectedDescriptors(component).length < 1;
});
}
/**
* Gets button title used for tipsy. Is blank when dropdown is open so we don't get tipsy hanging over options.
* @private
* @param component
* @returns {string}
*/
function getButtonTitle(component) {
return component.$dropdown.is('[aria-hidden=false]') ? '' : getSelectedLabels(component).join(', ');
}
/**
* Converts a jQuery collection of <option> elements into an object that describes them.
* @param {jQuery} $options
* @returns {Array<Object>}
* @private
*/
function mapOptionDescriptors($options) {
return $options.map(function () {
var $option = (0, _jquery2.default)(this);
return {
value: $option.val(),
label: $option.text(),
icon: $option.data('icon'),
styleClass: $option.data('styleClass'),
title: $option.attr('title'),
disabled: $option.attr('disabled'),
selected: $option.prop('selected')
};
});
}
/**
* Gets label for when nothing is selected
* @returns {string}
* @private
*/
function getImplicitAllLabel(component) {
return (0, _jquery2.default)(component).data('allLabel') || 'All';
}
/**
* Renders dropdown with list of items representing the selected or unselect state of the <option>s in <select>
* @private
*/
function renderDropdown(component) {
component.$dropdown.html(templates.dropdown(getDescriptors(component)));
updateClearAll(component);
}
/**
* Renders button with the selected <option>'s innerText in a comma seperated list. If nothing is selected 'All'
* is displayed.
* @private
*/
function renderButton(component) {
var selectedLabels = getSelectedLabels(component);
var label = isImplicitAll(component) ? getImplicitAllLabel(component) : selectedLabels.join(', ');
component.$btn.text(label);
}
/**
* Gets descriptor for selected options, the descriptor is an object that contains meta information about
* the option, such as value, label, icon etc.
* @private
* @returns Array<Object>
*/
function getDescriptors(component) {
return mapOptionDescriptors(component.getOptions());
}
/**
* Gets descriptor for selected options, the descriptor is an object that contains meta information about
* the option, such as value, label, icon etc.
* @private
* @returns Array<Object>
*/
function getSelectedDescriptors(component) {
return mapOptionDescriptors(component.getSelectedOptions());
}
/**
* Gets the innerText of the selected options
* @private
* @returns Array<String>
*/
function getSelectedLabels(component) {
return _jquery2.default.map(getSelectedDescriptors(component), function (descriptor) {
return descriptor.label;
});
}
/**
* If nothing is selected, we take this to mean that everything is selected.
* @returns Boolean
*/
function isImplicitAll(component) {
return getSelectedDescriptors(component).length === 0;
}
var checkboxMultiselect = (0, _skate2.default)('aui-checkbox-multiselect', {
attached: function attached(component) {
// This used to be template logic, however, it breaks tests if we
// keep it there after starting to use native custom elements. This
// should be refactored.
//
// Ideally we should be templating the element within the "template"
// hook which will ensure it's templated prior to calling the
// "attached" callback.
var name = component.getAttribute('name') || (0, _uniqueId2.default)('aui-checkbox-multiselect-');
component.innerHTML = templates.furniture(name, component.innerHTML);
component.$select = (0, _jquery2.default)('select', component).change(function () {
renderButton(component);
updateClearAll(component);
});
component.$dropdown = (0, _jquery2.default)('.aui-checkbox-multiselect-dropdown', component).on('aui-dropdown2-item-check', handleDropdownSelection.bind(component)).on('aui-dropdown2-item-uncheck', handleDropdownSelection.bind(component)).on('click', 'button[data-aui-checkbox-multiselect-clear]', component.deselectAllOptions.bind(component));
component.$btn = (0, _jquery2.default)('.aui-checkbox-multiselect-btn', component).tooltip({
title: function title() {
return getButtonTitle(component);
}
});
renderButton(component);
renderDropdown(component);
},
prototype: {
/**
* Gets all options regardless of selected or unselected
* @returns {jQuery}
*/
getOptions: function getOptions() {
return this.$select.find('option');
},
/**
* Gets all selected options
* @returns {jQuery}
*/
getSelectedOptions: function getSelectedOptions() {
return this.$select.find('option:selected');
},
/**
* Sets <option> elements matching given value to selected
*/
selectOption: function selectOption(value) {
updateOption(this, value, true);
},
/**
* Sets <option> elements matching given value to unselected
*/
unselectOption: function unselectOption(value) {
updateOption(this, value, false);
},
/**
* Gets value of <select>
* @returns Array
*/
getValue: function getValue() {
return this.$select.val();
},
/**
* Unchecks all items in the dropdown and in the <select>
*/
deselectAllOptions: function deselectAllOptions() {
this.$select.val([]).trigger('change');
this.$dropdown.find('.aui-dropdown2-checked,.checked').removeClass('aui-dropdown2-checked checked');
},
/**
* Adds an option to the <select>
* @param descriptor
*/
addOption: function addOption(descriptor) {
(0, _jquery2.default)('<option />').attr({
value: descriptor.value,
icon: descriptor.icon,
disabled: descriptor.disabled,
selected: descriptor.selected,
title: descriptor.title
}).text(descriptor.label).appendTo(this.$select);
renderButton(this);
renderDropdown(this);
},
/**
* Removes options matching value from <select>
* @param value
*/
removeOption: function removeOption(value) {
this.$select.find("[value='" + value + "']").remove();
renderButton(this);
renderDropdown(this);
}
}
});
(0, _amdify2.default)('aui/checkbox-multiselect');
exports.default = checkboxMultiselect;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/dialog2.js
(typeof window === 'undefined' ? global : window).__3ac567a4ab4b829d5c6e6c81df33cbe8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _layer = __06224e18e744dc8a44794ab29f247385;
var _layer2 = _interopRequireDefault(_layer);
var _widget = __2d1b5481970dd1547e294d829464e03f;
var _widget2 = _interopRequireDefault(_widget);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaults = {
'aui-focus': 'false', // do not focus by default as it's overridden below
'aui-blanketed': 'true'
};
function applyDefaults($el) {
_jquery2.default.each(defaults, function (key, value) {
var dataKey = 'data-' + key;
if (!$el[0].hasAttribute(dataKey)) {
$el.attr(dataKey, value);
}
});
}
function Dialog2(selector) {
if (selector) {
this.$el = (0, _jquery2.default)(selector);
} else {
this.$el = (0, _jquery2.default)(aui.dialog.dialog2({}));
}
applyDefaults(this.$el);
}
Dialog2.prototype.on = function (event, fn) {
(0, _layer2.default)(this.$el).on(event, fn);
return this;
};
Dialog2.prototype.off = function (event, fn) {
(0, _layer2.default)(this.$el).off(event, fn);
return this;
};
Dialog2.prototype.show = function () {
(0, _layer2.default)(this.$el).show();
return this;
};
Dialog2.prototype.hide = function () {
(0, _layer2.default)(this.$el).hide();
return this;
};
Dialog2.prototype.remove = function () {
(0, _layer2.default)(this.$el).remove();
return this;
};
Dialog2.prototype.isVisible = function () {
return (0, _layer2.default)(this.$el).isVisible();
};
var dialog2Widget = (0, _widget2.default)('dialog2', Dialog2);
dialog2Widget.on = function (eventName, fn) {
_layer2.default.on(eventName, '.aui-dialog2', fn);
return this;
};
dialog2Widget.off = function (eventName, fn) {
_layer2.default.off(eventName, '.aui-dialog2', fn);
return this;
};
/* Live events */
(0, _jquery2.default)(document).on('click', '.aui-dialog2-header-close', function (e) {
e.preventDefault();
dialog2Widget((0, _jquery2.default)(this).closest('.aui-dialog2')).hide();
});
dialog2Widget.on('show', function (e, $el) {
var selectors = ['.aui-dialog2-content', '.aui-dialog2-footer', '.aui-dialog2-header'];
var $selected;
selectors.some(function (selector) {
$selected = $el.find(selector + ' :aui-tabbable');
return $selected.length;
});
$selected && $selected.first().focus();
});
dialog2Widget.on('hide', function (e, $el) {
var layer = (0, _layer2.default)($el);
if ($el.data('aui-remove-on-hide')) {
layer.remove();
}
});
(0, _amdify2.default)('aui/dialog2', dialog2Widget);
(0, _globalize2.default)('dialog2', dialog2Widget);
exports.default = dialog2Widget;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/expander.js
(typeof window === 'undefined' ? global : window).__f165ad68f415362651d0d7f733fcdcea = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var $document = (0, _jquery2.default)(document);
//convenience function because this needs to be run for all the events.
var getExpanderProperties = function getExpanderProperties(event) {
var properties = {};
properties.$trigger = (0, _jquery2.default)(event.currentTarget);
properties.$content = $document.find('#' + properties.$trigger.attr('aria-controls'));
properties.triggerIsParent = properties.$content.parent().filter(properties.$trigger).length !== 0;
properties.$shortContent = properties.triggerIsParent ? properties.$trigger.find('.aui-expander-short-content') : null;
properties.height = properties.$content.css('min-height');
properties.isCollapsible = properties.$trigger.data('collapsible') !== false;
properties.replaceText = properties.$trigger.attr('data-replace-text'); //can't use .data here because it doesn't update after the first call
properties.replaceSelector = properties.$trigger.data('replace-selector');
return properties;
};
var replaceText = function replaceText(properties) {
if (properties.replaceText) {
var $replaceElement = properties.replaceSelector ? properties.$trigger.find(properties.replaceSelector) : properties.$trigger;
properties.$trigger.attr('data-replace-text', $replaceElement.text());
$replaceElement.text(properties.replaceText);
}
};
//events that the expander listens to
var EXPANDER_EVENTS = {
'aui-expander-invoke': function auiExpanderInvoke(event) {
var $trigger = (0, _jquery2.default)(event.currentTarget);
var $content = $document.find('#' + $trigger.attr('aria-controls'));
var isCollapsible = $trigger.data('collapsible') !== false;
//determine if content should be expanded or collapsed
if ($content.attr('aria-expanded') === 'true' && isCollapsible) {
$trigger.trigger('aui-expander-collapse');
} else {
$trigger.trigger('aui-expander-expand');
}
},
'aui-expander-expand': function auiExpanderExpand(event) {
var properties = getExpanderProperties(event);
// If the expander is already expanded, do nothing.
if (properties.$content.attr('aria-expanded') === 'true') {
return;
}
properties.$content.attr('aria-expanded', 'true');
properties.$trigger.attr('aria-expanded', 'true');
if (properties.$content.outerHeight() > 0) {
properties.$content.attr('aria-hidden', 'false');
}
//handle replace text
replaceText(properties);
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.hide();
}
properties.$trigger.trigger('aui-expander-expanded');
},
'aui-expander-collapse': function auiExpanderCollapse(event) {
var properties = getExpanderProperties(event);
// If the expander is already collapsed, do nothing.
if (properties.$content.attr('aria-expanded') !== 'true') {
return;
}
//handle replace text
replaceText(properties);
//collapse the expander
properties.$content.attr('aria-expanded', 'false');
properties.$trigger.attr('aria-expanded', 'false');
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.show();
}
//handle the height option
if (properties.$content.outerHeight() === 0) {
properties.$content.attr('aria-hidden', 'true');
}
properties.$trigger.trigger('aui-expander-collapsed');
},
'click.aui-expander': function clickAuiExpander(event) {
var $target = (0, _jquery2.default)(event.currentTarget);
$target.trigger('aui-expander-invoke', event.currentTarget);
}
};
//delegate events to the triggers on the page
$document.on(EXPANDER_EVENTS, '.aui-expander-trigger');
return module.exports;
}).call(this);
// src/js/aui/flag.js
(typeof window === 'undefined' ? global : window).__7c68b94bd1e7e5a2f72d197f55d1d459 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _template = __916a0948cf0486bc703577fb47b747c1;
var _template2 = _interopRequireDefault(_template);
var _customEvent = __16bf5f1d761138a726209288b7afb338;
var _customEvent2 = _interopRequireDefault(_customEvent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AUTO_CLOSE_TIME = 5000;
var ID_FLAG_CONTAINER = 'aui-flag-container';
var defaultOptions = {
body: '',
close: 'manual',
title: '',
type: 'info'
};
function flag(options) {
options = _jquery2.default.extend({}, defaultOptions, options);
var $flag = renderFlagElement(options);
extendFlagElement($flag);
if (options.close === 'auto') {
makeCloseable($flag);
makeAutoClosable($flag);
} else if (options.close === 'manual') {
makeCloseable($flag);
}
pruneFlagContainer();
return insertFlag($flag);
}
function extendFlagElement($flag) {
var flag = $flag[0];
flag.close = function () {
closeFlag($flag);
};
}
function renderFlagElement(options) {
var html = '<div class="aui-flag">' + '<div class="aui-message aui-message-{type} {type} {closeable} shadowed">' + '<p class="title">' + '<strong>{title}</strong>' + '</p>' + '{body}<!-- .aui-message -->' + '</div>' + '</div>';
var rendered = (0, _template2.default)(html).fill({
'body:html': options.body || '',
closeable: options.close === 'never' ? '' : 'closeable',
title: options.title || '',
type: options.type
}).toString();
return (0, _jquery2.default)(rendered);
}
function makeCloseable($flag) {
var $icon = (0, _jquery2.default)('<span class="aui-icon icon-close" role="button" tabindex="0"></span>');
$icon.click(function () {
closeFlag($flag);
});
$icon.keypress(function (e) {
if (e.which === _keyCode2.default.ENTER || e.which === _keyCode2.default.SPACE) {
closeFlag($flag);
e.preventDefault();
}
});
return $flag.find('.aui-message').append($icon)[0];
}
function makeAutoClosable($flag) {
$flag.find('.aui-message').addClass('aui-will-close');
setTimeout(function () {
$flag[0].close();
}, AUTO_CLOSE_TIME);
}
function closeFlag($flagToClose) {
var flag = $flagToClose.get(0);
flag.setAttribute('aria-hidden', 'true');
flag.dispatchEvent(new _customEvent2.default('aui-flag-close', { bubbles: true }));
return flag;
}
function pruneFlagContainer() {
var $container = findContainer();
var $allFlags = $container.find('.aui-flag');
$allFlags.get().forEach(function (flag) {
var isFlagAriaHidden = flag.getAttribute('aria-hidden') === 'true';
if (isFlagAriaHidden) {
(0, _jquery2.default)(flag).remove();
}
});
}
function findContainer() {
return (0, _jquery2.default)('#' + ID_FLAG_CONTAINER);
}
function insertFlag($flag) {
var $flagContainer = findContainer();
if (!$flagContainer.length) {
$flagContainer = (0, _jquery2.default)('<div id="' + ID_FLAG_CONTAINER + '"></div>');
(0, _jquery2.default)('body').prepend($flagContainer);
}
$flag.appendTo($flagContainer);
(0, _animation.recomputeStyle)($flag);
return $flag.attr('aria-hidden', 'false')[0];
}
(0, _amdify2.default)('aui/flag', flag);
(0, _globalize2.default)('flag', flag);
exports.default = flag;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/form-notification.js
(typeof window === 'undefined' ? global : window).__223d4ffbfb11c7b1196e30d8f0783cb8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NOTIFICATION_NAMESPACE = 'aui-form-notification';
var CLASS_NOTIFICATION_INITIALISED = '_aui-form-notification-initialised';
var CLASS_NOTIFICATION_ICON = 'aui-icon-notification';
var CLASS_TOOLTIP = NOTIFICATION_NAMESPACE + '-tooltip';
var CLASS_TOOLTIP_ERROR = CLASS_TOOLTIP + '-error';
var CLASS_TOOLTIP_INFO = CLASS_TOOLTIP + '-info';
var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-';
var ATTRIBUTE_NOTIFICATION_WAIT = ATTRIBUTE_NOTIFICATION_PREFIX + 'wait';
var ATTRIBUTE_NOTIFICATION_INFO = ATTRIBUTE_NOTIFICATION_PREFIX + 'info';
var ATTRIBUTE_NOTIFICATION_ERROR = ATTRIBUTE_NOTIFICATION_PREFIX + 'error';
var ATTRIBUTE_NOTIFICATION_SUCCESS = ATTRIBUTE_NOTIFICATION_PREFIX + 'success';
var ATTRIBUTE_TOOLTIP_POSITION = NOTIFICATION_NAMESPACE + '-position';
var NOTIFICATION_PRIORITY = [ATTRIBUTE_NOTIFICATION_ERROR, ATTRIBUTE_NOTIFICATION_SUCCESS, ATTRIBUTE_NOTIFICATION_WAIT, ATTRIBUTE_NOTIFICATION_INFO];
var notificationFields = [];
/* --- Tipsy configuration --- */
var TIPSY_OPACITY = 1;
var TIPSY_OFFSET_INSIDE_FIELD = 9; //offset in px from the icon to the start of the tipsy
var TIPSY_OFFSET_OUTSIDE_FIELD = 3;
function initialiseNotification($field) {
if (!isFieldInitialised($field)) {
prepareFieldMarkup($field);
initialiseTooltip($field);
bindFieldEvents($field);
synchroniseNotificationDisplay($field);
}
notificationFields.push($field);
}
function isFieldInitialised($field) {
return $field.hasClass(CLASS_NOTIFICATION_INITIALISED);
}
function constructFieldIcon() {
return (0, _jquery2.default)('<span class="aui-icon aui-icon-small ' + CLASS_NOTIFICATION_ICON + '"/>');
}
function prepareFieldMarkup($field) {
$field.addClass(CLASS_NOTIFICATION_INITIALISED);
appendIconToField($field);
}
function appendIconToField($field) {
var $icon = constructFieldIcon();
$field.after($icon);
}
function initialiseTooltip($field) {
getTooltipAnchor($field).tipsy({
gravity: getTipsyGravity($field),
title: function title() {
return getNotificationMessage($field);
},
trigger: 'manual',
offset: canContainIcon($field) ? TIPSY_OFFSET_INSIDE_FIELD : TIPSY_OFFSET_OUTSIDE_FIELD,
opacity: TIPSY_OPACITY,
className: function className() {
return 'aui-form-notification-tooltip ' + getNotificationClass($field);
},
html: true
});
}
// A list of HTML5 input types that don't typically get augmented by the browser, so are safe to put icons inside of.
var unadornedInputFields = ['text', 'url', 'email', 'tel', 'password'];
function canContainIcon($field) {
return unadornedInputFields.indexOf($field.attr('type')) !== -1;
}
function getNotificationMessage($field) {
var notificationType = getFieldNotificationType($field);
var message = notificationType ? $field.attr(notificationType) : '';
return formatMessage(message);
}
function formatMessage(message) {
if (message === '') {
return message;
}
var messageArray = jsonToArray(message);
if (messageArray.length === 1) {
return messageArray[0];
} else {
return '<ul><li>' + messageArray.join('</li><li>') + '</li></ul>';
}
}
function jsonToArray(jsonOrString) {
var jsonArray;
try {
jsonArray = JSON.parse(jsonOrString);
} catch (exception) {
jsonArray = [jsonOrString];
}
return jsonArray;
}
function getNotificationClass($field) {
var notificationType = getFieldNotificationType($field);
if (notificationType === ATTRIBUTE_NOTIFICATION_ERROR) {
return CLASS_TOOLTIP_ERROR;
} else if (notificationType === ATTRIBUTE_NOTIFICATION_INFO) {
return CLASS_TOOLTIP_INFO;
}
}
function getFieldNotificationType($field) {
var fieldNotificationType;
NOTIFICATION_PRIORITY.some(function (prioritisedNotification) {
if ($field.is('[' + prioritisedNotification + ']')) {
fieldNotificationType = prioritisedNotification;
return true;
}
});
return fieldNotificationType;
}
function bindFieldEvents($field) {
if (focusTogglesTooltip($field)) {
bindFieldTabEvents($field);
}
}
function focusTogglesTooltip($field) {
return $field.is(':aui-focusable');
}
function fieldHasTooltip($field) {
return getNotificationMessage($field) !== '';
}
function showTooltip($field) {
getTooltipAnchor($field).tipsy('show');
if (focusTogglesTooltip($field)) {
bindTooltipTabEvents($field);
}
}
function hideTooltip($field) {
getTooltipAnchor($field).tipsy('hide');
}
function bindFocusTooltipInteractions() {
document.addEventListener('focus', function (e) {
notificationFields.forEach(function (field) {
var $field = (0, _jquery2.default)(field);
var $tooltip = getTooltip($field);
if (!focusTogglesTooltip($field)) {
return;
}
var isFocusInTooltip = $tooltip && _jquery2.default.contains($tooltip[0], e.target);
var isFocusTargetField = $field.is(e.target);
var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $field);
if (isFocusTargetField || isFocusTargetChildOfField) {
showTooltip($field);
} else if ($tooltip && !isFocusInTooltip) {
hideTooltip($field);
}
});
}, true);
}
bindFocusTooltipInteractions();
function isFocusEventTargetInElement(event, $element) {
return (0, _jquery2.default)(event.target).closest($element).length > 0;
}
function bindFieldTabEvents($field) {
$field.on('keydown', function (e) {
if (isNormalTab(e) && fieldHasTooltip($field)) {
var $firstTooltipLink = getFirstTooltipLink($field);
if ($firstTooltipLink.length) {
$firstTooltipLink.focus();
e.preventDefault();
}
}
});
}
function isNormalTab(e) {
return e.keyCode === _keyCode2.default.TAB && !e.shiftKey && !e.altKey;
}
function isShiftTab(e) {
return e.keyCode === _keyCode2.default.TAB && e.shiftKey;
}
function getFirstTooltipLink($field) {
return getTooltip($field).find(':aui-tabbable').first();
}
function getLastTooltipLink($field) {
return getTooltip($field).find(':aui-tabbable').last();
}
function getTooltip($field) {
var $anchor = getTooltipAnchor($field);
if ($anchor.data('tipsy')) {
return $anchor.data('tipsy').$tip;
}
}
function bindTooltipTabEvents($field) {
var $tooltip = getTooltip($field);
$tooltip.on('keydown', function (e) {
var leavingTooltipForwards = elementIsActive(getLastTooltipLink($field));
var leavingTooltipBackwards = elementIsActive(getFirstTooltipLink($field));
if (isNormalTab(e) && leavingTooltipForwards) {
if (leavingTooltipForwards) {
$field.focus();
}
}
if (isShiftTab(e) && leavingTooltipBackwards) {
if (leavingTooltipBackwards) {
$field.focus();
e.preventDefault();
}
}
});
}
function getTipsyGravity($field) {
var position = $field.data(ATTRIBUTE_TOOLTIP_POSITION) || 'side';
var gravityMap = {
side: 'w',
top: 'se',
bottom: 'ne'
};
var gravity = gravityMap[position];
if (!gravity) {
gravity = 'w';
logger.warn('Invalid notification position: "' + position + '". Valid options are "side", "bottom, "top"');
}
return gravity;
}
function getTooltipAnchor($field) {
return getFieldIcon($field);
}
function getFieldIcon($field) {
return $field.next('.' + CLASS_NOTIFICATION_ICON);
}
function elementIsActive($el) {
var el = $el instanceof _jquery2.default ? $el[0] : $el;
return el && el === document.activeElement;
}
function synchroniseNotificationDisplay(field) {
var $field = (0, _jquery2.default)(field);
if (!isFieldInitialised($field)) {
return;
}
var notificationType = getFieldNotificationType($field);
var showSpinner = notificationType === ATTRIBUTE_NOTIFICATION_WAIT;
setFieldSpinner($field, showSpinner);
var noNotificationOnField = !notificationType;
if (noNotificationOnField) {
hideTooltip($field);
return;
}
var message = getNotificationMessage($field);
var fieldContainsActiveElement = _jquery2.default.contains($field[0], document.activeElement);
var tooltipShouldBeVisible = fieldContainsActiveElement || elementIsActive($field) || !focusTogglesTooltip($field);
if (tooltipShouldBeVisible && message) {
showTooltip($field);
} else {
hideTooltip($field);
}
}
function setFieldSpinner($field, isSpinnerVisible) {
if (isSpinnerVisible) {
getFieldIcon($field).addClass('aui-icon-wait');
} else {
getFieldIcon($field).removeClass('aui-icon-wait');
}
}
document.addEventListener('mousedown', function (e) {
var isTargetLink = (0, _jquery2.default)(e.target).is('a');
if (isTargetLink) {
return;
}
var isTargetTooltip = (0, _jquery2.default)(e.target).closest('.aui-form-notification-tooltip').length > 0;
if (isTargetTooltip) {
return;
}
var $allNotificationFields = (0, _jquery2.default)('[data-aui-notification-field]');
$allNotificationFields.each(function () {
var $notificationField = (0, _jquery2.default)(this);
var targetIsThisField = $notificationField.is(e.target);
var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $notificationField);
if (!targetIsThisField && !isFocusTargetChildOfField) {
hideTooltip($notificationField);
}
if (focusTogglesTooltip($notificationField)) {
hideTooltip($notificationField);
}
});
});
(0, _skate2.default)('data-aui-notification-field', {
attached: function attached(element) {
initialiseNotification((0, _jquery2.default)(element));
},
attributes: function () {
var attrs = {};
NOTIFICATION_PRIORITY.forEach(function (type) {
attrs[type] = synchroniseNotificationDisplay;
});
return attrs;
}(),
type: _skate2.default.type.ATTRIBUTE
});
(0, _amdify2.default)('aui/form-notification');
return module.exports;
}).call(this);
// src/js/aui/form-validation/validator-register.js
(typeof window === 'undefined' ? global : window).__d1c8e25e9e01e4d366088e44abd86cd0 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ATTRIBUTE_RESERVED_ARGUMENTS = ['displayfield', 'watchfield', 'when', 'novalidate', 'state'];
var _validators = [];
function getReservedArgument(validatorArguments) {
var reservedArgument = false;
validatorArguments.some(function (arg) {
var isReserved = _jquery2.default.inArray(arg, ATTRIBUTE_RESERVED_ARGUMENTS) !== -1;
if (isReserved) {
reservedArgument = arg;
}
return isReserved;
});
return reservedArgument;
}
/**
* Register a validator that can be used to validate fields. The main entry point for validator plugins.
* @param trigger - when to run the validator. Can be an array of arguments, or a selector
* @param validatorFunction - the function that will be called on the field to determine validation. Receives
* field - the field that is being validated
* args - the arguments that have been specified in HTML markup.
*/
function registerValidator(trigger, validatorFunction) {
var triggerSelector;
if (typeof trigger === 'string') {
triggerSelector = trigger;
} else {
var reservedArgument = getReservedArgument(trigger);
if (reservedArgument) {
logger.warn('Validators cannot be registered with the argument "' + reservedArgument + '", as it is a reserved argument.');
return false;
}
triggerSelector = '[data-aui-validation-' + trigger.join('],[data-aui-validation-') + ']';
}
var validator = {
validatorFunction: validatorFunction,
validatorTrigger: triggerSelector
};
_validators.push(validator);
return validator;
}
var validatorRegister = {
register: registerValidator,
validators: function validators() {
return _validators;
}
};
(0, _amdify2.default)('aui/form-validation/validator-register', validatorRegister);
exports.default = validatorRegister;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/form-validation/basic-validators.js
(typeof window === 'undefined' ? global : window).__22130538f5919f6e261036684b13c6f2 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _format = __a0d4f23ad4f9b40c6f8c8e4e6922c981;
var _format2 = _interopRequireDefault(_format);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _validatorRegister = __d1c8e25e9e01e4d366088e44abd86cd0;
var _validatorRegister2 = _interopRequireDefault(_validatorRegister);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//Input length
// eslint-disable-line no-unused-vars
function minMaxLength(field) {
var fieldValueLength = field.el.value.length;
var fieldIsEmpty = fieldValueLength === 0;
var minlength = parseInt(field.args('minlength'), 10);
var maxlength = parseInt(field.args('maxlength'), 10);
if (minlength && maxlength && minlength === maxlength && !fieldIsEmpty && fieldValueLength !== minlength) {
var exactlengthMessage = makeMessage('exactlength', field.args, [minlength]);
field.invalidate(exactlengthMessage);
} else if (minlength && fieldValueLength < minlength && !fieldIsEmpty) {
var minlengthMessage = makeMessage('minlength', field.args);
field.invalidate(minlengthMessage);
} else if (maxlength && fieldValueLength > maxlength) {
var maxlengthMessage = makeMessage('maxlength', field.args);
field.invalidate(maxlengthMessage);
} else {
field.validate();
}
} // eslint-disable-line no-unused-vars
_validatorRegister2.default.register(['maxlength', 'minlength'], minMaxLength); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[maxlength],[minlength]', minMaxLength);
//Field matching
_validatorRegister2.default.register(['matchingfield'], function (field) {
var thisFieldValue = field.el.value;
var matchingField = document.getElementById(field.args('matchingfield'));
var matchingFieldValue = matchingField.value;
var matchingFieldMessage = makeMessage('matchingfield', field.args, [thisFieldValue, matchingFieldValue]);
var shouldHidePasswords = isPasswordField(field.el) || isPasswordField(matchingField);
if (shouldHidePasswords) {
matchingFieldMessage = makeMessage('matchingfield-novalue', field.args);
}
if (!thisFieldValue || !matchingFieldValue) {
field.validate();
} else if (matchingFieldValue !== thisFieldValue) {
field.invalidate(matchingFieldMessage);
} else {
field.validate();
}
});
function isPasswordField(field) {
return field.getAttribute('type') === 'password';
}
//Banned words
_validatorRegister2.default.register(['doesnotcontain'], function (field) {
var doesNotContainMessage = makeMessage('doesnotcontain', field.args);
if (field.el.value.indexOf(field.args('doesnotcontain')) === -1) {
field.validate();
} else {
field.invalidate(doesNotContainMessage);
}
});
//Matches regex
function matchesRegex(val, regex) {
var matches = val.match(regex);
if (!matches) {
return false;
}
var isExactMatch = val === matches[0];
return isExactMatch;
}
function pattern(field) {
var patternMessage = makeMessage('pattern', field.args);
if (matchesRegex(field.el.value, new RegExp(field.args('pattern')))) {
field.validate();
} else {
field.invalidate(patternMessage);
}
}
_validatorRegister2.default.register(['pattern'], pattern); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[pattern]', pattern);
//Native Required
function required(field) {
var requiredMessage = makeMessage('required', field.args);
if (field.el.value) {
field.validate();
} else {
field.invalidate(requiredMessage);
}
}
_validatorRegister2.default.register(['required'], required); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[required]', required);
//Field value range (between min and max)
function minOrMax(field) {
var validNumberMessage = makeMessage('validnumber', field.args);
var fieldValue = parseInt(field.el.value, 10);
if (isNaN(fieldValue)) {
field.invalidate(validNumberMessage);
return;
}
var minValue = field.args('min');
var maxValue = field.args('max');
if (minValue && fieldValue < parseInt(minValue, 10)) {
field.invalidate(makeMessage('min', field.args));
} else if (maxValue && fieldValue > parseInt(maxValue, 10)) {
field.invalidate(makeMessage('max', field.args));
} else {
field.validate();
}
}
_validatorRegister2.default.register(['min', 'max'], minOrMax); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[min],[max]', minOrMax);
//Date format
_validatorRegister2.default.register(['dateformat'], function (field) {
var dateFormatSymbolic = field.args('dateformat');
var dateFormatMessage = makeMessage('dateformat', field.args);
var symbolRegexMap = {
'Y': '[0-9]{4}',
'y': '[0-9]{2}',
'm': '(0?[1-9]|10|11|12)',
'M': '[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]',
'D': '[Mon|Tue|Wed|Thu|Fri|Sat|Sun]',
'd': '([0-2]?[1-9]|10|20|30|31)'
};
var dateFormatSymbolArray = dateFormatSymbolic.split('');
var dateFormatRegexString = '';
dateFormatSymbolArray.forEach(function (dateSymbol) {
var isRecognisedSymbol = symbolRegexMap.hasOwnProperty(dateSymbol);
if (isRecognisedSymbol) {
dateFormatRegexString += symbolRegexMap[dateSymbol];
} else {
dateFormatRegexString += dateSymbol;
}
});
var dateFormatRegex = new RegExp(dateFormatRegexString + '$', 'i');
var isValidDate = matchesRegex(field.el.value, dateFormatRegex);
if (isValidDate) {
field.validate();
} else {
field.invalidate(dateFormatMessage);
}
});
//Checkbox count
_validatorRegister2.default.register(['minchecked', 'maxchecked'], function (field) {
var amountChecked = (0, _jquery2.default)(field.el).find(':checked').length;
var aboveMin = !field.args('minchecked') || amountChecked >= field.args('minchecked');
var belowMax = !field.args('maxchecked') || amountChecked <= field.args('maxchecked');
var belowMinMessage = makeMessage('minchecked', field.args);
var aboveMaxMessage = makeMessage('maxchecked', field.args);
if (aboveMin && belowMax) {
field.validate();
} else if (!aboveMin) {
field.invalidate(belowMinMessage);
} else if (!belowMax) {
field.invalidate(aboveMaxMessage);
}
});
/*
Retrieves a message for a plugin validator through the data attributes or the default (which is in the i18n file)
*/
function makeMessage(key, accessorFunction, customTokens) {
var inFlatpackMode = AJS.I18n.keys !== undefined;
var defaultMessage;
if (inFlatpackMode) {
defaultMessage = AJS.I18n.keys['aui.validation.message.' + key];
} else {
defaultMessage = pluginI18nMessages[key];
}
var messageTokens = customTokens;
if (!customTokens) {
messageTokens = [accessorFunction(key)];
}
var customMessageUnformatted = accessorFunction(key + '-msg');
var formattingArguments;
if (customMessageUnformatted) {
formattingArguments = [customMessageUnformatted].concat(messageTokens);
} else {
formattingArguments = [defaultMessage].concat(messageTokens);
}
return AJS.format.apply(null, formattingArguments);
}
/*
The value AJS.I18n.getText('aui.validation.message...') (defaultMessage) cannot be refactored as it
must appear verbatim for the plugin I18n transformation to pick it up
*/
var pluginI18nMessages = {
minlength: AJS.I18n.getText('aui.validation.message.minlength'),
maxlength: AJS.I18n.getText('aui.validation.message.maxlength'),
exactlength: AJS.I18n.getText('aui.validation.message.exactlength'),
matchingfield: AJS.I18n.getText('aui.validation.message.matchingfield'),
'matchingfield-novalue': AJS.I18n.getText('aui.validation.message.matchingfield-novalue'),
doesnotcontain: AJS.I18n.getText('aui.validation.message.doesnotcontain'),
pattern: AJS.I18n.getText('aui.validation.message.pattern'),
required: AJS.I18n.getText('aui.validation.message.required'),
validnumber: AJS.I18n.getText('aui.validation.message.validnumber'),
min: AJS.I18n.getText('aui.validation.message.min'),
max: AJS.I18n.getText('aui.validation.message.max'),
dateformat: AJS.I18n.getText('aui.validation.message.dateformat'),
minchecked: AJS.I18n.getText('aui.validation.message.minchecked'),
maxchecked: AJS.I18n.getText('aui.validation.message.maxchecked')
};
(0, _amdify2.default)('aui/form-validation/basic-validators');
return module.exports;
}).call(this);
// src/js/aui/form-validation.js
(typeof window === 'undefined' ? global : window).__bd4ecc7f267c4325495affa1d72b9196 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__223d4ffbfb11c7b1196e30d8f0783cb8;
__22130538f5919f6e261036684b13c6f2;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _deprecation = __4ddcc788b1704f76a51559fc0e0d2968;
var deprecate = _interopRequireWildcard(_deprecation);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _validatorRegister = __d1c8e25e9e01e4d366088e44abd86cd0;
var _validatorRegister2 = _interopRequireDefault(_validatorRegister);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//Attributes
var ATTRIBUTE_VALIDATION_OPTION_PREFIX = 'aui-validation-';
var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-';
var ATTRIBUTE_FIELD_STATE = 'aui-validation-state';
var INVALID = 'invalid';
var VALID = 'valid';
var VALIDATING = 'validating';
var UNVALIDATED = 'unvalidated';
var ATTRIBUTE_VALIDATION_FIELD_COMPONENT = 'data-aui-validation-field';
//Classes
var CLASS_VALIDATION_INITIALISED = '_aui-form-validation-initialised';
//Events
var EVENT_FIELD_STATE_CHANGED = '_aui-internal-field-state-changed';
function isFieldInitialised($field) {
return $field.hasClass(CLASS_VALIDATION_INITIALISED);
}
function initValidation($field) {
if (!isFieldInitialised($field)) {
initialiseDisplayField($field);
prepareFieldMarkup($field);
bindFieldEvents($field);
changeFieldState($field, UNVALIDATED);
}
}
function initialiseDisplayField($field) {
getDisplayField($field).attr('data-aui-notification-field', '');
}
function prepareFieldMarkup($field) {
$field.addClass(CLASS_VALIDATION_INITIALISED);
}
function bindFieldEvents($field) {
bindStopTypingEvent($field);
bindValidationEvent($field);
}
function bindStopTypingEvent($field) {
var keyUpTimer;
var triggerStopTypingEvent = function triggerStopTypingEvent() {
$field.trigger('aui-stop-typing');
};
$field.on('keyup', function () {
clearTimeout(keyUpTimer);
keyUpTimer = setTimeout(triggerStopTypingEvent, 1500);
});
}
function bindValidationEvent($field) {
var validateWhen = getValidationOption($field, 'when');
var watchedFieldID = getValidationOption($field, 'watchfield');
var elementsToWatch = watchedFieldID ? $field.add('#' + watchedFieldID) : $field;
elementsToWatch.on(validateWhen, function startValidation() {
validationTriggeredHandler($field);
});
}
function validationTriggeredHandler($field) {
var noValidate = getValidationOption($field, 'novalidate');
if (noValidate) {
changeFieldState($field, VALID);
return;
}
return startValidating($field);
}
function getValidationOption($field, option) {
var defaults = {
'when': 'change'
};
var optionValue = $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + option);
if (!optionValue) {
optionValue = defaults[option];
}
return optionValue;
}
function startValidating($field) {
clearFieldMessages($field);
var validatorsToRun = getActivatedValidators($field);
changeFieldState($field, VALIDATING);
var deferreds = runValidatorsAndGetDeferred($field, validatorsToRun);
var fieldValidators = _jquery2.default.when.apply(_jquery2.default, deferreds);
fieldValidators.done(function () {
changeFieldState($field, VALID);
});
return fieldValidators;
}
function clearFieldMessages($field) {
setFieldNotification(getDisplayField($field), 'none');
}
function getValidators() {
return _validatorRegister2.default.validators();
}
function getActivatedValidators($field) {
var callList = [];
getValidators().forEach(function (validator, index) {
var validatorTrigger = validator.validatorTrigger;
var runThisValidator = $field.is(validatorTrigger);
if (runThisValidator) {
callList.push(index);
}
});
return callList;
}
function runValidatorsAndGetDeferred($field, validatorsToRun) {
var allDeferreds = [];
validatorsToRun.forEach(function (validatorIndex) {
var validatorFunction = getValidators()[validatorIndex].validatorFunction;
var deferred = new _jquery2.default.Deferred();
var validatorContext = createValidatorContext($field, deferred);
validatorFunction(validatorContext);
allDeferreds.push(deferred);
});
return allDeferreds;
}
function createValidatorContext($field, validatorDeferred) {
var context = {
validate: function validate() {
validatorDeferred.resolve();
},
invalidate: function invalidate(message) {
changeFieldState($field, INVALID, message);
validatorDeferred.reject();
},
args: createArgumentAccessorFunction($field),
el: $field[0],
$el: $field
};
deprecate.prop(context, '$el', {
sinceVersion: '5.9.0',
removeInVersion: '8.0.0',
alternativeName: 'el',
extraInfo: 'See https://ecosystem.atlassian.net/browse/AUI-3263.'
});
return context;
}
function createArgumentAccessorFunction($field) {
return function (arg) {
return $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + arg) || $field.attr(arg);
};
}
function changeFieldState($field, state, message) {
$field.attr('data-' + ATTRIBUTE_FIELD_STATE, state);
if (state === UNVALIDATED) {
return;
}
$field.trigger(_jquery2.default.Event(EVENT_FIELD_STATE_CHANGED));
var $displayField = getDisplayField($field);
var stateToNotificationTypeMap = {};
stateToNotificationTypeMap[VALIDATING] = 'wait';
stateToNotificationTypeMap[INVALID] = 'error';
stateToNotificationTypeMap[VALID] = 'success';
var notificationType = stateToNotificationTypeMap[state];
if (state === VALIDATING) {
showSpinnerIfSlow($field);
} else {
setFieldNotification($displayField, notificationType, message);
}
}
function showSpinnerIfSlow($field) {
setTimeout(function () {
var stillValidating = getFieldState($field) === VALIDATING;
if (stillValidating) {
setFieldNotification($field, 'wait');
}
}, 500);
}
function setFieldNotification($field, type, message) {
var spinnerWasVisible = isSpinnerVisible($field);
removeIconOnlyNotifications($field);
var skipShowingSuccessNotification = type === 'success' && !spinnerWasVisible;
if (skipShowingSuccessNotification) {
return;
}
if (type === 'none') {
removeFieldNotification($field, 'error');
} else {
var previousMessage = $field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type) || '[]';
var newMessage = message ? combineJSONMessages(message, previousMessage) : '';
$field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type, newMessage);
}
}
function removeIconOnlyNotifications($field) {
removeFieldNotification($field, 'wait');
removeFieldNotification($field, 'success');
}
function removeFieldNotification($field, type) {
$field.removeAttr(ATTRIBUTE_NOTIFICATION_PREFIX + type);
}
function isSpinnerVisible($field) {
return $field.is('[' + ATTRIBUTE_NOTIFICATION_PREFIX + 'wait]');
}
function combineJSONMessages(newString, previousString) {
var previousStackedMessageList = JSON.parse(previousString);
var newStackedMessageList = previousStackedMessageList.concat([newString]);
var newStackedMessage = JSON.stringify(newStackedMessageList);
return newStackedMessage;
}
function getDisplayField($field) {
var displayFieldID = getValidationOption($field, 'displayfield');
var notifyOnSelf = displayFieldID === undefined;
return notifyOnSelf ? $field : (0, _jquery2.default)('#' + displayFieldID);
}
function getFieldState($field) {
return $field.attr('data-' + ATTRIBUTE_FIELD_STATE);
}
/**
* Trigger validation on a field manually
* @param $field the field that validation should be triggered for
*/
function validateField($field) {
$field = (0, _jquery2.default)($field);
validationTriggeredHandler($field);
}
/**
* Form scrolling and submission prevent based on validation state
* -If the form is unvalidated, validate all fields
* -If the form is invalid, go to the first invalid element
* -If the form is validating, wait for them to validate and then try submitting again
* -If the form is valid, allow form submission
*/
(0, _jquery2.default)(document).on('submit', function (e) {
var form = e.target;
var $form = (0, _jquery2.default)(form);
var formState = getFormStateName($form);
if (formState === UNVALIDATED) {
delaySubmitUntilStateChange($form, e);
validateUnvalidatedFields($form);
} else if (formState === VALIDATING) {
delaySubmitUntilStateChange($form, e);
} else if (formState === INVALID) {
e.preventDefault();
selectFirstInvalid($form);
} else if (formState === VALID) {
var validSubmitEvent = _jquery2.default.Event('aui-valid-submit');
$form.trigger(validSubmitEvent);
var preventNormalSubmit = validSubmitEvent.isDefaultPrevented();
if (preventNormalSubmit) {
e.preventDefault(); //users can bind to aui-valid-submit for ajax forms
}
}
});
function delaySubmitUntilStateChange($form, event) {
event.preventDefault();
$form.one(EVENT_FIELD_STATE_CHANGED, function () {
$form.trigger('submit');
});
}
function getFormStateName($form) {
var $fieldCollection = $form.find('.' + CLASS_VALIDATION_INITIALISED);
var fieldStates = getFieldCollectionStateNames($fieldCollection);
var wholeFormState = mergeStates(fieldStates);
return wholeFormState;
}
function getFieldCollectionStateNames($fields) {
var states = _jquery2.default.map($fields, function (field) {
return getFieldState((0, _jquery2.default)(field));
});
return states;
}
function mergeStates(stateNames) {
var containsInvalidState = stateNames.indexOf(INVALID) !== -1;
var containsUnvalidatedState = stateNames.indexOf(UNVALIDATED) !== -1;
var containsValidatingState = stateNames.indexOf(VALIDATING) !== -1;
if (containsInvalidState) {
return INVALID;
} else if (containsUnvalidatedState) {
return UNVALIDATED;
} else if (containsValidatingState) {
return VALIDATING;
} else {
return VALID;
}
}
function validateUnvalidatedFields($form) {
var $unvalidatedElements = getFieldsInFormWithState($form, UNVALIDATED);
$unvalidatedElements.each(function (index, el) {
validator.validate((0, _jquery2.default)(el));
});
}
function selectFirstInvalid($form) {
var $firstInvalidField = getFieldsInFormWithState($form, INVALID).first();
$firstInvalidField.focus();
}
function getFieldsInFormWithState($form, state) {
var selector = '[data-' + ATTRIBUTE_FIELD_STATE + '=' + state + ']';
return $form.find(selector);
}
var validator = {
register: _validatorRegister2.default.register,
validate: validateField
};
(0, _skate2.default)(ATTRIBUTE_VALIDATION_FIELD_COMPONENT, {
attached: function attached(field) {
if (field.form) {
field.form.setAttribute('novalidate', 'novalidate');
}
var $field = (0, _jquery2.default)(field);
initValidation($field);
_skate2.default.init(field); //needed to kick off form notification skate initialisation
},
type: _skate2.default.type.ATTRIBUTE
});
(0, _amdify2.default)('aui/form-validation', validator);
(0, _globalize2.default)('formValidation', validator);
exports.default = validator;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/constants.js
(typeof window === 'undefined' ? global : window).__e378fd259e8cc11973d9809608fe9a5e = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var INPUT_SUFFIX = '-input';
exports.default = {
INPUT_SUFFIX: INPUT_SUFFIX
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/label.js
(typeof window === 'undefined' ? global : window).__7904d2f802801befa81e22aff0bd1fb6 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
var _enforcer = __65a8b3ca1b55232381cf1e189f6e2c47;
var _enforcer2 = _interopRequireDefault(_enforcer);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getLabel(element) {
return element.querySelector('label');
}
function updateLabelFor(element, change) {
if (element.hasAttribute('for')) {
getLabel(element).setAttribute('for', '' + change.newValue + _constants.INPUT_SUFFIX);
} else {
getLabel(element).removeAttribute('for');
}
}
function updateLabelForm(element, change) {
if (element.hasAttribute('form')) {
getLabel(element).setAttribute('form', change.newValue);
} else {
getLabel(element).removeAttribute('form');
}
}
var Label = (0, _skate2.default)('aui-label', {
template: (0, _skatejsTemplateHtml2.default)('<label><content></content></label>'),
created: function created(element) {
element._label = getLabel(element); // required for quick access from test
},
attached: function attached(element) {
(0, _enforcer2.default)(element).attributeExists('for');
},
attributes: {
'for': updateLabelFor,
form: updateLabelForm
},
prototype: {
get disabled() {
return this.hasAttribute('disabled');
},
set disabled(value) {
if (value) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
},
events: {
click: function click(element, e) {
if (element.disabled) {
e.preventDefault();
}
}
}
});
exports.default = Label;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/progress-indicator.js
(typeof window === 'undefined' ? global : window).__ef3494fdb79b0ce378f14c1810d48a68 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function updateProgress($progressBar, $progressBarContainer, progressValue) {
(0, _animation.recomputeStyle)($progressBar);
$progressBar.css('width', progressValue * 100 + '%');
$progressBarContainer.attr('data-value', progressValue);
}
var progressBars = {
update: function update(element, value) {
var $progressBarContainer = (0, _jquery2.default)(element).first();
var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value');
var valueAttribute = $progressBarContainer.attr('data-value');
var currentProgress = parseFloat(valueAttribute) || 0;
var isProgressNotChanged = valueAttribute && currentProgress === value;
if (isProgressNotChanged) {
return;
}
var afterTransitionEvent = 'aui-progress-indicator-after-update';
var beforeTransitionEvent = 'aui-progress-indicator-before-update';
var transitionEnd = 'transitionend webkitTransitionEnd';
var isIndeterminate = !valueAttribute;
//if the progress bar is indeterminate switch it.
if (isIndeterminate) {
$progressBar.css('width', 0);
}
if (typeof value === 'number' && value <= 1 && value >= 0) {
$progressBarContainer.trigger(beforeTransitionEvent, [currentProgress, value]);
//detect whether transitions are supported
var documentBody = document.body || document.documentElement;
var style = documentBody.style;
var isTransitionSupported = typeof style.transition === 'string' || typeof style.WebkitTransition === 'string';
//trigger the event after transition end if supported, otherwise just trigger it
if (isTransitionSupported) {
$progressBar.one(transitionEnd, function () {
$progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]);
});
updateProgress($progressBar, $progressBarContainer, value);
} else {
updateProgress($progressBar, $progressBarContainer, value);
$progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]);
}
}
return $progressBarContainer;
},
setIndeterminate: function setIndeterminate(element) {
var $progressBarContainer = (0, _jquery2.default)(element).first();
var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value');
$progressBarContainer.removeAttr('data-value');
(0, _animation.recomputeStyle)($progressBarContainer);
$progressBar.css('width', '100%');
}
};
(0, _globalize2.default)('progressBars', progressBars);
exports.default = progressBars;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/backbone/backbone.js
(typeof window === 'undefined' ? global : window).__754d6596329027c6beeb095ab86facf5 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
var defineDependencies = {
"module": module,
"exports": exports,
"underscore": __b3f4465251fd1fb4828e20c3f041f71e,
"jquery": __77629c8e853846530dfdc3ccd3393ab6,
"underscore": __b3f4465251fd1fb4828e20c3f041f71e,
"jquery": __77629c8e853846530dfdc3ccd3393ab6
};
var define = function defineReplacementWrapper(generatedModuleName) {
return function defineReplacement(name, deps, func) {
var root = (typeof window === 'undefined' ? global : window);
var defineGlobal = root.define;
var rval;
var type;
func = [func, deps, name].filter(function (cur) {
return typeof cur === 'function';
})[0];
deps = [deps, name, []].filter(Array.isArray)[0];
rval = func.apply(null, deps.map(function (value) {
return defineDependencies[value];
}));
type = typeof rval;
// Support existing AMD libs.
if (typeof defineGlobal === 'function') {
// Almond always expects a name so resolve one (#29).
defineGlobal(typeof name === 'string' ? name : generatedModuleName, deps, func);
}
// Some processors like Babel don't check to make sure that the module value
// is not a primitive before calling Object.defineProperty() on it. We ensure
// it is an instance so that it can.
if (type === 'string') {
rval = String(rval);
} else if (type === 'number') {
rval = Number(rval);
} else if (type === 'boolean') {
rval = Boolean(rval);
}
// Reset the exports to the defined module. This is how we convert AMD to
// CommonJS and ensures both can either co-exist, or be used separately. We
// only set it if it is not defined because there is no object representation
// of undefined, thus calling Object.defineProperty() on it would fail.
if (rval !== undefined) {
exports = module.exports = rval;
}
};
}("__754d6596329027c6beeb095ab86facf5");
define.amd = true;
/*! THIS FILE HAS BEEN MODIFIED BY ATLASSIAN. Modified lines are marked below, search "ATLASSIAN" */
// Backbone.js 1.0.0
// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
/**
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* This is a modification of the UMD wrapper used in Backbone 1.1.x
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*/
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = __b3f4465251fd1fb4828e20c3f041f71e, $;
try { $ = __77629c8e853846530dfdc3ccd3393ab6; } catch(e) {}
factory(root, exports, _, $);
// Finally, as a browser global.
} else {
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
/** END ATLASSIAN */
// Initial Setup
// -------------
// Save a reference to the global object (`window` in the browser, `exports`
// on the server).
var root = this;
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
/**
* FOLLOWING LINES REMOVED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*
* // The top-level namespace. All public Backbone classes and modules will
* // be attached to this. Exported for both the browser and the server.
* var Backbone;
* if (typeof exports !== 'undefined') {
* Backbone = exports;
* } else {
* Backbone = root.Backbone = {};
* }
*
*/
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.0.0';
/**
* FOLLOWING LINES REMOVED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*
*
* // Require Underscore, if we're on the server, and it's not already present.
* var _ = root._;
*
* if (!_ && (typeof require !== 'undefined')) _ = __b3f4465251fd1fb4828e20c3f041f71e;
*
/** END ATLASSIAN */
/*
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
*/
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = $;
/** END ATLASSIAN */
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeners = this._listeners;
if (!listeners) return this;
var deleteListener = !name && !callback;
if (typeof name === 'object') callback = this;
if (obj) (listeners = {})[obj._listenerId] = obj;
for (var id in listeners) {
listeners[id].off(name, callback, this);
if (deleteListener) delete this._listeners[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeners = this._listeners || (this._listeners = {});
var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
listeners[id] = obj;
if (typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var defaults;
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
_.extend(this, _.pick(options, modelOptions));
if (options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// A list of options to be attached directly to the model, if provided.
var modelOptions = ['url', 'urlRoot', 'collection'];
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = true;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
options = _.extend({validate: true}, options);
// Do not persist invalid models.
if (!this._validate(attrs, options)) return false;
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.url) this.url = options.url;
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, merge: false, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.defaults(options || {}, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
models = _.isArray(models) ? models.slice() : [models];
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults(options || {}, setOptions);
if (options.parse) models = this.parse(models, options);
if (!_.isArray(models)) models = models ? [models] : [];
var i, l, model, attrs, existing, sort;
var at = options.at;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
if (!(model = this._prepareModel(models[i], options))) continue;
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(model)) {
if (options.remove) modelMap[existing.cid] = true;
if (options.merge) {
existing.set(model.attributes, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
// This is a new model, push it to the `toAdd` list.
} else if (options.add) {
toAdd.push(model);
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
model.on('all', this._onModelEvent, this);
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
}
// Remove nonexistent models if appropriate.
if (options.remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
splice.apply(this.models, [at, 0].concat(toAdd));
} else {
push.apply(this.models, toAdd);
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
if (options.silent) return this;
// Trigger `add` events.
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
// Trigger `sort` if the collection was sorted.
if (sort) this.trigger('sort', this, options);
return this;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
options.previousModels = this.models;
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: this.length}, options));
return model;
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function(begin, end) {
return this.models.slice(begin, end);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj.id != null ? obj.id : obj.cid || obj];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Figure out the smallest index at which a model should be inserted so as
// to maintain order.
sortedIndex: function(model, value, context) {
value || (value = this.comparator);
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _.sortedIndex(this.models, model, iterator, context);
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
// ATLASSIAN CHANGES DUE TO: https://ecosystem.atlassian.net/browse/AUI-1787
// FOLLOWING LINE REMOVED BY ATLASSIAN
// options.success = function(resp) {
// FOLLOWING LINE ADDED BY ATLASSIAN
options.success = function(model, resp, options) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options || (options = {});
options.collection = this;
var model = new this.model(attrs, options);
if (!model._validate(attrs, options)) {
this.trigger('invalid', this, attrs, options);
return false;
}
return model;
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be prefered to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(e.g. model, collection, id, className)* are
// attached directly to the view. See `viewOptions` for an exhaustive
// list.
_configure: function(options) {
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
_.extend(this, _.pick(options, viewOptions));
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && window.ActiveXObject &&
!(window.external && window.external.msActiveXFilteringEnabled)) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
callback && callback.apply(router, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional){
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param) {
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname;
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: options};
fragment = this.getFragment(fragment || '');
if (this.fragment === fragment) return;
this.fragment = fragment;
var url = this.root + fragment;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function (model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
/**
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* This is a modification of the UMD wrapper used in Backbone 1.1.x
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*/
return Backbone;
/** END ATLASSIAN */
}));
return module.exports;
}).call(this);
// src/js/aui/backbone.js
(typeof window === 'undefined' ? global : window).__07cdfb826f754040b351a0110fde6536 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __754d6596329027c6beeb095ab86facf5;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// BEWARE: The following is an unused import with side-effects
if (!window.Backbone) {
window.Backbone = _backbone2.default;
} // eslint-disable-line no-unused-vars
exports.default = window.Backbone;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/progressive-data-set.js
(typeof window === 'undefined' ? global : window).__bc3aa98a1624c420c64de6459784d4cc = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @fileOverview describes a ProgressiveDataSet object.
*
* This object serves as part of a series of components to handle the various aspects of autocomplete controls.
*/
var ProgressiveDataSet = _backbone2.default.Collection.extend({
/**
* A queryable set of data that optimises the speed at which responses can be provided.
*
* ProgressiveDataSet should be given a matcher function so that it may filter results for queries locally.
*
* ProgressiveDataSet can be given a remote query endpoint to fetch data from. Should a remote endpoint
* be provided, ProgressiveDataSet will leverage both client-side matching and query caching to reduce
* the number of times the remote source need be queried.
*
* @example
* var source = new ProgressiveDataSet([], {
* model: Backbone.Model.extend({ idAttribute: "username" }),
* queryEndpoint: "/jira/rest/latest/users",
* queryParamKey: "username",
* matcher: function(model, query) {
* return _.startsWith(model.get('username'), query);
* }
* });
* source.on('respond', doStuffWithMatchingResults);
* source.query('john');
*
* @property {String} value the latest query for which the ProgressiveDataSet is responding to.
* @property {Number} activeQueryCount the number of queries being run remotely.
*/
initialize: function initialize(models, options) {
options || (options = {});
if (options.matcher) {
this.matcher = options.matcher;
}
if (options.model) {
this.model = options.model; // Fixed in backbone 0.9.2
}
this._idAttribute = new this.model().idAttribute;
this._maxResults = options.maxResults || 5;
this._queryData = options.queryData || {};
this._queryParamKey = options.queryParamKey || 'q';
this._queryEndpoint = options.queryEndpoint || '';
this.value = null;
this.queryCache = {};
this.activeQueryCount = 0;
_underscore2.default.bindAll(this, 'query', 'respond');
},
url: function url() {
return this._queryEndpoint;
},
/**
* Sets and runs a query against the ProgressiveDataSet.
*
* Bind to ProgressiveDataSet's 'respond' event to receive the results that match the latest query.
*
* @param {String} query the query to run.
*/
query: function query(_query) {
var _this = this;
var remote;
var results;
this.value = _query;
results = this.getFilteredResults(_query);
this.respond(_query, results);
if (!_query || !this._queryEndpoint || this.hasQueryCache(_query) || !this.shouldGetMoreResults(results)) {
return;
}
remote = this.fetch(_query);
this.activeQueryCount++;
this.trigger('activity', { activity: true });
remote.always(function () {
_this.activeQueryCount--;
_this.trigger('activity', { activity: !!_this.activeQueryCount });
});
remote.done(function (resp, succ, xhr) {
_this.addQueryCache(_query, resp, xhr);
});
remote.done(function () {
_query = _this.value;
results = _this.getFilteredResults(_query);
_this.respond(_query, results);
});
},
/**
* Gets all the data that should be sent in a remote request for data.
* @param {String} query the value of the query to be run.
* @return {Object} the data to to be sent to the remote when querying it.
* @private
*/
getQueryData: function getQueryData(query) {
var params = _underscore2.default.isFunction(this._queryData) ? this._queryData(query) : this._queryData;
var data = _underscore2.default.extend({}, params);
data[this._queryParamKey] = query;
return data;
},
/**
* Get data from a remote source that matches the query, and add it to this ProgressiveDataSet's set.
*
* @param {String} query the value of the query to be run.
* @return {jQuery.Deferred} a deferred object representing the remote request.
*/
fetch: function fetch(query) {
var data = this.getQueryData(query);
// {add: true} for Backbone <= 0.9.2
// {update: true, remove: false} for Backbone >= 0.9.9
var params = { add: true, update: true, remove: false, data: data };
var remote = _backbone2.default.Collection.prototype.fetch.call(this, params);
return remote;
},
/**
* Triggers the 'respond' event on this ProgressiveDataSet for the given query and associated results.
*
* @param {String} query the query that was run
* @param {Array} results a set of results that matched the query.
* @return {Array} the results.
* @private
*/
respond: function respond(query, results) {
this.trigger('respond', {
query: query,
results: results
});
return results;
},
/**
* A hook-point to define a function that tests whether a model matches a query or not.
*
* This will be called by getFilteredResults in order to generate the list of results for a query.
*
* (For you java folks, it's essentially a predicate.)
*
* @param {Backbone.Model} item a model of the data to check for a match in.
* @param {String} query the value to test against the item.
* @returns {Boolean} true if the model matches the query, otherwise false.
* @function
*/
matcher: function matcher(item, query) {}, // eslint-disable-line no-unused-vars
/**
* Filters the set of data contained by the ProgressiveDataSet down to a smaller set of results.
*
* The set will only consist of Models that "match" the query -- i.e., only Models where
* a call to ProgressiveDataSet#matcher returns true.
*
* @param query {String} the value that results should match (according to the matcher function)
* @return {Array} A set of Backbone Models that match the query.
*/
getFilteredResults: function getFilteredResults(query) {
var results = [];
if (!query) {
return results;
}
results = this.filter(function (item) {
return !!this.matcher(item, query);
}, this);
if (this._maxResults) {
results = _underscore2.default.first(results, this._maxResults);
}
return results;
},
/**
* Store a response in the query cache for a given query.
*
* @param {String} query the value to cache a response for.
* @param {Object} response the data of the response from the server.
* @param {XMLHttpRequest} xhr
* @private
*/
addQueryCache: function addQueryCache(query, response, xhr) {
var cache = this.queryCache;
var results = this.parse(response, xhr);
cache[query] = _underscore2.default.pluck(results, this._idAttribute);
},
/**
* Check if there is a query cache entry for a given query.
*
* @param query the value to check in the cache
* @return {Boolean} true if the cache contains a response for the query, false otherwise.
*/
hasQueryCache: function hasQueryCache(query) {
return this.queryCache.hasOwnProperty(query);
},
/**
* Get the query cache entry for a given query.
*
* @param query the value to check in the cache
* @return {Object[]} an array of values representing the IDs of the models the response for this query contained.
*/
findQueryCache: function findQueryCache(query) {
return this.queryCache[query];
},
/**
*
* @param {Array} results the set of results we know about right now.
* @return {Boolean} true if the ProgressiveDataSet should look for more results.
* @private
*/
shouldGetMoreResults: function shouldGetMoreResults(results) {
return results.length < this._maxResults;
},
/**
*
* @note Changing this value will trigger ProgressiveDataSet#event:respond if there is a query.
* @param {Number} number how many results should the ProgressiveDataSet aim to retrieve for a query.
*/
setMaxResults: function setMaxResults(number) {
this._maxResults = number;
this.value && this.respond(this.value, this.getFilteredResults(this.value));
}
});
(0, _globalize2.default)('ProgressiveDataSet', ProgressiveDataSet);
exports.default = ProgressiveDataSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/query-input.js
(typeof window === 'undefined' ? global : window).__b12fa1032568f0d561e20a44ba70067a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var QueryInput = _backbone2.default.View.extend({
initialize: function initialize() {
_underscore2.default.bindAll(this, 'changed', 'val');
this._lastValue = this.val();
this.$el.bind('keyup focus', this.changed);
},
val: function val() {
return this.$el.val.apply(this.$el, arguments);
},
changed: function changed() {
if (this._lastValue !== this.val()) {
this.trigger('change', this.val());
this._lastValue = this.val();
}
}
});
(0, _globalize2.default)('QueryInput', QueryInput);
exports.default = QueryInput;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/class-names.js
(typeof window === 'undefined' ? global : window).__118527544b71a67b452649071c2ae422 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
NO_VALUE: 'aui-restfultable-editable-no-value',
NO_ENTRIES: 'aui-restfultable-no-entires',
RESTFUL_TABLE: 'aui-restfultable',
ROW: 'aui-restfultable-row',
READ_ONLY: 'aui-restfultable-readonly',
ACTIVE: 'aui-restfultable-active',
ALLOW_HOVER: 'aui-restfultable-allowhover',
FOCUSED: 'aui-restfultable-focused',
MOVEABLE: 'aui-restfultable-movable',
DISABLED: 'aui-restfultable-disabled',
SUBMIT: 'aui-restfultable-submit',
CANCEL: 'aui-restfultable-cancel',
EDIT_ROW: 'aui-restfultable-editrow',
CREATE: 'aui-restfultable-create',
DRAG_HANDLE: 'aui-restfultable-draghandle',
ORDER: 'aui-restfultable-order',
EDITABLE: 'aui-restfultable-editable',
ERROR: 'error',
DELETE: 'aui-restfultable-delete',
LOADING: 'loading'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-create-view.js
(typeof window === 'undefined' ? global : window).__8d19d0bdd704aa4d4cdc512b60f140de = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-edit-view.js
(typeof window === 'undefined' ? global : window).__12a9dc86ab66cc22f78cf62feba9dd64 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-read-view.js
(typeof window === 'undefined' ? global : window).__dcca2723b4c5fed4e65377ddb5d32682 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/data-keys.js
(typeof window === 'undefined' ? global : window).__b1c52d9d29b34f181b3d58c504dec0ce = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
ENABLED_SUBMIT: 'enabledSubmit',
ROW_VIEW: 'RestfulTable_Row_View'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/serializetoobject.js
(typeof window === 'undefined' ? global : window).__aa7c1770abfd4c15bea861f799ad2035 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**
* Serializes form fields within the given element to a JSON object
*
* {
* fieldName: "fieldValue"
* }
*
* @returns {Object}
*/
jQuery.fn.serializeObject = function () {
var data = {};
this.find(":input:not(:button):not(:submit):not(:radio):not('select[multiple]')").each(function () {
if (this.name === "") {
return;
}
if (this.value === null) {
this.value = "";
}
data[this.name] = this.value.match(/^(tru|fals)e$/i) ?
this.value.toLowerCase() == "true" : this.value;
});
this.find("input:radio:checked").each(function(){
data[this.name] = this.value;
});
this.find("select[multiple]").each(function(){
var $select = jQuery(this),
val = $select.val();
if ($select.data("aui-ss")) {
if (val) {
data[this.name] = val[0];
} else {
data[this.name] = "";
}
} else {
if (val !== null) {
data[this.name] = val;
} else {
data[this.name] = [];
}
}
});
return data;
};
return module.exports;
}).call(this);
// src/js/aui/restful-table/events.js
(typeof window === 'undefined' ? global : window).__229915fcac0b1d518ba82b8dccf17af7 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
// AJS
REORDER_SUCCESS: 'RestfulTable.reorderSuccess',
ROW_ADDED: 'RestfulTable.rowAdded',
ROW_REMOVED: 'RestfulTable.rowRemoved',
EDIT_ROW: 'RestfulTable.switchedToEditMode',
SERVER_ERROR: 'RestfulTable.serverError',
// Backbone
CREATED: 'created',
UPDATED: 'updated',
FOCUS: 'focus',
BLUR: 'blur',
SUBMIT: 'submit',
SAVE: 'save',
MODAL: 'modal',
MODELESS: 'modeless',
CANCEL: 'cancel',
CONTENT_REFRESHED: 'contentRefreshed',
RENDER: 'render',
FINISHED_EDITING: 'finishedEditing',
VALIDATION_ERROR: 'validationError',
SUBMIT_STARTED: 'submitStarted',
SUBMIT_FINISHED: 'submitFinished',
INITIALIZED: 'initialized',
ROW_INITIALIZED: 'rowInitialized',
ROW_EDIT: 'editRow'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/throbber.js
(typeof window === 'undefined' ? global : window).__491c5885a1dc4d2077d5e87e221aa590 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
return '<span class="aui-restfultable-throbber"></span>';
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/edit-row.js
(typeof window === 'undefined' ? global : window).__ea66711b82bb656ccc7223576cc606c7 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__aa7c1770abfd4c15bea861f799ad2035;
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
/**
* An abstract class that gives the required behaviour for the creating and editing entries. Extend this class and pass
* it as the {views.row} property of the options passed to RestfulTable in construction.
*/
exports.default = _backbone2.default.View.extend({
tagName: 'tr',
// delegate events
events: {
'focusin': '_focus',
'click': '_focus',
'keyup': '_handleKeyUpEvent'
},
/**
* @constructor
* @param {Object} options
*/
initialize: function initialize(options) {
this.$el = (0, _jquery2.default)(this.el);
// faster lookup
this._event = _events2.default;
this.classNames = _classNames2.default;
this.dataKeys = _dataKeys2.default;
this.columns = options.columns;
this.isCreateRow = options.isCreateRow;
this.allowReorder = options.allowReorder;
// Allow cancelling an edit with support for setting a new element.
this.events['click .' + this.classNames.CANCEL] = '_cancel';
this.delegateEvents();
if (options.isUpdateMode) {
this.isUpdateMode = true;
} else {
this._modelClass = options.model;
this.model = new this._modelClass();
}
this.fieldFocusSelector = options.fieldFocusSelector;
this.bind(this._event.CANCEL, function () {
this.disabled = true;
}).bind(this._event.SAVE, function (focusUpdated) {
if (!this.disabled) {
this.submit(focusUpdated);
}
}).bind(this._event.FOCUS, function (name) {
this.focus(name);
}).bind(this._event.BLUR, function () {
this.$el.removeClass(this.classNames.FOCUSED);
this.disable();
}).bind(this._event.SUBMIT_STARTED, function () {
this._submitStarted();
}).bind(this._event.SUBMIT_FINISHED, function () {
this._submitFinished();
});
},
/**
* Renders default cell contents
*
* @param data
*/
defaultColumnRenderer: function defaultColumnRenderer(data) {
if (data.allowEdit !== false) {
return (0, _jquery2.default)("<input type='text' />").addClass('text').attr({
name: data.name,
value: data.value
});
} else if (data.value) {
return document.createTextNode(data.value);
}
},
/**
* Renders drag handle
* @return jQuery
*/
renderDragHandle: function renderDragHandle() {
return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>';
},
/**
* Executes cancel event if ESC is pressed
*
* @param {Event} e
*/
_handleKeyUpEvent: function _handleKeyUpEvent(e) {
if (e.keyCode === 27) {
this.trigger(this._event.CANCEL);
}
},
/**
* Fires cancel event
*
* @param {Event} e
*
* @return EditRow
*/
_cancel: function _cancel(e) {
this.trigger(this._event.CANCEL);
e.preventDefault();
return this;
},
/**
* Disables events/fields and adds safe guard against double submitting
*
* @return EditRow
*/
_submitStarted: function _submitStarted() {
this.submitting = true;
this.showLoading().disable().delegateEvents({});
return this;
},
/**
* Enables events & fields
*
* @return EditRow
*/
_submitFinished: function _submitFinished() {
this.submitting = false;
this.hideLoading().enable().delegateEvents(this.events);
return this;
},
/**
* Handles dom focus event, by only focusing row if it isn't already
*
* @param {Event} e
*
* @return EditRow
*/
_focus: function _focus(e) {
if (!this.hasFocus()) {
this.trigger(this._event.FOCUS, e.target.name);
}
return this;
},
/**
* Returns true if row has focused class
*
* @return Boolean
*/
hasFocus: function hasFocus() {
return this.$el.hasClass(this.classNames.FOCUSED);
},
/**
* Focus specified field (by name or id - first argument), first field with an error or first field (DOM order)
*
* @param name
*
* @return EditRow
*/
focus: function focus(name) {
var $focus;
var $error;
this.enable();
if (name) {
$focus = this.$el.find(this.fieldFocusSelector(name));
} else {
$error = this.$el.find(this.classNames.ERROR + ':first');
if ($error.length === 0) {
$focus = this.$el.find(':input:text:first');
} else {
$focus = $error.parent().find(':input');
}
}
this.$el.addClass(this.classNames.FOCUSED);
$focus.focus().trigger('select');
return this;
},
/**
* Disables all fields
*
* @return EditRow
*/
disable: function disable() {
var $replacementSubmit;
var $submit;
// firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but
// one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack.
if (isFirefox) {
$submit = this.$el.find(':submit');
if ($submit.length) {
$replacementSubmit = (0, _jquery2.default)("<input type='submit' class='" + this.classNames.SUBMIT + "' />").addClass($submit.attr('class')).val($submit.val()).data(this.dataKeys.ENABLED_SUBMIT, $submit);
$submit.replaceWith($replacementSubmit);
}
}
this.$el.addClass(this.classNames.DISABLED).find(':submit').attr('disabled', 'disabled');
return this;
},
/**
* Enables all fields
*
* @return EditRow
*/
enable: function enable() {
var $placeholderSubmit;
var $submit;
// firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but
// one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack.
if (isFirefox) {
$placeholderSubmit = this.$el.find(this.classNames.SUBMIT);
$submit = $placeholderSubmit.data(this.dataKeys.ENABLED_SUBMIT);
if ($submit && $placeholderSubmit.length) {
$placeholderSubmit.replaceWith($submit);
}
}
this.$el.removeClass(this.classNames.DISABLED).find(':submit').removeAttr('disabled');
return this;
},
/**
* Shows loading indicator
*
* @return EditRow
*/
showLoading: function showLoading() {
this.$el.addClass(this.classNames.LOADING);
return this;
},
/**
* Hides loading indicator
*
* @return EditRow
*/
hideLoading: function hideLoading() {
this.$el.removeClass(this.classNames.LOADING);
return this;
},
/**
* If any of the fields have changed
*
* @return {Boolean}
*/
hasUpdates: function hasUpdates() {
return !!this.mapSubmitParams(this.serializeObject());
},
/**
* Serializes the view into model representation.
* Default implementation uses simple jQuery plugin to serialize form fields into object
*
* @return Object
*/
serializeObject: function serializeObject() {
var $el = this.$el;
return $el.serializeObject ? $el.serializeObject() : $el.serialize();
},
mapSubmitParams: function mapSubmitParams(params) {
return this.model.changedAttributes(params);
},
/**
* Handle submission of new entries and editing of old.
*
* @param {Boolean} focusUpdated - flag of whether to focus read-only view after succssful submission
*
* @return EditRow
*/
submit: function submit(focusUpdated) {
var instance = this;
var values;
// IE doesnt like it when the focused element is removed
if (document.activeElement !== window) {
(0, _jquery2.default)(document.activeElement).blur();
}
if (this.isUpdateMode) {
values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON
if (!values) {
return instance.trigger(instance._event.CANCEL);
}
} else {
this.model.clear();
values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON
}
this.trigger(this._event.SUBMIT_STARTED);
/* Attempt to add to server model. If fail delegate to createView to render errors etc. Otherwise,
add a new model to this._models and render a row to represent it. */
this.model.save(values, {
success: function success() {
if (instance.isUpdateMode) {
instance.trigger(instance._event.UPDATED, instance.model, focusUpdated);
} else {
instance.trigger(instance._event.CREATED, instance.model.toJSON());
instance.model = new instance._modelClass(); // reset
instance.render({ errors: {}, values: {} }); // pulls in instance's model for create row
instance.trigger(instance._event.FOCUS);
}
instance.trigger(instance._event.SUBMIT_FINISHED);
},
error: function error(model, data, xhr) {
if (xhr.status === 400) {
instance.renderErrors(data.errors);
instance.trigger(instance._event.VALIDATION_ERROR, data.errors);
}
instance.trigger(instance._event.SUBMIT_FINISHED);
},
silent: true
});
return this;
},
/**
* Render an error message
*
* @param msg
*
* @return {jQuery}
*/
renderError: function renderError(name, msg) {
return (0, _jquery2.default)('<div />').attr('data-field', name).addClass(this.classNames.ERROR).text(msg);
},
/**
* Render and append error messages. The property name will be matched to the input name to determine which cell to
* append the error message to. If this does not meet your needs please extend this method.
*
* @param errors
*/
renderErrors: function renderErrors(errors) {
var instance = this;
this.$('.' + this.classNames.ERROR).remove(); // avoid duplicates
if (errors) {
_jquery2.default.each(errors, function (name, msg) {
instance.$el.find("[name='" + name + "']").closest('td').append(instance.renderError(name, msg));
});
}
return this;
},
/**
* Handles rendering of row
*
* @param {Object} renderData
* ... {Object} vales - Values of fields
*/
render: function render(renderData) {
var instance = this;
this.$el.empty();
if (this.allowReorder) {
(0, _jquery2.default)('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el);
}
_jquery2.default.each(this.columns, function (i, column) {
var contents;
var $cell;
var value = renderData.values[column.id];
var args = [{ name: column.id, value: value, allowEdit: column.allowEdit }, renderData.values, instance.model];
if (value) {
instance.$el.attr('data-' + column.id, value); // helper for webdriver testing
}
if (instance.isCreateRow && column.createView) {
// TODO AUI-1058 - The row's model should be guaranteed to be in the correct state by this point.
contents = new column.createView({
model: instance.model
}).render(args[0]);
} else if (column.editView) {
contents = new column.editView({
model: instance.model
}).render(args[0]);
} else {
contents = instance.defaultColumnRenderer.apply(instance, args);
}
$cell = (0, _jquery2.default)('<td />');
if ((typeof contents === 'undefined' ? 'undefined' : _typeof(contents)) === 'object' && contents.done) {
contents.done(function (contents) {
$cell.append(contents);
});
} else {
$cell.append(contents);
}
if (column.styleClass) {
$cell.addClass(column.styleClass);
}
$cell.appendTo(instance.$el);
});
this.$el.append(this.renderOperations(renderData.update, renderData.values)) // add submit/cancel buttons
.addClass(this.classNames.ROW + ' ' + this.classNames.EDIT_ROW);
this.trigger(this._event.RENDER, this.$el, renderData.values);
this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]);
return this;
},
/**
* Gets markup for add/update and cancel buttons
*
* @param {Boolean} update
*/
renderOperations: function renderOperations(update) {
var $operations = (0, _jquery2.default)('<td class="aui-restfultable-operations" />');
if (update) {
$operations.append((0, _jquery2.default)('<input class="aui-button" type="submit" />').attr({
accesskey: this.submitAccessKey,
value: AJS.I18n.getText('aui.words.update')
})).append((0, _jquery2.default)('<a class="aui-button aui-button-link" href="#" />').addClass(this.classNames.CANCEL).text(AJS.I18n.getText('aui.words.cancel')).attr({
accesskey: this.cancelAccessKey
}));
} else {
$operations.append((0, _jquery2.default)('<input class="aui-button" type="submit" />').attr({
accesskey: this.submitAccessKey,
value: AJS.I18n.getText('aui.words.add')
}));
}
return $operations.add((0, _jquery2.default)('<td class="aui-restfultable-status" />').append((0, _throbber2.default)()));
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/entry-model.js
(typeof window === 'undefined' ? global : window).__085efe8598a83df67ac0ec7155e156ad = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _events = __a8a2a7bb852460b812b29dc7b998d456;
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _events2 = __229915fcac0b1d518ba82b8dccf17af7;
var _events3 = _interopRequireDefault(_events2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A class provided to fill some gaps with the out of the box Backbone.Model class. Most notiably the inability
* to send ONLY modified attributes back to the server.
*/
var EntryModel = _backbone2.default.Model.extend({
sync: function sync(method, model, options) {
var instance = this;
var oldError = options.error;
options.error = function (xhr) {
instance._serverErrorHandler(xhr, this);
if (oldError) {
oldError.apply(this, arguments);
}
};
return _backbone2.default.sync.apply(_backbone2.default, arguments);
},
/**
* Overrides default save handler to only save (send to server) attributes that have changed.
* Also provides some default error handling.
*
* @override
* @param attributes
* @param options
*/
save: function save(attributes, options) {
options = options || {};
var instance = this;
var Model;
var syncModel;
var error = options.error; // we override, so store original
var success = options.success;
// override error handler to provide some defaults
options.error = function (model, xhr) {
var data = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
// call original error handler
if (error) {
error.call(instance, instance, data, xhr);
}
};
// if it is a new model, we don't have to worry about updating only changed attributes because they are all new
if (this.isNew()) {
// call super
_backbone2.default.Model.prototype.save.call(this, attributes, options);
// only go to server if something has changed
} else if (attributes) {
// create temporary model
Model = EntryModel.extend({
url: this.url()
});
syncModel = new Model({
id: this.id
});
syncModel.save = _backbone2.default.Model.prototype.save;
options.success = function (model, xhr) {
// update original model with saved attributes
instance.clear().set(model.toJSON());
// call original success handler
if (success) {
success.call(instance, instance, xhr);
}
};
// update temporary model with the changed attributes
syncModel.save(attributes, options);
}
},
/**
* Destroys the model on the server. We need to override the default method as it does not support sending of
* query paramaters.
*
* @override
* @param options
* ... {function} success - Server success callback
* ... {function} error - Server error callback
* ... {object} data
*
* @return EntryModel
*/
destroy: function destroy(options) {
options = options || {};
var instance = this;
var url = this.url();
var data;
if (options.data) {
data = _jquery2.default.param(options.data);
}
if (data !== '') {
// we need to add to the url as the data param does not work for jQuery DELETE requests
url = url + '?' + data;
}
_jquery2.default.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
contentType: 'application/json',
success: function success(data) {
if (instance.collection) {
instance.collection.remove(instance);
}
if (options.success) {
options.success.call(instance, data);
}
},
error: function error(xhr) {
instance._serverErrorHandler(xhr, this);
if (options.error) {
options.error.call(instance, xhr);
}
}
});
return this;
},
/**
* A more complex lookup for changed attributes then default backbone one.
*
* @param attributes
*/
changedAttributes: function changedAttributes(attributes) {
var changed = {};
var current = this.toJSON();
_jquery2.default.each(attributes, function (name, value) {
if (!current[name]) {
if (typeof value === 'string') {
if (_jquery2.default.trim(value) !== '') {
changed[name] = value;
}
} else if (_jquery2.default.isArray(value)) {
if (value.length !== 0) {
changed[name] = value;
}
} else {
changed[name] = value;
}
} else if (current[name] && current[name] !== value) {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (!_underscore2.default.isEqual(value, current[name])) {
changed[name] = value;
}
} else {
changed[name] = value;
}
}
});
if (!_underscore2.default.isEmpty(changed)) {
this.addExpand(changed);
return changed;
}
},
/**
* Useful point to override if you always want to add an expand to your rest calls.
*
* @param changed attributes that have already changed
*/
addExpand: function addExpand(changed) {},
/**
* Throws a server error event unless user input validation error (status 400)
*
* @param xhr
*/
_serverErrorHandler: function _serverErrorHandler(xhr, ajaxOptions) {
var data;
if (xhr.status !== 400) {
data = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
(0, _events.triggerEvtForInst)(_events3.default.SERVER_ERROR, this, [data, xhr, ajaxOptions]);
}
},
/**
* Fetches values, with some generic error handling
*
* @override
* @param options
*/
fetch: function fetch(options) {
options = options || {};
// clear the model, so we do not merge the old with the new
this.clear();
// call super
_backbone2.default.Model.prototype.fetch.call(this, options);
}
});
exports.default = EntryModel;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/row.js
(typeof window === 'undefined' ? global : window).__8da0d4434ee98ffecf6e34940b133dfd = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __8d4634fbee21b3e51cb6c1e2a1adb5ff;
var dialog = _interopRequireWildcard(_dialog);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* An abstract class that gives the required behaviour for RestfulTable rows.
* Extend this class and pass it as the {views.row} property of the options passed to RestfulTable in construction.
*/
exports.default = _backbone2.default.View.extend({
tagName: 'tr',
events: {
'click .aui-restfultable-editable': 'edit'
},
initialize: function initialize(options) {
var instance = this;
options = options || {};
this._event = _events2.default;
this.classNames = _classNames2.default;
this.dataKeys = _dataKeys2.default;
this.columns = options.columns;
this.allowEdit = options.allowEdit;
this.allowDelete = options.allowDelete;
if (!this.events['click .aui-restfultable-editable']) {
throw new Error('It appears you have overridden the events property. To add events you will need to use' + 'a work around. https://github.com/documentcloud/backbone/issues/244');
}
this.index = options.index || 0;
this.deleteConfirmation = options.deleteConfirmation;
this.allowReorder = options.allowReorder;
this.$el = (0, _jquery2.default)(this.el);
this.bind(this._event.CANCEL, function () {
this.disabled = true;
}).bind(this._event.FOCUS, function (field) {
this.focus(field);
}).bind(this._event.BLUR, function () {
this.unfocus();
}).bind(this._event.MODAL, function () {
this.$el.addClass(this.classNames.ACTIVE);
}).bind(this._event.MODELESS, function () {
this.$el.removeClass(this.classNames.ACTIVE);
});
},
/**
* Renders drag handle
*
* @return jQuery
*/
renderDragHandle: function renderDragHandle() {
return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>';
},
/**
* Renders default cell contents
*
* @param data
*
* @return {undefiend, String}
*/
defaultColumnRenderer: function defaultColumnRenderer(data) {
if (data.value) {
return document.createTextNode(data.value.toString());
}
},
/**
* Save changed attributes back to server and re-render
*
* @param attr
*
* @return {Row}
*/
sync: function sync(attr) {
var instance = this;
this.model.addExpand(attr);
this.showLoading();
this.model.save(attr, {
success: function success() {
instance.hideLoading().render();
instance.trigger(instance._event.UPDATED);
},
error: function error() {
instance.hideLoading();
}
});
return this;
},
/**
* Get model from server and re-render
*
* @return {Row}
*/
refresh: function refresh(_success, _error) {
var instance = this;
this.showLoading();
this.model.fetch({
success: function success() {
instance.hideLoading().render();
if (_success) {
_success.apply(this, arguments);
}
},
error: function error() {
instance.hideLoading();
if (_error) {
_error.apply(this, arguments);
}
}
});
return this;
},
/**
* Returns true if row has focused class
*
* @return Boolean
*/
hasFocus: function hasFocus() {
return this.$el.hasClass(this.classNames.FOCUSED);
},
/**
* Adds focus class (Item has been recently updated)
*
* @return Row
*/
focus: function focus() {
(0, _jquery2.default)(this.el).addClass(this.classNames.FOCUSED);
return this;
},
/**
* Removes focus class
*
* @return Row
*/
unfocus: function unfocus() {
(0, _jquery2.default)(this.el).removeClass(this.classNames.FOCUSED);
return this;
},
/**
* Adds loading class (to show server activity)
*
* @return Row
*/
showLoading: function showLoading() {
this.$el.addClass(this.classNames.LOADING);
return this;
},
/**
* Hides loading class (to show server activity)
*
* @return Row
*/
hideLoading: function hideLoading() {
this.$el.removeClass(this.classNames.LOADING);
return this;
},
/**
* Switches row into edit mode
*
* @param e
*/
edit: function edit(e) {
var field;
if ((0, _jquery2.default)(e.target).is('.' + this.classNames.EDITABLE)) {
field = (0, _jquery2.default)(e.target).attr('data-field-name');
} else {
field = (0, _jquery2.default)(e.target).closest('.' + this.classNames.EDITABLE).attr('data-field-name');
}
this.trigger(this._event.ROW_EDIT, field);
return this;
},
/**
* Can be overriden to add custom options.
*
* @returns {jQuery}
*/
renderOperations: function renderOperations() {
var instance = this;
if (this.allowDelete !== false) {
return (0, _jquery2.default)("<a href='#' class='aui-button' />").addClass(this.classNames.DELETE).text(AJS.I18n.getText('aui.words.delete')).click(function (e) {
e.preventDefault();
instance.destroy();
});
}
},
/**
* Removes entry from table.
*
* @returns {undefined}
*/
destroy: function destroy() {
if (this.deleteConfirmation) {
var popup = dialog.popup(400, 200, 'delete-entity-' + this.model.get('id'));
popup.element.html(this.deleteConfirmation(this.model.toJSON()));
popup.show();
popup.element.find('.cancel').click(function () {
popup.hide();
});
popup.element.find('form').submit(function (e) {
popup.hide();
this.model.destroy();
e.preventDefault();
}.bind(this));
} else {
this.model.destroy();
}
},
/**
* Renders a generic edit row. You probably want to override this in a sub class.
*
* @return Row
*/
render: function render() {
var instance = this;
var renderData = this.model.toJSON();
var $opsCell = (0, _jquery2.default)("<td class='aui-restfultable-operations' />").append(this.renderOperations({}, renderData));
var $throbberCell = (0, _jquery2.default)("<td class='aui-restfultable-status' />").append((0, _throbber2.default)());
// restore state
this.$el.removeClass(this.classNames.DISABLED + ' ' + this.classNames.FOCUSED + ' ' + this.classNames.LOADING + ' ' + this.classNames.EDIT_ROW).addClass(this.classNames.READ_ONLY).empty();
if (this.allowReorder) {
(0, _jquery2.default)('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el);
}
this.$el.attr('data-id', this.model.id); // helper for webdriver testing
_jquery2.default.each(this.columns, function (i, column) {
var contents;
var $cell = (0, _jquery2.default)('<td />');
var value = renderData[column.id];
var fieldName = column.fieldName || column.id;
var args = [{ name: fieldName, value: value, allowEdit: column.allowEdit }, renderData, instance.model];
if (value) {
instance.$el.attr('data-' + column.id, value); // helper for webdriver testing
}
if (column.readView) {
contents = new column.readView({
model: instance.model
}).render(args[0]);
} else {
contents = instance.defaultColumnRenderer.apply(instance, args);
}
if (instance.allowEdit !== false && column.allowEdit !== false) {
var $editableRegion = (0, _jquery2.default)('<span />').addClass(instance.classNames.EDITABLE).append('<span class="aui-icon aui-icon-small aui-iconfont-edit"></span>').append(contents).attr('data-field-name', fieldName);
$cell = (0, _jquery2.default)('<td />').append($editableRegion).appendTo(instance.$el);
if (!contents || _jquery2.default.trim(contents) == '') {
$cell.addClass(instance.classNames.NO_VALUE);
$editableRegion.html((0, _jquery2.default)('<em />').text(this.emptyText || AJS.I18n.getText('aui.enter.value')));
}
} else {
$cell.append(contents);
}
if (column.styleClass) {
$cell.addClass(column.styleClass);
}
$cell.appendTo(instance.$el);
});
this.$el.append($opsCell).append($throbberCell).addClass(this.classNames.ROW + ' ' + this.classNames.READ_ONLY);
this.trigger(this._event.RENDER, this.$el, renderData);
this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]);
return this;
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table.js
(typeof window === 'undefined' ? global : window).__d9778e9495b7a4889d0567cf2b8e1182 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _customCreateView = __8d19d0bdd704aa4d4cdc512b60f140de;
var _customCreateView2 = _interopRequireDefault(_customCreateView);
var _customEditView = __12a9dc86ab66cc22f78cf62feba9dd64;
var _customEditView2 = _interopRequireDefault(_customEditView);
var _customReadView = __dcca2723b4c5fed4e65377ddb5d32682;
var _customReadView2 = _interopRequireDefault(_customReadView);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _editRow = __ea66711b82bb656ccc7223576cc606c7;
var _editRow2 = _interopRequireDefault(_editRow);
var _entryModel = __085efe8598a83df67ac0ec7155e156ad;
var _entryModel2 = _interopRequireDefault(_entryModel);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _row = __8da0d4434ee98ffecf6e34940b133dfd;
var _row2 = _interopRequireDefault(_row);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Triggers a custom event on the document object
*
* @param {String} name - name of event
* @param {Array} args - args for event handler
*/
function triggerEvt(name, args) {
(0, _jquery2.default)(document).trigger(name, args);
}
/**
* Some generic error handling that fires event in multiple contexts
* - on document
* - on Instance
* - on document with prefixed id.
*
* @param evt
* @param inst
* @param args
*/
function triggerEvtForInst(evt, inst, args) {
(0, _jquery2.default)(inst).trigger(evt, args);
triggerEvt(evt, args);
if (inst.id) {
triggerEvt(inst.id + '_' + evt, args);
}
}
/**
* A table whose entries/rows can be retrieved, added and updated via REST (CRUD).
* It uses backbone.js to sync the table's state back to the server, avoiding page refreshes.
*
* @class RestfulTable
*/
var RestfulTable = _backbone2.default.View.extend({
/**
* @param {!Object} options
* ... {!Object} resources
* ... ... {(string|function(function(Array.<Object>)))} all - URL of REST resource OR function that retrieves all entities.
* ... ... {string} self - URL of REST resource to sync a single entities state (CRUD).
* ... {!(selector|Element|jQuery)} el - Table element or selector of the table element to populate.
* ... {!Array.<Object>} columns - Which properties of the entities to render. The id of a column maps to the property of an entity.
* ... {Object} views
* ... ... {RestfulTable.EditRow} editRow - Backbone view that renders the edit & create row. Your view MUST extend RestfulTable.EditRow.
* ... ... {RestfulTable.Row} row - Backbone view that renders the readonly row. Your view MUST extend RestfulTable.Row.
* ... {boolean} allowEdit - Is the table editable. If true, clicking row will switch it to edit state. Default true.
* ... {boolean} allowDelete - Can entries be removed from the table, default true.
* ... {boolean} allowCreate - Can new entries be added to the table, default true.
* ... {boolean} allowReorder - Can we drag rows to reorder them, default false.
* ... {boolean} autoFocus - Automatically set focus to first field on init, default false.
* ... {boolean} reverseOrder - Reverse the order of rows, default false.
* ... {boolean} silent - Do not trigger a "refresh" event on sort, default false.
* ... {String} id - The id for the table. This id will be used to fire events specific to this instance.
* ... {string} createPosition - If set to "bottom", place the create form at the bottom of the table instead of the top.
* ... {string} addPosition - If set to "bottom", add new rows at the bottom of the table instead of the top. If undefined, createPosition will be used to define where to add the new row.
* ... {string} noEntriesMsg - Text to display under the table header if it is empty, default empty.
* ... {string} loadingMsg - Text/HTML to display while loading, default "Loading".
* ... {string} submitAccessKey - Access key for submitting.
* ... {string} cancelAccessKey - Access key for canceling.
* ... {function(Object): (string|function(number, string): string)} deleteConfirmation - HTML to display in popup to confirm deletion.
* ... {function(string): (selector|jQuery|Element)} fieldFocusSelector - Element to focus on given a name.
* ... {EntryModel} model - Backbone model representing a row, default EntryModel.
* ... {Backbone.Collection} Collection - Backbone collection representing the entire table, default Backbone.Collection.
*/
initialize: function initialize(options) {
var instance = this;
// combine default and user options
instance.options = _jquery2.default.extend(true, instance._getDefaultOptions(options), options);
// Prefix events for this instance with this id.
instance.id = this.options.id;
// faster lookup
instance._event = _events2.default;
instance.classNames = _classNames2.default;
instance.dataKeys = _dataKeys2.default;
// shortcuts to popular elements
this.$table = (0, _jquery2.default)(options.el).addClass(this.classNames.RESTFUL_TABLE).addClass(this.classNames.ALLOW_HOVER).addClass('aui').addClass(instance.classNames.LOADING);
this.$table.wrapAll("<form class='aui' action='#' />");
this.$thead = (0, _jquery2.default)('<thead/>');
this.$theadRow = (0, _jquery2.default)('<tr />').appendTo(this.$thead);
this.$tbody = (0, _jquery2.default)('<tbody/>');
if (!this.$table.length) {
throw new Error('RestfulTable: Init failed! The table you have specified [' + this.$table.selector + '] cannot be found.');
}
if (!this.options.columns) {
throw new Error("RestfulTable: Init failed! You haven't provided any columns to render.");
}
// Let user know the table is loading
this.showGlobalLoading();
this.options.columns.forEach(function (column) {
var header = _jquery2.default.isFunction(column.header) ? column.header() : column.header;
if (typeof header === 'undefined') {
logger.warn('You have not specified [header] for column [' + column.id + ']. Using id for now...');
header = column.id;
}
instance.$theadRow.append('<th>' + header + '</th>');
});
// columns for submit buttons and loading indicator used when editing
instance.$theadRow.append('<th></th><th></th>');
// create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection)
this._models = this._createCollection();
// shortcut to the class we use to create rows
this._rowClass = this.options.views.row;
this.editRows = []; // keep track of rows that are being edited concurrently
this.$table.closest('form').submit(function (e) {
if (instance.focusedRow) {
// Delegates saving of row. See EditRow.submit
instance.focusedRow.trigger(instance._event.SAVE);
}
e.preventDefault();
});
if (this.options.allowReorder) {
// Add allowance for another cell to the <thead>
this.$theadRow.prepend('<th />');
// Allow drag and drop reordering of rows
this.$tbody.sortable({
handle: '.' + this.classNames.DRAG_HANDLE,
helper: function helper(e, elt) {
var helper = (0, _jquery2.default)('<div/>').attr('class', elt.attr('class')).addClass(instance.classNames.MOVEABLE);
elt.children().each(function (i) {
var $td = (0, _jquery2.default)(this);
// .offsetWidth/.outerWidth() is broken in webkit for tables, so we do .clientWidth + borders
// Need to coerce the border-left-width to an in because IE - http://bugs.jquery.com/ticket/10855
var borderLeft = parseInt(0 + $td.css('border-left-width'), 10);
var borderRight = parseInt(0 + $td.css('border-right-width'), 10);
var width = $td[0].clientWidth + borderLeft + borderRight;
helper.append((0, _jquery2.default)('<div/>').html($td.html()).attr('class', $td.attr('class')).width(width));
});
helper = (0, _jquery2.default)("<div class='aui-restfultable-readonly'/>").append(helper); // Basically just to get the styles.
helper.css({ left: elt.offset().left }); // To align with the other table rows, since we've locked scrolling on x.
helper.appendTo(document.body);
return helper;
},
start: function start(event, ui) {
var cachedHeight = ui.helper[0].clientHeight;
var $this = ui.placeholder.find('td');
// Make sure that when we start dragging widths do not change
ui.item.addClass(instance.classNames.MOVEABLE).children().each(function (i) {
(0, _jquery2.default)(this).width($this.eq(i).width());
});
// Create a <td> to add to the placeholder <tr> to inherit CSS styles.
var td = '<td colspan="' + instance.getColumnCount() + '"> </td>';
ui.placeholder.html(td).css({
height: cachedHeight,
visibility: 'visible'
});
// Stop hover effects etc from occuring as we move the mouse (while dragging) over other rows
instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODAL);
},
stop: function stop(event, ui) {
if ((0, _jquery2.default)(ui.item[0]).is(':visible')) {
ui.item.removeClass(instance.classNames.MOVEABLE).children().attr('style', '');
ui.placeholder.removeClass(instance.classNames.ROW);
// Return table to a normal state
instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODELESS);
}
},
update: function update(event, ui) {
var context = {
row: instance.getRowFromElement(ui.item[0]),
item: ui.item,
nextItem: ui.item.next(),
prevItem: ui.item.prev()
};
instance.move(context);
},
axis: 'y',
delay: 0,
containment: 'document',
cursor: 'move',
scroll: true,
zIndex: 8000
});
// Prevent text selection while reordering.
this.$tbody.bind('selectstart mousedown', function (event) {
return !(0, _jquery2.default)(event.target).is('.' + instance.classNames.DRAG_HANDLE);
});
}
if (this.options.allowCreate !== false) {
// Create row responsible for adding new entries ...
this._createRow = new this.options.views.editRow({
columns: this.options.columns,
isCreateRow: true,
model: this.options.model.extend({
url: function url() {
return instance.options.resources.self;
}
}),
cancelAccessKey: this.options.cancelAccessKey,
submitAccessKey: this.options.submitAccessKey,
allowReorder: this.options.allowReorder,
fieldFocusSelector: this.options.fieldFocusSelector
}).bind(this._event.CREATED, function (values) {
if (instance.options.addPosition == undefined && instance.options.createPosition === 'bottom' || instance.options.addPosition === 'bottom') {
instance.addRow(values);
} else {
instance.addRow(values, 0);
}
}).bind(this._event.VALIDATION_ERROR, function () {
this.trigger(instance._event.FOCUS);
}).render({
errors: {},
values: {}
});
// ... and appends it as the first row
this.$create = (0, _jquery2.default)('<tbody class="' + this.classNames.CREATE + '" />').append(this._createRow.el);
// Manage which row has focus
this._applyFocusCoordinator(this._createRow);
// focus create row
this._createRow.trigger(this._event.FOCUS);
}
// when a model is removed from the collection, remove it from the viewport also
this._models.bind('remove', function (model) {
instance.getRows().forEach(function (row) {
if (row.model === model) {
if (row.hasFocus() && instance._createRow) {
instance._createRow.trigger(instance._event.FOCUS);
}
instance.removeRow(row);
}
});
});
this.fetchInitialResources();
},
fetchInitialResources: function fetchInitialResources() {
var instance = this;
if (_jquery2.default.isFunction(this.options.resources.all)) {
this.options.resources.all(function (entries) {
instance.populate(entries);
});
} else {
_jquery2.default.get(this.options.resources.all, function (entries) {
instance.populate(entries);
});
}
},
move: function move(context) {
var instance = this;
var createRequest = function createRequest(afterElement) {
if (!afterElement.length) {
return {
position: 'First'
};
} else {
var afterModel = instance.getRowFromElement(afterElement).model;
return {
after: afterModel.url()
};
}
};
if (context.row) {
var data = instance.options.reverseOrder ? createRequest(context.nextItem) : createRequest(context.prevItem);
_jquery2.default.ajax({
url: context.row.model.url() + '/move',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
complete: function complete() {
// hides loading indicator (spinner)
context.row.hideLoading();
},
success: function success(xhr) {
triggerEvtForInst(instance._event.REORDER_SUCCESS, instance, [xhr]);
},
error: function error(xhr) {
var responseData = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
triggerEvtForInst(instance._event.SERVER_ERROR, instance, [responseData, xhr, this]);
}
});
// shows loading indicator (spinner)
context.row.showLoading();
}
},
_createCollection: function _createCollection() {
var instance = this;
// create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection)
var RowsAwareCollection = this.options.Collection.extend({
// Force the collection to re-sort itself. You don't need to call this under normal
// circumstances, as the set will maintain sort order as each item is added.
sort: function sort(options) {
options || (options = {});
if (!this.comparator) {
throw new Error('Cannot sort a set without a comparator');
}
this.tableRows = instance.getRows();
this.models = this.sortBy(this.comparator);
this.tableRows = undefined;
if (!options.silent) {
this.trigger('refresh', this, options);
}
return this;
},
remove: function remove(models, options) {
this.tableRows = instance.getRows();
_backbone2.default.Collection.prototype.remove.apply(this, arguments);
this.tableRows = undefined;
return this;
}
});
return new RowsAwareCollection([], {
comparator: function comparator(row) {
// sort models in collection based on dom ordering
var index;
var currentTableRows = this.tableRows !== undefined ? this.tableRows : instance.getRows();
currentTableRows.some(function (item, i) {
if (item.model.id === row.id) {
index = i;
return true;
}
});
return index;
}
});
},
/**
* Refreshes table with entries
*
* @param entries
*/
populate: function populate(entries) {
if (this.options.reverseOrder) {
entries.reverse();
}
this.hideGlobalLoading();
if (entries && entries.length) {
// Empty the models collection
this._models.reset([], { silent: true });
// Add all the entries to collection and render them
this.renderRows(entries);
// show message to user if we have no entries
if (this.isEmpty()) {
this.showNoEntriesMsg();
}
} else {
this.showNoEntriesMsg();
}
// Ok, lets let everyone know that we are done...
this.$table.append(this.$thead);
if (this.options.createPosition === 'bottom') {
this.$table.append(this.$tbody).append(this.$create);
} else {
this.$table.append(this.$create).append(this.$tbody);
}
this.$table.removeClass(this.classNames.LOADING).trigger(this._event.INITIALIZED, [this]);
triggerEvtForInst(this._event.INITIALIZED, this, [this]);
if (this.options.autoFocus) {
this.$table.find(':input:text:first').focus(); // set focus to first field
}
},
/**
* Shows loading indicator and text
*
* @return {RestfulTable}
*/
showGlobalLoading: function showGlobalLoading() {
if (!this.$loading) {
this.$loading = (0, _jquery2.default)('<div class="aui-restfultable-init">' + (0, _throbber2.default)() + '<span class="aui-restfultable-loading">' + this.options.loadingMsg + '</span></div>');
}
if (!this.$loading.is(':visible')) {
this.$loading.insertAfter(this.$table);
}
return this;
},
/**
* Hides loading indicator and text
* @return {RestfulTable}
*/
hideGlobalLoading: function hideGlobalLoading() {
if (this.$loading) {
this.$loading.remove();
}
return this;
},
/**
* Adds row to collection and renders it
*
* @param {Object} values
* @param {number} index
* @return {RestfulTable}
*/
addRow: function addRow(values, index) {
var view;
var model;
if (!values.id) {
throw new Error('RestfulTable.addRow: to add a row values object must contain an id. ' + 'Maybe you are not returning it from your restend point?' + 'Recieved:' + JSON.stringify(values));
}
model = new this.options.model(values);
view = this._renderRow(model, index);
this._models.add(model);
this.removeNoEntriesMsg();
// Let everyone know we added a row
triggerEvtForInst(this._event.ROW_ADDED, this, [view, this]);
return this;
},
/**
* Provided a view, removes it from display and backbone collection
*
* @param row {Row} The row to remove.
*/
removeRow: function removeRow(row) {
this._models.remove(row.model);
row.remove();
if (this.isEmpty()) {
this.showNoEntriesMsg();
}
// Let everyone know we removed a row
triggerEvtForInst(this._event.ROW_REMOVED, this, [row, this]);
},
/**
* Is there any entries in the table
*
* @return {Boolean}
*/
isEmpty: function isEmpty() {
return this._models.length === 0;
},
/**
* Gets all models
*
* @return {Backbone.Collection}
*/
getModels: function getModels() {
return this._models;
},
/**
* Gets table body
*
* @return {jQuery}
*/
getTable: function getTable() {
return this.$table;
},
/**
* Gets table body
*
* @return {jQuery}
*/
getTableBody: function getTableBody() {
return this.$tbody;
},
/**
* Gets create Row
*
* @return {EditRow}
*/
getCreateRow: function getCreateRow() {
return this._createRow;
},
/**
* Gets the number of table columns, accounting for the number of
* additional columns added by RestfulTable itself
* (such as the drag handle column, buttons and actions columns)
*
* @return {Number}
*/
getColumnCount: function getColumnCount() {
var staticFieldCount = 2; // accounts for the columns allocated to submit buttons and loading indicator
if (this.allowReorder) {
++staticFieldCount;
}
return this.options.columns.length + staticFieldCount;
},
/**
* Get the Row that corresponds to the given <tr> element.
*
* @param {HTMLElement} tr
*
* @return {Row}
*/
getRowFromElement: function getRowFromElement(tr) {
return (0, _jquery2.default)(tr).data(this.dataKeys.ROW_VIEW);
},
/**
* Shows message {options.noEntriesMsg} to the user if there are no entries
*
* @return {RestfulTable}
*/
showNoEntriesMsg: function showNoEntriesMsg() {
if (this.$noEntries) {
this.$noEntries.remove();
}
this.$noEntries = (0, _jquery2.default)('<tr>').addClass(this.classNames.NO_ENTRIES).append((0, _jquery2.default)('<td>').attr('colspan', this.getColumnCount()).text(this.options.noEntriesMsg)).appendTo(this.$tbody);
return this;
},
/**
* Removes message {options.noEntriesMsg} to the user if there ARE entries
*
* @return {RestfulTable}
*/
removeNoEntriesMsg: function removeNoEntriesMsg() {
if (this.$noEntries && this._models.length > 0) {
this.$noEntries.remove();
}
return this;
},
/**
* Gets the Row from their associated <tr> elements
*
* @return {Array}
*/
getRows: function getRows() {
var instance = this;
var views = [];
this.$tbody.find('.' + this.classNames.READ_ONLY).each(function () {
var $row = (0, _jquery2.default)(this);
var view = $row.data(instance.dataKeys.ROW_VIEW);
if (view) {
views.push(view);
}
});
return views;
},
/**
* Appends entry to end or specified index of table
*
* @param {EntryModel} model
* @param index
*
* @return {jQuery}
*/
_renderRow: function _renderRow(model, index) {
var instance = this;
var $rows = this.$tbody.find('.' + this.classNames.READ_ONLY);
var $row;
var view;
view = new this._rowClass({
model: model,
columns: this.options.columns,
allowEdit: this.options.allowEdit,
allowDelete: this.options.allowDelete,
allowReorder: this.options.allowReorder,
deleteConfirmation: this.options.deleteConfirmation
});
this.removeNoEntriesMsg();
view.bind(this._event.ROW_EDIT, function (field) {
triggerEvtForInst(this._event.EDIT_ROW, {}, [this, instance]);
instance.edit(this, field);
});
$row = view.render().$el;
if (index !== -1) {
if (typeof index === 'number' && $rows.length !== 0) {
$row.insertBefore($rows[index]);
} else {
this.$tbody.append($row);
}
}
$row.data(this.dataKeys.ROW_VIEW, view);
// deactivate all rows - used in the cases, such as opening a dropdown where you do not want the table editable
// or any interactions
view.bind(this._event.MODAL, function () {
instance.$table.removeClass(instance.classNames.ALLOW_HOVER);
instance.$tbody.sortable('disable');
instance.getRows().forEach(function (row) {
if (!instance.isRowBeingEdited(row)) {
row.delegateEvents({}); // clear all events
}
});
});
// activate all rows - used in the cases, such as opening a dropdown where you do not want the table editable
// or any interactions
view.bind(this._event.MODELESS, function () {
instance.$table.addClass(instance.classNames.ALLOW_HOVER);
instance.$tbody.sortable('enable');
instance.getRows().forEach(function (row) {
if (!instance.isRowBeingEdited(row)) {
row.delegateEvents(); // rebind all events
}
});
});
// ensure that when this row is focused no other are
this._applyFocusCoordinator(view);
this.trigger(this._event.ROW_INITIALIZED, view);
return view;
},
/**
* Returns if the row is edit mode or note.
*
* @param {Row} row Read-only row to check if being edited.
*
* @return {Boolean}
*/
isRowBeingEdited: function isRowBeingEdited(row) {
var isBeingEdited = false;
this.editRows.some(function (editRow) {
if (editRow.el === row.el) {
isBeingEdited = true;
return true;
}
});
return isBeingEdited;
},
/**
* Ensures that when supplied view is focused no others are
*
* @param {Backbone.View} view
* @return {RestfulTable}
*/
_applyFocusCoordinator: function _applyFocusCoordinator(view) {
var instance = this;
if (!view.hasFocusBound) {
view.hasFocusBound = true;
view.bind(this._event.FOCUS, function () {
if (instance.focusedRow && instance.focusedRow !== view) {
instance.focusedRow.trigger(instance._event.BLUR);
}
instance.focusedRow = view;
if (view instanceof _row2.default && instance._createRow) {
instance._createRow.enable();
}
});
}
return this;
},
/**
* Remove specified row from collection holding rows being concurrently edited
*
* @param {EditRow} editView
*
* @return {RestfulTable}
*/
_removeEditRow: function _removeEditRow(editView) {
var index = _jquery2.default.inArray(editView, this.editRows);
this.editRows.splice(index, 1);
return this;
},
/**
* Focuses last row still being edited or create row (if it exists)
*
* @return {RestfulTable}
*/
_shiftFocusAfterEdit: function _shiftFocusAfterEdit() {
if (this.editRows.length > 0) {
this.editRows[this.editRows.length - 1].trigger(this._event.FOCUS);
} else if (this._createRow) {
this._createRow.trigger(this._event.FOCUS);
}
return this;
},
/**
* Evaluate if we save row when we blur. We can only do this when there is one row being edited at a time, otherwise
* it causes an infinite loop JRADEV-5325
*
* @return {boolean}
*/
_saveEditRowOnBlur: function _saveEditRowOnBlur() {
return this.editRows.length <= 1;
},
/**
* Dismisses rows being edited concurrently that have no changes
*/
dismissEditRows: function dismissEditRows() {
this.editRows.forEach(function (editRow) {
if (!editRow.hasUpdates()) {
editRow.trigger(this._event.FINISHED_EDITING);
}
}, this);
},
/**
* Converts readonly row to editable view
*
* @param {Backbone.View} row
* @param {String} field - field name to focus
* @return {Backbone.View} editRow
*/
edit: function edit(row, field) {
var instance = this;
var editRow = new this.options.views.editRow({
el: row.el,
columns: this.options.columns,
isUpdateMode: true,
allowReorder: this.options.allowReorder,
fieldFocusSelector: this.options.fieldFocusSelector,
model: row.model,
cancelAccessKey: this.options.cancelAccessKey,
submitAccessKey: this.options.submitAccessKey
});
var values = row.model.toJSON();
values.update = true;
editRow.render({
errors: {},
update: true,
values: values
}).bind(instance._event.UPDATED, function (model, focusUpdated) {
instance._removeEditRow(this);
this.unbind();
row.render().delegateEvents(); // render and rebind events
row.trigger(instance._event.UPDATED); // trigger blur fade out
if (focusUpdated !== false) {
instance._shiftFocusAfterEdit();
}
}).bind(instance._event.VALIDATION_ERROR, function () {
this.trigger(instance._event.FOCUS);
}).bind(instance._event.FINISHED_EDITING, function () {
instance._removeEditRow(this);
row.render().delegateEvents();
this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired
}).bind(instance._event.CANCEL, function () {
instance._removeEditRow(this);
this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired
row.render().delegateEvents(); // render and rebind events
instance._shiftFocusAfterEdit();
}).bind(instance._event.BLUR, function () {
instance.dismissEditRows(); // dismiss edit rows that have no changes
if (instance._saveEditRowOnBlur()) {
this.trigger(instance._event.SAVE, false); // save row, which if successful will call the updated event above
}
});
// Ensure that if focus is pulled to another row, we blur the edit row
this._applyFocusCoordinator(editRow);
// focus edit row, which has the flow on effect of blurring current focused row
editRow.trigger(instance._event.FOCUS, field);
// disables form fields
if (instance._createRow) {
instance._createRow.disable();
}
this.editRows.push(editRow);
return editRow;
},
/**
* Renders all specified rows
*
* @param rows {Array<Backbone.Model>} array of objects describing Backbone.Model's to render
* @return {RestfulTable}
*/
renderRows: function renderRows() {
var _this = this;
var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var comparator = this._models.comparator;
var els = [];
this._models.comparator = undefined; // disable temporarily, assume rows are sorted
var models = rows.map(function (row) {
var model = new _this.options.model(row);
els.push(_this._renderRow(model, -1).el);
return model;
});
this._models.add(models, { silent: true });
this._models.comparator = comparator;
this.removeNoEntriesMsg();
this.$tbody.append(els);
return this;
},
/**
* Gets default options
*
* @param {Object} options
*/
_getDefaultOptions: function _getDefaultOptions(options) {
return {
model: options.model || _entryModel2.default,
allowEdit: true,
views: {
editRow: _editRow2.default,
row: _row2.default
},
Collection: _backbone2.default.Collection.extend({
url: options.resources.self,
model: options.model || _entryModel2.default
}),
allowReorder: false,
fieldFocusSelector: function fieldFocusSelector(name) {
return ':input[name=' + name + '], #' + name;
},
loadingMsg: options.loadingMsg || AJS.I18n.getText('aui.words.loading')
};
}
});
RestfulTable.ClassNames = _classNames2.default;
RestfulTable.CustomCreateView = _customCreateView2.default;
RestfulTable.CustomEditView = _customEditView2.default;
RestfulTable.CustomReadView = _customReadView2.default;
RestfulTable.DataKeys = _dataKeys2.default;
RestfulTable.EditRow = _editRow2.default;
RestfulTable.EntryModel = _entryModel2.default;
RestfulTable.Events = _events2.default;
RestfulTable.Row = _row2.default;
RestfulTable.Throbber = _throbber2.default;
(0, _globalize2.default)('RestfulTable', RestfulTable);
exports.default = RestfulTable;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/result-set.js
(typeof window === 'undefined' ? global : window).__e9e07e92893b0b7f9f3e6e2ffe018c96 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ResultSet = _backbone2.default.Model.extend({
initialize: function initialize(options) {
this.set('active', null, { silent: true });
this.collection = new _backbone2.default.Collection();
this.collection.bind('reset', this.setActive, this);
this.source = options.source;
this.source.bind('respond', this.process, this);
},
url: false,
process: function process(response) {
this.set('query', response.query);
this.collection.reset(response.results);
this.set('length', response.results.length);
this.trigger('update', this);
},
setActive: function setActive() {
var id = arguments[0] instanceof _backbone2.default.Collection ? false : arguments[0];
var model = id ? this.collection.get(id) : this.collection.first();
this.set('active', model || null);
return this.get('active');
},
next: function next() {
var current = this.collection.indexOf(this.get('active'));
var i = (current + 1) % this.get('length');
var next = this.collection.at(i);
return this.setActive(next && next.id);
},
prev: function prev() {
var current = this.collection.indexOf(this.get('active'));
var i = (current === 0 ? this.get('length') : current) - 1;
var prev = this.collection.at(i);
return this.setActive(prev && prev.id);
},
each: function each() {
return this.collection.each.apply(this.collection, arguments);
}
});
(0, _globalize2.default)('ResultSet', ResultSet);
exports.default = ResultSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/results-list.js
(typeof window === 'undefined' ? global : window).__1e2a7fafeebd870fc623ea9cf84e84eb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _resultSet = __e9e07e92893b0b7f9f3e6e2ffe018c96;
var _resultSet2 = _interopRequireDefault(_resultSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ResultsList = _backbone2.default.View.extend({
events: {
'click [data-id]': 'setSelection'
},
initialize: function initialize(options) {
if (!this.model) {
this.model = new _resultSet2.default({ source: options.source });
}
if (!(this.model instanceof _resultSet2.default)) {
throw new Error('model must be set to a ResultSet');
}
this.model.bind('update', this.process, this);
this.render = _underscore2.default.wrap(this.render, function (func) {
this.trigger('rendering');
func.apply(this, arguments);
this.trigger('rendered');
});
},
process: function process() {
if (!this._shouldShow(this.model.get('query'))) {
return;
}
this.show();
},
render: function render() {
var ul = _backbone2.default.$('<ul/>');
this.model.each(function (model) {
var li = _backbone2.default.$('<li/>').attr('data-id', model.id).html(this.renderItem(model)).appendTo(ul);
}, this);
this.$el.html(ul);
return this;
},
renderItem: function renderItem() {
return;
},
setSelection: function setSelection(event) {
var id = event.target.getAttribute('data-id');
var selected = this.model.setActive(id);
this.trigger('selected', selected);
},
show: function show() {
this.lastQuery = this.model.get('query');
this._hiddenQuery = null;
this.render();
this.$el.show();
},
hide: function hide() {
this.$el.hide();
this._hiddenQuery = this.lastQuery;
},
size: function size() {
return this.model.get('length');
},
_shouldShow: function _shouldShow(query) {
return query === '' || !(this._hiddenQuery && this._hiddenQuery === query);
}
});
(0, _globalize2.default)('ResultsList', ResultsList);
exports.default = ResultsList;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/option.js
(typeof window === 'undefined' ? global : window).__9635740841d5de6fc1070a95b24a5161 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _escapeHtml = __8106a911fd0030e07f16b2767ac9f548;
var _escapeHtml2 = _interopRequireDefault(_escapeHtml);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = (0, _skate2.default)('aui-option', {
created: function created(element) {
Object.defineProperty(element, 'value', {
get: function get() {
return element.getAttribute('value') || (0, _escapeHtml2.default)(this.textContent);
},
set: function set(value) {
element.setAttribute('value', value);
}
});
},
prototype: {
serialize: function serialize() {
var json = {};
if (this.hasAttribute('img-src')) {
json['img-src'] = this.getAttribute('img-src');
}
json.value = this.value;
json.label = (0, _escapeHtml2.default)(this.textContent);
return json;
}
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestion-model.js
(typeof window === 'undefined' ? global : window).__2b6275390f681ad9cb41cbbc6712cb3a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.Model.extend({
idAttribute: 'label',
getLabel: function getLabel() {
return this.get('label') || this.get('value');
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestions-model.js
(typeof window === 'undefined' ? global : window).__1288846ede15fbf7e700f826a71a60c0 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function SuggestionsModel() {
this._suggestions = [];
this._activeIndex = -1;
}
SuggestionsModel.prototype = {
onChange: function onChange() {},
onHighlightChange: function onHighlightChange() {},
get: function get(index) {
return this._suggestions[index];
},
set: function set(suggestions) {
var oldSuggestions = this._suggestions;
this._suggestions = suggestions || [];
this.onChange(oldSuggestions);
return this;
},
getNumberOfResults: function getNumberOfResults() {
return this._suggestions.length;
},
setHighlighted: function setHighlighted(toHighlight) {
if (toHighlight) {
for (var i = 0; i < this._suggestions.length; i++) {
if (this._suggestions[i].id === toHighlight.id) {
this.highlight(i);
}
}
}
return this;
},
highlight: function highlight(index) {
this._activeIndex = index;
this.onHighlightChange();
return this;
},
highlightPrevious: function highlightPrevious() {
var current = this._activeIndex;
var previousActiveIndex = current === 0 ? current : current - 1;
this.highlight(previousActiveIndex);
return this;
},
highlightNext: function highlightNext() {
var current = this._activeIndex;
var nextActiveIndex = current === this._suggestions.length - 1 ? current : current + 1;
this.highlight(nextActiveIndex);
return this;
},
highlighted: function highlighted() {
return this.get(this._activeIndex);
},
highlightedIndex: function highlightedIndex() {
return this._activeIndex;
}
};
exports.default = SuggestionsModel;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestions-view.js
(typeof window === 'undefined' ? global : window).__93aa20046b4aad30a18c95a624221d6b = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__be3e01199078cdf5ded88dda6a8fbec9;
var _alignment = __640a50a417a578824aa17827db8c9d2f;
var _alignment2 = _interopRequireDefault(_alignment);
var _layer = __06224e18e744dc8a44794ab29f247385;
var _layer2 = _interopRequireDefault(_layer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateListItemID(listId, index) {
return listId + '-' + index;
}
/**
*
* @param view SuggestionsView
*/
function enableAlignment(view) {
if (view.anchor && !view.auiAlignment) {
view.auiAlignment = new _alignment2.default(view.el, view.anchor);
}
if (view.auiAlignment) {
view.auiAlignment.enable();
}
}
function destroyAlignment(view) {
if (view.auiAlignment) {
view.auiAlignment.destroy();
}
}
function matchWidth(view) {
(0, _jquery2.default)(view.el).css('min-width', (0, _jquery2.default)(view.anchor).outerWidth());
}
function SuggestionsView(element, anchor) {
this.el = element;
this.anchor = anchor;
}
function clearActive(element) {
(0, _jquery2.default)(element).find('.aui-select-active').removeClass('aui-select-active');
}
SuggestionsView.prototype = {
render: function render(suggestions, currentLength, listId) {
this.currListId = listId;
var html = '';
// Do nothing if we have no new suggestions, otherwise append anything else we find.
if (suggestions.length) {
var i = currentLength;
suggestions.forEach(function (sugg) {
var label = sugg.getLabel();
var imageSrc = sugg.get('img-src');
var image = imageSrc ? '<img src="' + imageSrc + '"/>' : '';
var newValueText = sugg.get('new-value') ? ' (<em>' + AJS.I18n.getText('aui.select.new.value') + '</em>)' : '';
html += '<li role="option" class="aui-select-suggestion" id="' + generateListItemID(listId, i) + '">' + image + label + newValueText + '</li>';
i++;
});
// If the old suggestions were empty, a <li> of 'No suggestions' will be appended, we need to remove it
if (currentLength) {
this.el.querySelector('ul').innerHTML += html;
} else {
this.el.querySelector('ul').innerHTML = html;
}
} else if (!currentLength) {
this.el.querySelector('ul').innerHTML = '<li role="option" class="aui-select-no-suggestions">' + AJS.I18n.getText('aui.select.no.suggestions') + '</li>';
}
return this;
},
setActive: function setActive(active) {
clearActive(this.el);
(0, _jquery2.default)(this.el).find('#' + generateListItemID(this.currListId, active)).addClass('aui-select-active');
},
getActive: function getActive() {
return this.el.querySelector('.aui-select-active');
},
show: function show() {
matchWidth(this);
(0, _layer2.default)(this.el).show();
enableAlignment(this);
},
hide: function hide() {
clearActive(this.el);
(0, _layer2.default)(this.el).hide();
destroyAlignment(this);
},
isVisible: function isVisible() {
return (0, _jquery2.default)(this.el).is(':visible');
}
};
exports.default = SuggestionsView;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/template.js
(typeof window === 'undefined' ? global : window).__e2c1f657d183d1b538d81a87ba0b4760 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = (0, _skatejsTemplateHtml2.default)('\n <input type="text" class="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false">\n <select></select>\n <datalist>\n <content select="aui-option"></content>\n </datalist>\n <button class="aui-button" role="button" tabindex="-1" type="button"></button>\n <div class="aui-popover" role="listbox" data-aui-alignment="bottom left">\n <ul class="aui-optionlist" role="presentation"></ul>\n </div>\n <div class="aui-select-status assistive" aria-live="polite" role="status"></div>\n');
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/select.js
(typeof window === 'undefined' ? global : window).__c7e0d50b6a65bf58a28e1b310881043e = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__133851082a1337b5710e5a2aa98258e9;
__be3e01199078cdf5ded88dda6a8fbec9;
__313e15322266d7b6cc6ffb039891d9ce;
var _option = __9635740841d5de6fc1070a95b24a5161;
var _option2 = _interopRequireDefault(_option);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _customEvent = __16bf5f1d761138a726209288b7afb338;
var _customEvent2 = _interopRequireDefault(_customEvent);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _progressiveDataSet = __bc3aa98a1624c420c64de6459784d4cc;
var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _state = __6b822d4c87bd59d8adf46df64b0f24c7;
var _state2 = _interopRequireDefault(_state);
var _suggestionModel = __2b6275390f681ad9cb41cbbc6712cb3a;
var _suggestionModel2 = _interopRequireDefault(_suggestionModel);
var _suggestionsModel = __1288846ede15fbf7e700f826a71a60c0;
var _suggestionsModel2 = _interopRequireDefault(_suggestionsModel);
var _suggestionsView = __93aa20046b4aad30a18c95a624221d6b;
var _suggestionsView2 = _interopRequireDefault(_suggestionsView);
var _template = __e2c1f657d183d1b538d81a87ba0b4760;
var _template2 = _interopRequireDefault(_template);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DESELECTED = -1;
var NO_HIGHLIGHT = -1;
var DEFAULT_SS_PDS_SIZE = 20;
function clearElementImage(element) {
element._input.removeAttribute('style');
(0, _jquery2.default)(element._input).removeClass('aui-select-has-inline-image');
}
function deselect(element) {
element._select.selectedIndex = DESELECTED;
clearElementImage(element);
}
function hasResults(element) {
return element._suggestionModel.getNumberOfResults();
}
function waitForAssistive(callback) {
setTimeout(callback, 50);
}
function setBusyState(element) {
if (!element._button.isBusy()) {
element._button.busy();
element._input.setAttribute('aria-busy', 'true');
element._dropdown.setAttribute('aria-busy', 'true');
}
}
function setIdleState(element) {
element._button.idle();
element._input.setAttribute('aria-busy', 'false');
element._dropdown.setAttribute('aria-busy', 'false');
}
function matchPrefix(model, query) {
var value = model.get('label').toLowerCase();
return value.indexOf(query.toLowerCase()) === 0;
}
function hideDropdown(element) {
element._suggestionsView.hide();
element._input.setAttribute('aria-expanded', 'false');
}
function setInitialVisualState(element) {
var initialHighlightedItem = hasResults(element) ? 0 : NO_HIGHLIGHT;
element._suggestionModel.highlight(initialHighlightedItem);
hideDropdown(element);
}
function setElementImage(element, imageSource) {
(0, _jquery2.default)(element._input).addClass('aui-select-has-inline-image');
element._input.setAttribute('style', 'background-image: url(' + imageSource + ')');
}
function suggest(element, autoHighlight, query) {
element._autoHighlight = autoHighlight;
if (query === undefined) {
query = element._input.value;
}
element._progressiveDataSet.query(query);
}
function setInputImageToHighlightedSuggestion(element) {
var imageSource = element._suggestionModel.highlighted() && element._suggestionModel.highlighted().get('img-src');
if (imageSource) {
setElementImage(element, imageSource);
}
}
function setValueAndDisplayFromModel(element, model) {
if (!model) {
return;
}
var option = document.createElement('option');
var select = element._select;
var value = model.get('value') || model.get('label');
option.setAttribute('selected', '');
option.setAttribute('value', value);
option.textContent = model.getLabel();
// Sync element value.
element._input.value = option.textContent;
select.innerHTML = '';
select.options.add(option);
select.dispatchEvent(new _customEvent2.default('change', { bubbles: true }));
}
function clearValue(element) {
element._input.value = '';
element._select.innerHTML = '';
}
function selectHighlightedSuggestion(element) {
setValueAndDisplayFromModel(element, element._suggestionModel.highlighted());
setInputImageToHighlightedSuggestion(element);
setInitialVisualState(element);
}
function convertOptionToModel(option) {
return new _suggestionModel2.default(option.serialize());
}
function convertOptionsToModels(element) {
var models = [];
for (var i = 0; i < element._datalist.children.length; i++) {
var option = element._datalist.children[i];
models.push(convertOptionToModel(option));
}
return models;
}
function clearAndSet(element, data) {
element._suggestionModel.set();
element._suggestionModel.set(data.results);
}
function getActiveId(select) {
var active = select._dropdown.querySelector('.aui-select-active');
return active && active.id;
}
function getIndexInResults(id, results) {
var resultsIds = _jquery2.default.map(results, function (result) {
return result.id;
});
return resultsIds.indexOf(id);
}
function createNewValueModel(element) {
var option = new _option2.default();
option.setAttribute('value', element._input.value);
var newValueSuggestionModel = convertOptionToModel(option);
newValueSuggestionModel.set('new-value', true);
return newValueSuggestionModel;
}
function initialiseProgressiveDataSet(element) {
element._progressiveDataSet = new _progressiveDataSet2.default(convertOptionsToModels(element), {
model: _suggestionModel2.default,
matcher: matchPrefix,
queryEndpoint: element._queryEndpoint,
maxResults: DEFAULT_SS_PDS_SIZE
});
element._isSync = element._queryEndpoint ? false : true;
// Progressive data set should indicate whether or not it is busy when processing any async requests.
// Check if there's any active queries left, if so: set spinner and state to busy, else set to idle and remove
// the spinner.
element._progressiveDataSet.on('activity', function () {
if (element._progressiveDataSet.activeQueryCount && !element._isSync) {
setBusyState(element);
(0, _state2.default)(element).set('should-flag-new-suggestions', false);
} else {
setIdleState(element);
(0, _state2.default)(element).set('should-flag-new-suggestions', true);
}
});
// Progressive data set doesn't do anything if the query is empty so we
// must manually convert all data list options into models.
//
// Otherwise progressive data set can do everything else for us:
// 1. Sync matching
// 2. Async fetching and matching
element._progressiveDataSet.on('respond', function (data) {
var optionToHighlight;
// This means that a query was made before the input was cleared and
// we should cancel the response.
if (data.query && !element._input.value) {
return;
}
if ((0, _state2.default)(element).get('should-cancel-response')) {
if (!element._progressiveDataSet.activeQueryCount) {
(0, _state2.default)(element).set('should-cancel-response', false);
}
return;
}
if (!data.query) {
data.results = convertOptionsToModels(element);
}
var isInputExactMatch = getIndexInResults(element._input.value, data.results) !== -1;
var isInputEmpty = !element._input.value;
if (element.hasAttribute('can-create-values') && !isInputExactMatch && !isInputEmpty) {
data.results.push(createNewValueModel(element));
}
if (!(0, _state2.default)(element).get('should-include-selected')) {
var indexOfValueInResults = getIndexInResults(element.value, data.results);
if (indexOfValueInResults >= 0) {
data.results.splice(indexOfValueInResults, 1);
}
}
clearAndSet(element, data);
optionToHighlight = element._suggestionModel.highlighted() || data.results[0];
if (element._autoHighlight) {
element._suggestionModel.setHighlighted(optionToHighlight);
waitForAssistive(function () {
element._input.setAttribute('aria-activedescendant', getActiveId(element));
});
}
element._input.setAttribute('aria-expanded', 'true');
// If the response is async (append operation), has elements to append and has a highlighted element, we need to update the status.
if (!element._isSync && element._suggestionsView.getActive() && (0, _state2.default)(element).get('should-flag-new-suggestions')) {
element.querySelector('.aui-select-status').innerHTML = AJS.I18n.getText('aui.select.new.suggestions');
}
element._suggestionsView.show();
if (element._autoHighlight) {
waitForAssistive(function () {
element._input.setAttribute('aria-activedescendant', getActiveId(element));
});
}
});
}
function associateDropdownAndTrigger(element) {
element._dropdown.id = element._listId;
element.querySelector('button').setAttribute('aria-controls', element._listId);
}
function bindHighlightMouseover(element) {
(0, _jquery2.default)(element._dropdown).on('mouseover', 'li', function (e) {
if (hasResults(element)) {
element._suggestionModel.highlight((0, _jquery2.default)(e.target).index());
}
});
}
function bindSelectMousedown(element) {
(0, _jquery2.default)(element._dropdown).on('mousedown', 'li', function (e) {
if (hasResults(element)) {
element._suggestionModel.highlight((0, _jquery2.default)(e.target).index());
selectHighlightedSuggestion(element);
element._suggestionsView.hide();
element._input.removeAttribute('aria-activedescendant');
} else {
return false;
}
});
}
function initialiseValue(element) {
var option = element._datalist.querySelector('aui-option[selected]');
if (option) {
setValueAndDisplayFromModel(element, convertOptionToModel(option));
}
}
function isQueryInProgress(element) {
return element._progressiveDataSet.activeQueryCount > 0;
}
function focusInHandler(element) {
//if there is a selected value the single select should do an empty
//search and return everything
var searchValue = element.value ? '' : element._input.value;
var isInputEmpty = element._input.value === '';
(0, _state2.default)(element).set('should-include-selected', isInputEmpty);
suggest(element, true, searchValue);
}
function cancelInProgressQueries(element) {
if (isQueryInProgress(element)) {
(0, _state2.default)(element).set('should-cancel-response', true);
}
}
function getSelectedLabel(element) {
if (element._select.selectedIndex >= 0) {
return element._select.options[element._select.selectedIndex].textContent;
}
}
function handleInvalidInputOnFocusOut(element) {
var selectCanBeEmpty = !element.hasAttribute('no-empty-values');
var selectionIsEmpty = !element._input.value;
var selectionNotExact = element._input.value !== getSelectedLabel(element);
var selectionNotValid = selectionIsEmpty || selectionNotExact;
if (selectionNotValid) {
if (selectCanBeEmpty) {
deselect(element);
} else {
var selection = getSelectedLabel(element);
if (typeof selection === 'undefined') {
deselect(element);
} else {
element._input.value = selection;
}
}
}
}
function handleHighlightOnFocusOut(element) {
// Forget the highlighted suggestion.
element._suggestionModel.highlight(NO_HIGHLIGHT);
}
function focusOutHandler(element) {
cancelInProgressQueries(element);
handleInvalidInputOnFocusOut(element);
handleHighlightOnFocusOut(element);
hideDropdown(element);
}
function handleTabOut(element) {
var isSuggestionViewVisible = element._suggestionsView.isVisible();
if (isSuggestionViewVisible) {
selectHighlightedSuggestion(element);
}
}
var select = (0, _skate2.default)('aui-select', {
template: _template2.default,
created: function created(element) {
element._listId = (0, _uniqueId2.default)();
element._input = element.querySelector('input');
element._select = element.querySelector('select');
element._dropdown = element.querySelector('.aui-popover');
element._datalist = element.querySelector('datalist');
element._button = element.querySelector('button');
element._suggestionsView = new _suggestionsView2.default(element._dropdown, element._input);
element._suggestionModel = new _suggestionsModel2.default();
element._suggestionModel.onChange = function (oldSuggestions) {
var suggestionsToAdd = [];
element._suggestionModel._suggestions.forEach(function (newSuggestion) {
var inArray = oldSuggestions.some(function (oldSuggestion) {
return newSuggestion.id === oldSuggestion.id;
});
if (!inArray) {
suggestionsToAdd.push(newSuggestion);
}
});
element._suggestionsView.render(suggestionsToAdd, oldSuggestions.length, element._listId);
};
element._suggestionModel.onHighlightChange = function () {
var active = element._suggestionModel.highlightedIndex();
element._suggestionsView.setActive(active);
element._input.setAttribute('aria-activedescendant', getActiveId(element));
};
},
attached: function attached(element) {
_skate2.default.init(element);
initialiseProgressiveDataSet(element);
associateDropdownAndTrigger(element);
element._input.setAttribute('aria-controls', element._listId);
element.setAttribute('tabindex', '-1');
bindHighlightMouseover(element);
bindSelectMousedown(element);
initialiseValue(element);
setInitialVisualState(element);
setInputImageToHighlightedSuggestion(element);
},
attributes: {
id: function id(element, data) {
if (element.id) {
element.querySelector('input').id = data.newValue + _constants.INPUT_SUFFIX;
}
},
name: function name(element, data) {
element.querySelector('select').setAttribute('name', data.newValue);
},
placeholder: function placeholder(element, data) {
element.querySelector('input').setAttribute('placeholder', data.newValue);
},
src: function src(element, data) {
element._queryEndpoint = data.newValue;
}
},
events: {
'blur input': function blurInput(element) {
focusOutHandler(element);
},
'mousedown button': function mousedownButton(element) {
if (document.activeElement === element._input && element._dropdown.getAttribute('aria-hidden') === 'false') {
(0, _state2.default)(element).set('prevent-open-on-button-click', true);
}
},
'click input': function clickInput(element) {
focusInHandler(element);
},
'click button': function clickButton(element) {
var data = (0, _state2.default)(element);
if (data.get('prevent-open-on-button-click')) {
data.set('prevent-open-on-button-click', false);
} else {
element.focus();
}
},
input: function input(element) {
if (!element._input.value) {
hideDropdown(element);
} else {
(0, _state2.default)(element).set('should-include-selected', true);
suggest(element, true);
}
},
'keydown input': function keydownInput(element, e) {
var currentValue = element._input.value;
var handled = false;
if (e.keyCode === _keyCode2.default.ESCAPE) {
cancelInProgressQueries(element);
hideDropdown(element);
return;
}
var isSuggestionViewVisible = element._suggestionsView.isVisible();
if (isSuggestionViewVisible && hasResults(element)) {
if (e.keyCode === _keyCode2.default.ENTER) {
cancelInProgressQueries(element);
selectHighlightedSuggestion(element);
e.preventDefault();
} else if (e.keyCode === _keyCode2.default.TAB) {
handleTabOut(element);
handled = true;
} else if (e.keyCode === _keyCode2.default.UP) {
element._suggestionModel.highlightPrevious();
e.preventDefault();
} else if (e.keyCode === _keyCode2.default.DOWN) {
element._suggestionModel.highlightNext();
e.preventDefault();
}
} else if (e.keyCode === _keyCode2.default.UP || e.keyCode === _keyCode2.default.DOWN) {
focusInHandler(element);
e.preventDefault();
}
handled = handled || e.defaultPrevented;
setTimeout(function emulateCrossBrowserInputEvent() {
if (element._input.value !== currentValue && !handled) {
element.dispatchEvent(new _customEvent2.default('input', { bubbles: true }));
}
}, 0);
}
},
prototype: {
get value() {
var selected = this._select.options[this._select.selectedIndex];
return selected ? selected.value : '';
},
set value(value) {
if (value === '') {
clearValue(this);
} else if (value) {
var data = this._progressiveDataSet;
var model = data.findWhere({
value: value
}) || data.findWhere({
label: value
});
// Create a new value if allowed and the value doesn't exist.
if (!model && this.hasAttribute('can-create-values')) {
model = new _suggestionModel2.default({ value: value, label: value });
}
setValueAndDisplayFromModel(this, model);
}
return this;
},
get displayValue() {
return this._input.value;
},
blur: function blur() {
this._input.blur();
focusOutHandler(this);
return this;
},
focus: function focus() {
this._input.focus();
focusInHandler(this);
return this;
}
}
});
(0, _amdify2.default)('aui/select', select);
(0, _globalize2.default)('select', select);
exports.default = select;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/plugins/jquery.select2.js
(typeof window === 'undefined' ? global : window).__b2190710f2822b5d7286528d3eaff37f = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/*
Copyright 2012 Igor Vaynberg
Version: 3.4.5 Timestamp: Mon Nov 4 08:22:42 PST 2013
This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.
You may obtain a copy of the Apache License and the GPL License at:
http://www.apache.org/licenses/LICENSE-2.0
http://www.gnu.org/licenses/gpl-2.0.html
Unless required by applicable law or agreed to in writing, software distributed under the
Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
the specific language governing permissions and limitations under the Apache License and the GPL License.
*/
(function ($) {
if(typeof $.fn.each2 == "undefined") {
$.extend($.fn, {
/*
* 4-10 times faster .each replacement
* use it carefully, as it overrides jQuery context of element on each iteration
*/
each2 : function (c) {
var j = $([0]), i = -1, l = this.length;
while (
++i < l
&& (j.context = j[0] = this[i])
&& c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
);
return this;
}
});
}
})(jQuery);
(function ($, undefined) {
/*global document, window, jQuery, console */
if (window.Select2 !== undefined) {
return;
}
var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
isArrow: function (k) {
k = k.which ? k.which : k;
switch (k) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
return true;
}
return false;
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
}
},
MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",
DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"};
$document = $(document);
nextUid=(function() { var counter=1; return function() { return counter++; }; }());
function stripDiacritics(str) {
var ret, i, l, c;
if (!str || str.length < 1) return str;
ret = "";
for (i = 0, l = str.length; i < l; i++) {
c = str.charAt(i);
ret += DIACRITICS[c] || c;
}
return ret;
}
function indexOf(value, array) {
var i = 0, l = array.length;
for (; i < l; i = i + 1) {
if (equal(value, array[i])) return i;
}
return -1;
}
function measureScrollbar () {
var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
$template.appendTo('body');
var dim = {
width: $template.width() - $template[0].clientWidth,
height: $template.height() - $template[0].clientHeight
};
$template.remove();
return dim;
}
/**
* Compares equality of a and b
* @param a
* @param b
*/
function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
// Check whether 'a' or 'b' is a string (primitive or object).
// The concatenation of an empty string (+'') converts its argument to a string's primitive.
if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
return false;
}
/**
* Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
* strings
* @param string
* @param separator
*/
function splitVal(string, separator) {
var val, i, l;
if (string === null || string.length < 1) return [];
val = string.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
return val;
}
function getSideBorderPadding(element) {
return element.outerWidth(false) - element.width();
}
function installKeyUpChangeEvent(element) {
var key="keyup-change-value";
element.on("keydown", function () {
if ($.data(element, key) === undefined) {
$.data(element, key, element.val());
}
});
element.on("keyup", function () {
var val= $.data(element, key);
if (val !== undefined && element.val() !== val) {
$.removeData(element, key);
element.trigger("keyup-change");
}
});
}
$document.on("mousemove", function (e) {
lastMousePosition.x = e.pageX;
lastMousePosition.y = e.pageY;
});
/**
* filters mouse events so an event is fired only if the mouse moved.
*
* filters out mouse events that occur when mouse is stationary but
* the elements under the pointer are scrolled.
*/
function installFilteredMouseMove(element) {
element.on("mousemove", function (e) {
var lastpos = lastMousePosition;
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
}
/**
* Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
* within the last quietMillis milliseconds.
*
* @param quietMillis number of milliseconds to wait before invoking fn
* @param fn function to be debounced
* @param ctx object to be used as this reference within fn
* @return debounced version of fn
*/
function debounce(quietMillis, fn, ctx) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
/**
* A simple implementation of a thunk
* @param formula function used to lazily initialize the thunk
* @return {Function}
*/
function thunk(formula) {
var evaluated = false,
value;
return function() {
if (evaluated === false) { value = formula(); evaluated = true; }
return value;
};
};
function installDebouncedScroll(threshold, element) {
var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
element.on("scroll", function (e) {
if (indexOf(e.target, element.get()) >= 0) notify(e);
});
}
function focus($el) {
if ($el[0] === document.activeElement) return;
/* set the focus in a 0 timeout - that way the focus is set after the processing
of the current event has finished - which seems like the only reliable way
to set focus */
window.setTimeout(function() {
var el=$el[0], pos=$el.val().length, range;
$el.focus();
/* make sure el received focus so we do not error out when trying to manipulate the caret.
sometimes modals or others listeners may steal it after its set */
if ($el.is(":visible") && el === document.activeElement) {
/* after the focus is set move the caret to the end, necessary when we val()
just before setting focus */
if(el.setSelectionRange)
{
el.setSelectionRange(pos, pos);
}
else if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
}
}
}, 0);
}
function getCursorInfo(el) {
el = $(el)[0];
var offset = 0;
var length = 0;
if ('selectionStart' in el) {
offset = el.selectionStart;
length = el.selectionEnd - offset;
} else if ('selection' in document) {
el.focus();
var sel = document.selection.createRange();
length = document.selection.createRange().text.length;
sel.moveStart('character', -el.value.length);
offset = sel.text.length - length;
}
return { offset: offset, length: length };
}
function killEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function killEventImmediately(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function measureTextWidth(e) {
if (!sizer){
var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
sizer = $(document.createElement("div")).css({
position: "absolute",
left: "-10000px",
top: "-10000px",
display: "none",
fontSize: style.fontSize,
fontFamily: style.fontFamily,
fontStyle: style.fontStyle,
fontWeight: style.fontWeight,
letterSpacing: style.letterSpacing,
textTransform: style.textTransform,
whiteSpace: "nowrap"
});
sizer.attr("class","select2-sizer");
$("body").append(sizer);
}
sizer.text(e.val());
return sizer.width();
}
function syncCssClasses(dest, src, adapter) {
var classes, replacements = [], adapted;
classes = dest.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") === 0) {
replacements.push(this);
}
});
}
classes = src.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") !== 0) {
adapted = adapter(this);
if (adapted) {
replacements.push(adapted);
}
}
});
}
dest.attr("class", replacements.join(" "));
}
function markMatch(text, term, markup, escapeMarkup) {
var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
tl=term.length;
if (match<0) {
markup.push(escapeMarkup(text));
return;
}
markup.push(escapeMarkup(text.substring(0, match)));
markup.push("<span class='select2-match'>");
markup.push(escapeMarkup(text.substring(match, match + tl)));
markup.push("</span>");
markup.push(escapeMarkup(text.substring(match + tl, text.length)));
}
function defaultEscapeMarkup(markup) {
var replace_map = {
'\\': '\',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/'
};
return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
return replace_map[match];
});
}
/**
* Produces an ajax-based query function
*
* @param options object containing configuration paramters
* @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
* @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
* @param options.url url for the data
* @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
* @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
* @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
* @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
*/
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler) { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
// TODO - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
/**
* Produces a query function that works with a local array
*
* @param options object containing configuration parameters. The options parameter can either be an array or an
* object.
*
* If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
*
* If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
* an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
* key can either be a String in which case it is expected that each element in the 'data' array has a key with the
* value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
* the text.
*/
function local(options) {
var data = options, // data elements
dataText,
tmp,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if ($.isArray(data)) {
tmp = data;
data = { results: tmp };
}
if ($.isFunction(data) === false) {
tmp = data;
data = function() { return tmp; };
}
var dataItem = data();
if (dataItem.text) {
text = dataItem.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback(data());
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length || query.matcher(t, text(group), datum)) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum), datum)) {
collection.push(datum);
}
}
};
$(data().results).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
}
// TODO javadoc
function tags(data) {
var isFunc = $.isFunction(data);
return function (query) {
var t = query.term, filtered = {results: []};
$(isFunc ? data() : data).each(function () {
var isObject = this.text !== undefined,
text = isObject ? this.text : this;
if (t === "" || query.matcher(t, text)) {
filtered.results.push(isObject ? this : {id: this, text: this});
}
});
query.callback(filtered);
};
}
/**
* Checks if the formatter function should be used.
*
* Throws an error if it is not a function. Returns true if it should be used,
* false if no formatting should be performed.
*
* @param formatter
*/
function checkFormatter(formatter, formatterName) {
if ($.isFunction(formatter)) return true;
if (!formatter) return false;
throw new Error(formatterName +" must be a function or a falsy value");
}
function evaluate(val) {
return $.isFunction(val) ? val() : val;
}
function countResults(results) {
var count = 0;
$.each(results, function(i, item) {
if (item.children) {
count += countResults(item.children);
} else {
count++;
}
});
return count;
}
/**
* Default tokenizer. This function uses breaks the input on substring match of any string from the
* opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
* two options have to be defined in order for the tokenizer to work.
*
* @param input text user has typed so far or pasted into the search field
* @param selection currently selected choices
* @param selectCallback function(choice) callback tho add the choice to selection
* @param opts select2's opts
* @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
*/
function defaultTokenizer(input, selection, selectCallback, opts) {
var original = input, // store the original so we can compare and know if we need to tell the search to update its text
dupe = false, // check for whether a token we extracted represents a duplicate selected choice
token, // token
index, // position at which the separator was found
i, l, // looping variables
separator; // the matched separator
if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
while (true) {
index = -1;
for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
separator = opts.tokenSeparators[i];
index = input.indexOf(separator);
if (index >= 0) break;
}
if (index < 0) break; // did not find any token separator in the input string, bail
token = input.substring(0, index);
input = input.substring(index + separator.length);
if (token.length > 0) {
token = opts.createSearchChoice.call(this, token, selection);
if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
dupe = false;
for (i = 0, l = selection.length; i < l; i++) {
if (equal(opts.id(token), opts.id(selection[i]))) {
dupe = true; break;
}
}
if (!dupe) selectCallback(token);
}
}
}
if (original!==input) return input;
}
/**
* Creates a new class
*
* @param superClass
* @param methods
*/
function clazz(SuperClass, methods) {
var constructor = function () {};
constructor.prototype = new SuperClass;
constructor.prototype.constructor = constructor;
constructor.prototype.parent = SuperClass.prototype;
constructor.prototype = $.extend(constructor.prototype, methods);
return constructor;
}
AbstractSelect2 = clazz(Object, {
// abstract
bind: function (func) {
var self = this;
return function () {
func.apply(self, arguments);
};
},
// abstract
init: function (opts) {
var results, search, resultsSelector = ".select2-results";
// prepare options
this.opts = opts = this.prepareOpts(opts);
this.id=opts.id;
// destroy if called on an existing component
if (opts.element.data("select2") !== undefined &&
opts.element.data("select2") !== null) {
opts.element.data("select2").destroy();
}
this.container = this.createContainer();
this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
this.container.attr("id", this.containerId);
// cache the body so future lookups are cheap
this.body = thunk(function() { return opts.element.closest("body"); });
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.attr("style", opts.element.attr("style"));
this.container.css(evaluate(opts.containerCss));
this.container.addClass(evaluate(opts.containerCssClass));
this.elementTabIndex = this.opts.element.attr("tabindex");
// swap container for the element
this.opts.element
.data("select2", this)
.attr("tabindex", "-1")
.before(this.container)
.on("click.select2", killEvent); // do not leak click events
this.container.data("select2", this);
this.dropdown = this.container.find(".select2-drop");
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(opts.dropdownCssClass));
this.dropdown.data("select2", this);
this.dropdown.on("click", killEvent);
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
this.queryCount = 0;
this.resultsPage = 0;
this.context = null;
// initialize the container
this.initContainer();
this.container.on("click", killEvent);
installFilteredMouseMove(this.results);
this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
installDebouncedScroll(80, this.results);
this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
// do not propagate change event from the search field out of the component
$(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
$(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
// if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
if ($.fn.mousewheel) {
results.mousewheel(function (e, delta, deltaX, deltaY) {
var top = results.scrollTop();
if (deltaY > 0 && top - deltaY <= 0) {
results.scrollTop(0);
killEvent(e);
} else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
results.scrollTop(results.get(0).scrollHeight - results.height());
killEvent(e);
}
});
}
installKeyUpChangeEvent(search);
search.on("keyup-change input paste", this.bind(this.updateResults));
search.on("focus", function () { search.addClass("select2-focused"); });
search.on("blur", function () { search.removeClass("select2-focused");});
this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
if ($(e.target).closest(".select2-result-selectable").length > 0) {
this.highlightUnderEvent(e);
this.selectHighlighted(e);
}
}));
// trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
// for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
// dom it will trigger the popup close, which is not what we want
this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
if ($.isFunction(this.opts.initSelection)) {
// initialize selection based on the current value of the source element
this.initSelection();
// if the user has provided a function that can set selection based on the value of the source element
// we monitor the change event on the element and trigger it, allowing for two way synchronization
this.monitorSource();
}
if (opts.maximumInputLength !== null) {
this.search.attr("maxlength", opts.maximumInputLength);
}
var disabled = opts.element.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = opts.element.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
// Calculate size of scrollbar
scrollBarDimensions = scrollBarDimensions || measureScrollbar();
this.autofocus = opts.element.prop("autofocus");
opts.element.prop("autofocus", false);
if (this.autofocus) this.focus();
this.nextSearchTerm = undefined;
},
// abstract
destroy: function () {
var element=this.opts.element, select2 = element.data("select2");
this.close();
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
if (select2 !== undefined) {
select2.container.remove();
select2.dropdown.remove();
element
.removeClass("select2-offscreen")
.removeData("select2")
.off(".select2")
.prop("autofocus", this.autofocus || false);
if (this.elementTabIndex) {
element.attr({tabindex: this.elementTabIndex});
} else {
element.removeAttr("tabindex");
}
element.show();
}
},
// abstract
optionToData: function(element) {
if (element.is("option")) {
return {
id:element.prop("value"),
text:element.text(),
element: element.get(),
css: element.attr("class"),
disabled: element.prop("disabled"),
locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
};
} else if (element.is("optgroup")) {
return {
text:element.attr("label"),
children:[],
element: element.get(),
css: element.attr("class")
};
}
},
// abstract
prepareOpts: function (opts) {
var element, select, idKey, ajaxUrl, self = this;
element = opts.element;
if (element.get(0).tagName.toLowerCase() === "select") {
this.select = select = opts.element;
}
if (select) {
// these options are not allowed when attached to a select because they are picked up off the element itself
$.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
if (this in opts) {
throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
}
});
}
opts = $.extend({}, {
populateResults: function(container, results, query) {
var populate, id=this.opts.id;
populate=function(results, container, depth) {
var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
results = opts.sortResults(results, container, query);
for (i = 0, l = results.length; i < l; i = i + 1) {
result=results[i];
disabled = (result.disabled === true);
selectable = (!disabled) && (id(result) !== undefined);
compound=result.children && result.children.length > 0;
node=$("<li></li>");
node.addClass("select2-results-dept-"+depth);
node.addClass("select2-result");
node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
if (disabled) { node.addClass("select2-disabled"); }
if (compound) { node.addClass("select2-result-with-children"); }
node.addClass(self.opts.formatResultCssClass(result));
label=$(document.createElement("div"));
label.addClass("select2-result-label");
formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
if (formatted!==undefined) {
label.html(formatted);
}
node.append(label);
if (compound) {
innerContainer=$("<ul></ul>");
innerContainer.addClass("select2-result-sub");
populate(result.children, innerContainer, depth+1);
node.append(innerContainer);
}
node.data("select2-data", result);
container.append(node);
}
};
populate(results, container, 0);
}
}, $.fn.select2.defaults, opts);
if (typeof(opts.id) !== "function") {
idKey = opts.id;
opts.id = function (e) { return e[idKey]; };
}
if ($.isArray(opts.element.data("select2Tags"))) {
if ("tags" in opts) {
throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
}
opts.tags=opts.element.data("select2Tags");
}
if (select) {
opts.query = this.bind(function (query) {
var data = { results: [], more: false },
term = query.term,
children, placeholderOption, process;
process=function(element, collection) {
var group;
if (element.is("option")) {
if (query.matcher(term, element.text(), element)) {
collection.push(self.optionToData(element));
}
} else if (element.is("optgroup")) {
group=self.optionToData(element);
element.children().each2(function(i, elm) { process(elm, group.children); });
if (group.children.length>0) {
collection.push(group);
}
}
};
children=element.children();
// ignore the placeholder option if there is one
if (this.getPlaceholder() !== undefined && children.length > 0) {
placeholderOption = this.getPlaceholderOption();
if (placeholderOption) {
children=children.not(placeholderOption);
}
}
children.each2(function(i, elm) { process(elm, data.results); });
query.callback(data);
});
// this is needed because inside val() we construct choices from options and there id is hardcoded
opts.id=function(e) { return e.id; };
opts.formatResultCssClass = function(data) { return data.css; };
} else {
if (!("query" in opts)) {
if ("ajax" in opts) {
ajaxUrl = opts.element.data("ajax-url");
if (ajaxUrl && ajaxUrl.length > 0) {
opts.ajax.url = ajaxUrl;
}
opts.query = ajax.call(opts.element, opts.ajax);
} else if ("data" in opts) {
opts.query = local(opts.data);
} else if ("tags" in opts) {
opts.query = tags(opts.tags);
if (opts.createSearchChoice === undefined) {
opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
}
if (opts.initSelection === undefined) {
opts.initSelection = function (element, callback) {
var data = [];
$(splitVal(element.val(), opts.separator)).each(function () {
var obj = { id: this, text: this },
tags = opts.tags;
if ($.isFunction(tags)) tags=tags();
$(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
data.push(obj);
});
callback(data);
};
}
}
}
}
if (typeof(opts.query) !== "function") {
throw "query function not defined for Select2 " + opts.element.attr("id");
}
return opts;
},
/**
* Monitor the original element for changes and update select2 accordingly
*/
// abstract
monitorSource: function () {
var el = this.opts.element, sync, observer;
el.on("change.select2", this.bind(function (e) {
if (this.opts.element.data("select2-change-triggered") !== true) {
this.initSelection();
}
}));
sync = this.bind(function () {
// sync enabled state
var disabled = el.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = el.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.addClass(evaluate(this.opts.containerCssClass));
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
});
// IE8-10
el.on("propertychange.select2", sync);
// hold onto a reference of the callback to work around a chromium bug
if (this.mutationCallback === undefined) {
this.mutationCallback = function (mutations) {
mutations.forEach(sync);
}
}
// safari, chrome, firefox, IE11
observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
if (observer !== undefined) {
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
this.propertyObserver = new observer(this.mutationCallback);
this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
}
},
// abstract
triggerSelect: function(data) {
var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
this.opts.element.trigger(evt);
return !evt.isDefaultPrevented();
},
/**
* Triggers the change event on the source element
*/
// abstract
triggerChange: function (details) {
details = details || {};
details= $.extend({}, details, { type: "change", val: this.val() });
// prevents recursive triggering
this.opts.element.data("select2-change-triggered", true);
this.opts.element.trigger(details);
this.opts.element.data("select2-change-triggered", false);
// some validation frameworks ignore the change event and listen instead to keyup, click for selects
// so here we trigger the click event manually
this.opts.element.click();
// ValidationEngine ignorea the change event and listens instead to blur
// so here we trigger the blur event manually if so desired
if (this.opts.blurOnChange)
this.opts.element.blur();
},
//abstract
isInterfaceEnabled: function()
{
return this.enabledInterface === true;
},
// abstract
enableInterface: function() {
var enabled = this._enabled && !this._readonly,
disabled = !enabled;
if (enabled === this.enabledInterface) return false;
this.container.toggleClass("select2-container-disabled", disabled);
this.close();
this.enabledInterface = enabled;
return true;
},
// abstract
enable: function(enabled) {
if (enabled === undefined) enabled = true;
if (this._enabled === enabled) return;
this._enabled = enabled;
this.opts.element.prop("disabled", !enabled);
this.enableInterface();
},
// abstract
disable: function() {
this.enable(false);
},
// abstract
readonly: function(enabled) {
if (enabled === undefined) enabled = false;
if (this._readonly === enabled) return false;
this._readonly = enabled;
this.opts.element.prop("readonly", enabled);
this.enableInterface();
return true;
},
// abstract
opened: function () {
return this.container.hasClass("select2-dropdown-open");
},
// abstract
positionDropdown: function() {
var $dropdown = this.dropdown,
offset = this.container.offset(),
height = this.container.outerHeight(false),
width = this.container.outerWidth(false),
dropHeight = $dropdown.outerHeight(false),
$window = $(window),
windowWidth = $window.width(),
windowHeight = $window.height(),
viewPortRight = $window.scrollLeft() + windowWidth,
viewportBottom = $window.scrollTop() + windowHeight,
dropTop = offset.top + height,
dropLeft = offset.left,
enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
dropWidth = $dropdown.outerWidth(false),
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
aboveNow = $dropdown.hasClass("select2-drop-above"),
bodyOffset,
above,
changeDirection,
css,
resultsListNode;
// always prefer the current above/below alignment, unless there is not enough room
if (aboveNow) {
above = true;
if (!enoughRoomAbove && enoughRoomBelow) {
changeDirection = true;
above = false;
}
} else {
above = false;
if (!enoughRoomBelow && enoughRoomAbove) {
changeDirection = true;
above = true;
}
}
//if we are changing direction we need to get positions when dropdown is hidden;
if (changeDirection) {
$dropdown.hide();
offset = this.container.offset();
height = this.container.outerHeight(false);
width = this.container.outerWidth(false);
dropHeight = $dropdown.outerHeight(false);
viewPortRight = $window.scrollLeft() + windowWidth;
viewportBottom = $window.scrollTop() + windowHeight;
dropTop = offset.top + height;
dropLeft = offset.left;
dropWidth = $dropdown.outerWidth(false);
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
$dropdown.show();
}
if (this.opts.dropdownAutoWidth) {
resultsListNode = $('.select2-results', $dropdown)[0];
$dropdown.addClass('select2-drop-auto-width');
$dropdown.css('width', '');
// Add scrollbar width to dropdown if vertical scrollbar is present
dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
dropWidth > width ? width = dropWidth : dropWidth = width;
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
}
else {
this.container.removeClass('select2-drop-auto-width');
}
//console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
//console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
// fix positioning when body has an offset and is not position: static
if (this.body().css('position') !== 'static') {
bodyOffset = this.body().offset();
dropTop -= bodyOffset.top;
dropLeft -= bodyOffset.left;
}
if (!enoughRoomOnRight) {
dropLeft = offset.left + width - dropWidth;
}
css = {
left: dropLeft,
width: width
};
if (above) {
css.bottom = windowHeight - offset.top;
css.top = 'auto';
this.container.addClass("select2-drop-above");
$dropdown.addClass("select2-drop-above");
}
else {
css.top = dropTop;
css.bottom = 'auto';
this.container.removeClass("select2-drop-above");
$dropdown.removeClass("select2-drop-above");
}
css = $.extend(css, evaluate(this.opts.dropdownCss));
$dropdown.css(css);
},
// abstract
shouldOpen: function() {
var event;
if (this.opened()) return false;
if (this._enabled === false || this._readonly === true) return false;
event = $.Event("select2-opening");
this.opts.element.trigger(event);
return !event.isDefaultPrevented();
},
// abstract
clearDropdownAlignmentPreference: function() {
// clear the classes used to figure out the preference of where the dropdown should be opened
this.container.removeClass("select2-drop-above");
this.dropdown.removeClass("select2-drop-above");
},
/**
* Opens the dropdown
*
* @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
* the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
*/
// abstract
open: function () {
if (!this.shouldOpen()) return false;
this.opening();
return true;
},
/**
* Performs the opening of the dropdown
*/
// abstract
opening: function() {
var cid = this.containerId,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid,
mask;
this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
this.clearDropdownAlignmentPreference();
if(this.dropdown[0] !== this.body().children().last()[0]) {
this.dropdown.detach().appendTo(this.body());
}
// create the dropdown mask if doesnt already exist
mask = $("#select2-drop-mask");
if (mask.length == 0) {
mask = $(document.createElement("div"));
mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
mask.hide();
mask.appendTo(this.body());
mask.on("mousedown touchstart click", function (e) {
var dropdown = $("#select2-drop"), self;
if (dropdown.length > 0) {
self=dropdown.data("select2");
if (self.opts.selectOnBlur) {
self.selectHighlighted({noFocus: true});
}
self.close({focus:true});
e.preventDefault();
e.stopPropagation();
}
});
}
// ensure the mask is always right before the dropdown
if (this.dropdown.prev()[0] !== mask[0]) {
this.dropdown.before(mask);
}
// move the global id to the correct dropdown
$("#select2-drop").removeAttr("id");
this.dropdown.attr("id", "select2-drop");
// show the elements
mask.show();
this.positionDropdown();
this.dropdown.show();
this.positionDropdown();
this.dropdown.addClass("select2-drop-active");
// attach listeners to events that can change the position of the container and thus require
// the position of the dropdown to be updated as well so it does not come unglued from the container
var that = this;
this.container.parents().add(window).each(function () {
$(this).on(resize+" "+scroll+" "+orient, function (e) {
that.positionDropdown();
});
});
},
// abstract
close: function () {
if (!this.opened()) return;
var cid = this.containerId,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid;
// unbind event listeners
this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
this.clearDropdownAlignmentPreference();
$("#select2-drop-mask").hide();
this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
this.dropdown.hide();
this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
this.results.empty();
this.clearSearch();
this.search.removeClass("select2-active");
this.opts.element.trigger($.Event("select2-close"));
},
/**
* Opens control, sets input value, and updates results.
*/
// abstract
externalSearch: function (term) {
this.open();
this.search.val(term);
this.updateResults(false);
},
// abstract
clearSearch: function () {
},
//abstract
getMaximumSelectionSize: function() {
return evaluate(this.opts.maximumSelectionSize);
},
// abstract
ensureHighlightVisible: function () {
var results = this.results, children, index, child, hb, rb, y, more;
index = this.highlight();
if (index < 0) return;
if (index == 0) {
// if the first element is highlighted scroll all the way to the top,
// that way any unselectable headers above it will also be scrolled
// into view
results.scrollTop(0);
return;
}
children = this.findHighlightableChoices().find('.select2-result-label');
child = $(children[index]);
hb = child.offset().top + child.outerHeight(true);
// if this is the last child lets also make sure select2-more-results is visible
if (index === children.length - 1) {
more = results.find("li.select2-more-results");
if (more.length > 0) {
hb = more.offset().top + more.outerHeight(true);
}
}
rb = results.offset().top + results.outerHeight(true);
if (hb > rb) {
results.scrollTop(results.scrollTop() + (hb - rb));
}
y = child.offset().top - results.offset().top;
// make sure the top of the element is visible
if (y < 0 && child.css('display') != 'none' ) {
results.scrollTop(results.scrollTop() + y); // y is negative
}
},
// abstract
findHighlightableChoices: function() {
return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)");
},
// abstract
moveHighlight: function (delta) {
var choices = this.findHighlightableChoices(),
index = this.highlight();
while (index > -1 && index < choices.length) {
index += delta;
var choice = $(choices[index]);
if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
this.highlight(index);
break;
}
}
},
// abstract
highlight: function (index) {
var choices = this.findHighlightableChoices(),
choice,
data;
if (arguments.length === 0) {
return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
}
if (index >= choices.length) index = choices.length - 1;
if (index < 0) index = 0;
this.removeHighlight();
choice = $(choices[index]);
choice.addClass("select2-highlighted");
this.ensureHighlightVisible();
data = choice.data("select2-data");
if (data) {
this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
}
},
removeHighlight: function() {
this.results.find(".select2-highlighted").removeClass("select2-highlighted");
},
// abstract
countSelectableResults: function() {
return this.findHighlightableChoices().length;
},
// abstract
highlightUnderEvent: function (event) {
var el = $(event.target).closest(".select2-result-selectable");
if (el.length > 0 && !el.is(".select2-highlighted")) {
var choices = this.findHighlightableChoices();
this.highlight(choices.index(el));
} else if (el.length == 0) {
// if we are over an unselectable item remove all highlights
this.removeHighlight();
}
},
// abstract
loadMoreIfNeeded: function () {
var results = this.results,
more = results.find("li.select2-more-results"),
below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
page = this.resultsPage + 1,
self=this,
term=this.search.val(),
context=this.context;
if (more.length === 0) return;
below = more.offset().top - results.offset().top - results.height();
if (below <= this.opts.loadMorePadding) {
more.addClass("select2-active");
this.opts.query({
element: this.opts.element,
term: term,
page: page,
context: context,
matcher: this.opts.matcher,
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
self.postprocessResults(data, false, false);
if (data.more===true) {
more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
self.context = data.context;
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
}
},
/**
* Default tokenizer function which does nothing
*/
tokenize: function() {
},
/**
* @param initial whether or not this is the call to this method right after the dropdown has been opened
*/
// abstract
updateResults: function (initial) {
var search = this.search,
results = this.results,
opts = this.opts,
data,
self = this,
input,
term = search.val(),
lastTerm = $.data(this.container, "select2-last-term"),
// sequence number used to drop out-of-order responses
queryNumber;
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;
$.data(this.container, "select2-last-term", term);
// if the search is currently hidden we do not alter the results
if (initial !== true && (this.showSearchInput === false || !this.opened())) {
return;
}
function postRender() {
search.removeClass("select2-active");
self.positionDropdown();
}
function render(html) {
results.html(html);
postRender();
}
queryNumber = ++this.queryCount;
var maxSelSize = this.getMaximumSelectionSize();
if (maxSelSize >=1) {
data = this.data();
if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
return;
}
}
if (search.val().length < opts.minimumInputLength) {
if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
} else {
render("");
}
if (initial && this.showSearch) this.showSearch(true);
return;
}
if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
} else {
render("");
}
return;
}
if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
}
search.addClass("select2-active");
this.removeHighlight();
// give the tokenizer a chance to pre-process the input
input = this.tokenize();
if (input != undefined && input != null) {
search.val(input);
}
this.resultsPage = 1;
opts.query({
element: opts.element,
term: search.val(),
page: this.resultsPage,
context: null,
matcher: opts.matcher,
callback: this.bind(function (data) {
var def; // default choice
// ignore old responses
if (queryNumber != this.queryCount) {
return;
}
// ignore a response if the select2 has been closed before it was received
if (!this.opened()) {
this.search.removeClass("select2-active");
return;
}
// save context, if any
this.context = (data.context===undefined) ? null : data.context;
// create a default choice and prepend it to the list
if (this.opts.createSearchChoice && search.val() !== "") {
def = this.opts.createSearchChoice.call(self, search.val(), data.results);
if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
if ($(data.results).filter(
function () {
return equal(self.id(this), self.id(def));
}).length === 0) {
data.results.unshift(def);
}
}
}
if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
return;
}
results.empty();
self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
}
this.postprocessResults(data, initial);
postRender();
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
},
// abstract
cancel: function () {
this.close();
},
// abstract
blur: function () {
// if selectOnBlur == true, select the currently highlighted option
if (this.opts.selectOnBlur)
this.selectHighlighted({noFocus: true});
this.close();
this.container.removeClass("select2-container-active");
// synonymous to .is(':focus'), which is available in jquery >= 1.6
if (this.search[0] === document.activeElement) { this.search.blur(); }
this.clearSearch();
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
},
// abstract
focusSearch: function () {
focus(this.search);
},
// abstract
selectHighlighted: function (options) {
var index=this.highlight(),
highlighted=this.results.find(".select2-highlighted"),
data = highlighted.closest('.select2-result').data("select2-data");
if (data) {
this.highlight(index);
this.onSelect(data, options);
} else if (options && options.noFocus) {
this.close();
}
},
// abstract
getPlaceholder: function () {
var placeholderOption;
return this.opts.element.attr("placeholder") ||
this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
this.opts.element.data("placeholder") ||
this.opts.placeholder ||
((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
},
// abstract
getPlaceholderOption: function() {
if (this.select) {
var firstOption = this.select.children('option').first();
if (this.opts.placeholderOption !== undefined ) {
//Determine the placeholder option based on the specified placeholderOption setting
return (this.opts.placeholderOption === "first" && firstOption) ||
(typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
} else if (firstOption.text() === "" && firstOption.val() === "") {
//No explicit placeholder option specified, use the first if it's blank
return firstOption;
}
}
},
/**
* Get the desired width for the container element. This is
* derived first from option `width` passed to select2, then
* the inline 'style' on the original element, and finally
* falls back to the jQuery calculated element width.
*/
// abstract
initContainerWidth: function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l, attr;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
attr = attrs[i].replace(/\s/g, '');
matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.css("width", width);
}
}
});
SingleSelect2 = clazz(AbstractSelect2, {
// single
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container"
}).html([
"<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
" <span class='select2-chosen'> </span><abbr class='select2-search-choice-close'></abbr>",
" <span class='select2-arrow'><b></b></span>",
"</a>",
"<input class='select2-focusser select2-offscreen' type='text'/>",
"<div class='select2-drop select2-display-none'>",
" <div class='select2-search'>",
" <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>",
" </div>",
" <ul class='select2-results'>",
" </ul>",
"</div>"].join(""));
return container;
},
// single
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.focusser.prop("disabled", !this.isInterfaceEnabled());
}
},
// single
opening: function () {
var el, range, len;
if (this.opts.minimumResultsForSearch >= 0) {
this.showSearch(true);
}
this.parent.opening.apply(this, arguments);
if (this.showSearchInput !== false) {
// IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
// all other browsers handle this just fine
this.search.val(this.focusser.val());
}
this.search.focus();
// move the cursor to the end after focussing, otherwise it will be at the beginning and
// new text will appear *before* focusser.val()
el = this.search.get(0);
if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
} else if (el.setSelectionRange) {
len = this.search.val().length;
el.setSelectionRange(len, len);
}
// initializes search's value with nextSearchTerm (if defined by user)
// ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
if(this.search.val() === "") {
if(this.nextSearchTerm != undefined){
this.search.val(this.nextSearchTerm);
this.search.select();
}
}
this.focusser.prop("disabled", true).val("");
this.updateResults(true);
this.opts.element.trigger($.Event("select2-open"));
},
// single
close: function (params) {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
params = params || {focus: true};
this.focusser.removeAttr("disabled");
if (params.focus) {
this.focusser.focus();
}
},
// single
focus: function () {
if (this.opened()) {
this.close();
} else {
this.focusser.removeAttr("disabled");
this.focusser.focus();
}
},
// single
isFocused: function () {
return this.container.hasClass("select2-container-active");
},
// single
cancel: function () {
this.parent.cancel.apply(this, arguments);
this.focusser.removeAttr("disabled");
this.focusser.focus();
},
// single
destroy: function() {
$("label[for='" + this.focusser.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
},
// single
initContainer: function () {
var selection,
container = this.container,
dropdown = this.dropdown;
if (this.opts.minimumResultsForSearch < 0) {
this.showSearch(false);
} else {
this.showSearch(true);
}
this.selection = selection = container.find(".select2-choice");
this.focusser = container.find(".select2-focusser");
// rewrite labels from original element to focusser
this.focusser.attr("id", "s2id_autogen"+nextUid());
$("label[for='" + this.opts.element.attr("id") + "']")
.attr('for', this.focusser.attr('id'));
this.focusser.attr("tabindex", this.elementTabIndex);
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
return;
}
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus: true});
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}));
this.search.on("blur", this.bind(function(e) {
// a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
// without this the search field loses focus which is annoying
if (document.activeElement === this.body().get(0)) {
window.setTimeout(this.bind(function() {
this.search.focus();
}), 0);
}
}));
this.focusser.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
killEvent(e);
return;
}
if (e.which == KEY.DOWN || e.which == KEY.UP
|| (e.which == KEY.ENTER && this.opts.openOnEnter)) {
if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
this.open();
killEvent(e);
return;
}
if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
if (this.opts.allowClear) {
this.clear();
}
killEvent(e);
return;
}
}));
installKeyUpChangeEvent(this.focusser);
this.focusser.on("keyup-change input", this.bind(function(e) {
if (this.opts.minimumResultsForSearch >= 0) {
e.stopPropagation();
if (this.opened()) return;
this.open();
}
}));
selection.on("mousedown", "abbr", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
this.clear();
killEventImmediately(e);
this.close();
this.selection.focus();
}));
selection.on("mousedown", this.bind(function (e) {
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
if (this.opened()) {
this.close();
} else if (this.isInterfaceEnabled()) {
this.open();
}
killEvent(e);
}));
dropdown.on("mousedown", this.bind(function() { this.search.focus(); }));
selection.on("focus", this.bind(function(e) {
killEvent(e);
}));
this.focusser.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
})).on("blur", this.bind(function() {
if (!this.opened()) {
this.container.removeClass("select2-container-active");
this.opts.element.trigger($.Event("select2-blur"));
}
}));
this.search.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
this.setPlaceholder();
},
// single
clear: function(triggerChange) {
var data=this.selection.data("select2-data");
if (data) { // guard against queued quick consecutive clicks
var evt = $.Event("select2-clearing");
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return;
}
var placeholderOption = this.getPlaceholderOption();
this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
this.selection.find(".select2-chosen").empty();
this.selection.removeData("select2-data");
this.setPlaceholder();
if (triggerChange !== false){
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({removed:data});
}
}
},
/**
* Sets selection based on source element's value
*/
// single
initSelection: function () {
var selected;
if (this.isPlaceholderOptionSelected()) {
this.updateSelection(null);
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
},
isPlaceholderOptionSelected: function() {
var placeholderOption;
if (!this.getPlaceholder()) return false; // no placeholder specified so no option should be considered
return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
|| (this.opts.element.val() === "")
|| (this.opts.element.val() === undefined)
|| (this.opts.element.val() === null);
},
// single
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install the selection initializer
opts.initSelection = function (element, callback) {
var selected = element.find("option").filter(function() { return this.selected });
// a single select box always has a value, no need to null check 'selected'
callback(self.optionToData(selected));
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var id = element.val();
//search in data by id, storing the actual matching item
var match = null;
opts.query({
matcher: function(term, text, el){
var is_match = equal(id, opts.id(el));
if (is_match) {
match = el;
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
callback(match);
}
});
};
}
return opts;
},
// single
getPlaceholder: function() {
// if a placeholder is specified on a single select without a valid placeholder option ignore it
if (this.select) {
if (this.getPlaceholderOption() === undefined) {
return undefined;
}
}
return this.parent.getPlaceholder.apply(this, arguments);
},
// single
setPlaceholder: function () {
var placeholder = this.getPlaceholder();
if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
// check for a placeholder option if attached to a select
if (this.select && this.getPlaceholderOption() === undefined) return;
this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
this.selection.addClass("select2-default");
this.container.removeClass("select2-allowclear");
}
},
// single
postprocessResults: function (data, initial, noHighlightUpdate) {
var selected = 0, self = this, showSearchInput = true;
// find the selected element in the result list
this.findHighlightableChoices().each2(function (i, elm) {
if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
selected = i;
return false;
}
});
// and highlight it
if (noHighlightUpdate !== false) {
if (initial === true && selected >= 0) {
this.highlight(selected);
} else {
this.highlight(0);
}
}
// hide the search box if this is the first we got the results and there are enough of them for search
if (initial === true) {
var min = this.opts.minimumResultsForSearch;
if (min >= 0) {
this.showSearch(countResults(data.results) >= min);
}
}
},
// single
showSearch: function(showSearchInput) {
if (this.showSearchInput === showSearchInput) return;
this.showSearchInput = showSearchInput;
this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
//add "select2-with-searchbox" to the container if search box is shown
$(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
},
// single
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
var old = this.opts.element.val(),
oldData = this.data();
this.opts.element.val(this.id(data));
this.updateSelection(data);
this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
this.close();
if (!options || !options.noFocus)
this.focusser.focus();
if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
},
// single
updateSelection: function (data) {
var container=this.selection.find(".select2-chosen"), formatted, cssClass;
this.selection.data("select2-data", data);
container.empty();
if (data !== null) {
formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
}
if (formatted !== undefined) {
container.append(formatted);
}
cssClass=this.opts.formatSelectionCssClass(data, container);
if (cssClass !== undefined) {
container.addClass(cssClass);
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.container.addClass("select2-allowclear");
}
},
// single
val: function () {
var val,
triggerChange = false,
data = null,
self = this,
oldData = this.data();
if (arguments.length === 0) {
return this.opts.element.val();
}
val = arguments[0];
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (this.select) {
this.select
.val(val)
.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
data = self.optionToData(elm);
return false;
});
this.updateSelection(data);
this.setPlaceholder();
if (triggerChange) {
this.triggerChange({added: data, removed:oldData});
}
} else {
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.clear(triggerChange);
return;
}
if (this.opts.initSelection === undefined) {
throw new Error("cannot call val() if initSelection() is not defined");
}
this.opts.element.val(val);
this.opts.initSelection(this.opts.element, function(data){
self.opts.element.val(!data ? "" : self.id(data));
self.updateSelection(data);
self.setPlaceholder();
if (triggerChange) {
self.triggerChange({added: data, removed:oldData});
}
});
}
},
// single
clearSearch: function () {
this.search.val("");
this.focusser.val("");
},
// single
data: function(value) {
var data,
triggerChange = false;
if (arguments.length === 0) {
data = this.selection.data("select2-data");
if (data == undefined) data = null;
return data;
} else {
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (!value) {
this.clear(triggerChange);
} else {
data = this.data();
this.opts.element.val(!value ? "" : this.id(value));
this.updateSelection(value);
if (triggerChange) {
this.triggerChange({added: value, removed:data});
}
}
}
}
});
MultiSelect2 = clazz(AbstractSelect2, {
// multi
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container select2-container-multi"
}).html([
"<ul class='select2-choices'>",
" <li class='select2-search-field'>",
" <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
" </li>",
"</ul>",
"<div class='select2-drop select2-drop-multi select2-display-none'>",
" <ul class='select2-results'>",
" </ul>",
"</div>"].join(""));
return container;
},
// multi
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
// TODO validate placeholder is a string if specified
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install sthe selection initializer
opts.initSelection = function (element, callback) {
var data = [];
element.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
data.push(self.optionToData(elm));
});
callback(data);
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var ids = splitVal(element.val(), opts.separator);
//search in data by array of ids, storing matching items in a list
var matches = [];
opts.query({
matcher: function(term, text, el){
var is_match = $.grep(ids, function(id) {
return equal(id, opts.id(el));
}).length;
if (is_match) {
matches.push(el);
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
// reorder matches based on the order they appear in the ids array because right now
// they are in the order in which they appear in data array
var ordered = [];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
for (var j = 0; j < matches.length; j++) {
var match = matches[j];
if (equal(id, opts.id(match))) {
ordered.push(match);
matches.splice(j, 1);
break;
}
}
}
callback(ordered);
}
});
};
}
return opts;
},
// multi
selectChoice: function (choice) {
var selected = this.container.find(".select2-search-choice-focus");
if (selected.length && choice && choice[0] == selected[0]) {
} else {
if (selected.length) {
this.opts.element.trigger("choice-deselected", selected);
}
selected.removeClass("select2-search-choice-focus");
if (choice && choice.length) {
this.close();
choice.addClass("select2-search-choice-focus");
this.opts.element.trigger("choice-selected", choice);
}
}
},
// multi
destroy: function() {
$("label[for='" + this.search.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
},
// multi
initContainer: function () {
var selector = ".select2-choices", selection;
this.searchContainer = this.container.find(".select2-search-field");
this.selection = selection = this.container.find(selector);
var _this = this;
this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
//killEvent(e);
_this.search[0].focus();
_this.selectChoice($(this));
});
// rewrite labels from original element to focusser
this.search.attr("id", "s2id_autogen"+nextUid());
$("label[for='" + this.opts.element.attr("id") + "']")
.attr('for', this.search.attr('id'));
this.search.on("input paste", this.bind(function() {
if (!this.isInterfaceEnabled()) return;
if (!this.opened()) {
this.open();
}
}));
this.search.attr("tabindex", this.elementTabIndex);
this.keydowns = 0;
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
++this.keydowns;
var selected = selection.find(".select2-search-choice-focus");
var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
var next = selected.next(".select2-search-choice:not(.select2-locked)");
var pos = getCursorInfo(this.search);
if (selected.length &&
(e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
var selectedChoice = selected;
if (e.which == KEY.LEFT && prev.length) {
selectedChoice = prev;
}
else if (e.which == KEY.RIGHT) {
selectedChoice = next.length ? next : null;
}
else if (e.which === KEY.BACKSPACE) {
this.unselect(selected.first());
this.search.width(10);
selectedChoice = prev.length ? prev : next;
} else if (e.which == KEY.DELETE) {
this.unselect(selected.first());
this.search.width(10);
selectedChoice = next.length ? next : null;
} else if (e.which == KEY.ENTER) {
selectedChoice = null;
}
this.selectChoice(selectedChoice);
killEvent(e);
if (!selectedChoice || !selectedChoice.length) {
this.open();
}
return;
} else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
|| e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
killEvent(e);
return;
} else {
this.selectChoice(null);
}
if (this.opened()) {
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus:true});
this.close();
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
|| e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
return;
}
if (e.which === KEY.ENTER) {
if (this.opts.openOnEnter === false) {
return;
} else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
return;
}
}
this.open();
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
}
if (e.which === KEY.ENTER) {
// prevent form from being submitted
killEvent(e);
}
}));
this.search.on("keyup", this.bind(function (e) {
this.keydowns = 0;
this.resizeSearch();
})
);
this.search.on("blur", this.bind(function(e) {
this.container.removeClass("select2-container-active");
this.search.removeClass("select2-focused");
this.selectChoice(null);
if (!this.opened()) this.clearSearch();
e.stopImmediatePropagation();
this.opts.element.trigger($.Event("select2-blur"));
}));
this.container.on("click", selector, this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if ($(e.target).closest(".select2-search-choice").length > 0) {
// clicked inside a select2 search choice, do not open
return;
}
this.selectChoice(null);
this.clearPlaceholder();
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.open();
this.focusSearch();
e.preventDefault();
}));
this.container.on("focus", selector, this.bind(function () {
if (!this.isInterfaceEnabled()) return;
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
this.clearPlaceholder();
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
// set the placeholder if necessary
this.clearSearch();
},
// multi
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.search.prop("disabled", !this.isInterfaceEnabled());
}
},
// multi
initSelection: function () {
var data;
if (this.opts.element.val() === "" && this.opts.element.text() === "") {
this.updateSelection([]);
this.close();
// set the placeholder if necessary
this.clearSearch();
}
if (this.select || this.opts.element.val() !== "") {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(data){
if (data !== undefined && data !== null) {
self.updateSelection(data);
self.close();
// set the placeholder if necessary
self.clearSearch();
}
});
}
},
// multi
clearSearch: function () {
var placeholder = this.getPlaceholder(),
maxWidth = this.getMaxSearchWidth();
if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
this.search.val(placeholder).addClass("select2-default");
// stretch the search box to full width of the container so as much of the placeholder is visible as possible
// we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
} else {
this.search.val("").width(10);
}
},
// multi
clearPlaceholder: function () {
if (this.search.hasClass("select2-default")) {
this.search.val("").removeClass("select2-default");
}
},
// multi
opening: function () {
this.clearPlaceholder(); // should be done before super so placeholder is not used to search
this.resizeSearch();
this.parent.opening.apply(this, arguments);
this.focusSearch();
this.updateResults(true);
this.search.focus();
this.opts.element.trigger($.Event("select2-open"));
},
// multi
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
},
// multi
focus: function () {
this.close();
this.search.focus();
},
// multi
isFocused: function () {
return this.search.hasClass("select2-focused");
},
// multi
updateSelection: function (data) {
var ids = [], filtered = [], self = this;
// filter out duplicates
$(data).each(function () {
if (indexOf(self.id(this), ids) < 0) {
ids.push(self.id(this));
filtered.push(this);
}
});
data = filtered;
this.selection.find(".select2-search-choice").remove();
$(data).each(function () {
self.addSelectedChoice(this);
});
self.postprocessResults();
},
// multi
tokenize: function() {
var input = this.search.val();
input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
if (input != null && input != undefined) {
this.search.val(input);
if (input.length > 0) {
this.open();
}
}
},
// multi
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
this.addSelectedChoice(data);
this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
if (this.opts.closeOnSelect) {
this.close();
this.search.width(10);
} else {
if (this.countSelectableResults()>0) {
this.search.width(10);
this.resizeSearch();
if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
// if we reached max selection size repaint the results so choices
// are replaced with the max selection reached message
this.updateResults(true);
}
this.positionDropdown();
} else {
// if nothing left to select close
this.close();
this.search.width(10);
}
}
// since its not possible to select an element that has already been
// added we do not need to check if this is a new element before firing change
this.triggerChange({ added: data });
if (!options || !options.noFocus)
this.focusSearch();
},
// multi
cancel: function () {
this.close();
this.focusSearch();
},
addSelectedChoice: function (data) {
var enableChoice = !data.locked,
enabledItem = $(
"<li class='select2-search-choice'>" +
" <div></div>" +
" <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
"</li>"),
disabledItem = $(
"<li class='select2-search-choice select2-locked'>" +
"<div></div>" +
"</li>");
var choice = enableChoice ? enabledItem : disabledItem,
id = this.id(data),
val = this.getVal(),
formatted,
cssClass;
formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
if (formatted != undefined) {
choice.find("div").replaceWith("<div>"+formatted+"</div>");
}
cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
if (cssClass != undefined) {
choice.addClass(cssClass);
}
if(enableChoice){
choice.find(".select2-search-choice-close")
.on("mousedown", killEvent)
.on("click dblclick", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
$(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
this.unselect($(e.target));
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
this.close();
this.focusSearch();
})).dequeue();
killEvent(e);
})).on("focus", this.bind(function () {
if (!this.isInterfaceEnabled()) return;
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
}));
}
choice.data("select2-data", data);
choice.insertBefore(this.searchContainer);
val.push(id);
this.setVal(val);
},
// multi
unselect: function (selected) {
var val = this.getVal(),
data,
index;
selected = selected.closest(".select2-search-choice");
if (selected.length === 0) {
throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
}
data = selected.data("select2-data");
if (!data) {
// prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
// and invoked on an element already removed
return;
}
while((index = indexOf(this.id(data), val)) >= 0) {
val.splice(index, 1);
this.setVal(val);
if (this.select) this.postprocessResults();
}
var evt = $.Event("select2-removing");
evt.val = this.id(data);
evt.choice = data;
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return;
}
selected.remove();
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({ removed: data });
},
// multi
postprocessResults: function (data, initial, noHighlightUpdate) {
var val = this.getVal(),
choices = this.results.find(".select2-result"),
compound = this.results.find(".select2-result-with-children"),
self = this;
choices.each2(function (i, choice) {
var id = self.id(choice.data("select2-data"));
if (indexOf(id, val) >= 0) {
choice.addClass("select2-selected");
// mark all children of the selected parent as selected
choice.find(".select2-result-selectable").addClass("select2-selected");
}
});
compound.each2(function(i, choice) {
// hide an optgroup if it doesnt have any selectable children
if (!choice.is('.select2-result-selectable')
&& choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
choice.addClass("select2-selected");
}
});
if (this.highlight() == -1 && noHighlightUpdate !== false){
self.highlight(0);
}
//If all results are chosen render formatNoMAtches
if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
}
}
}
},
// multi
getMaxSearchWidth: function() {
return this.selection.width() - getSideBorderPadding(this.search);
},
// multi
resizeSearch: function () {
var minimumWidth, left, maxWidth, containerLeft, searchWidth,
sideBorderPadding = getSideBorderPadding(this.search);
minimumWidth = measureTextWidth(this.search) + 10;
left = this.search.offset().left;
maxWidth = this.selection.width();
containerLeft = this.selection.offset().left;
searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
if (searchWidth < minimumWidth) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth < 40) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth <= 0) {
searchWidth = minimumWidth;
}
this.search.width(Math.floor(searchWidth));
},
// multi
getVal: function () {
var val;
if (this.select) {
val = this.select.val();
return val === null ? [] : val;
} else {
val = this.opts.element.val();
return splitVal(val, this.opts.separator);
}
},
// multi
setVal: function (val) {
var unique;
if (this.select) {
this.select.val(val);
} else {
unique = [];
// filter out duplicates
$(val).each(function () {
if (indexOf(this, unique) < 0) unique.push(this);
});
this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
}
},
// multi
buildChangeDetails: function (old, current) {
var current = current.slice(0),
old = old.slice(0);
// remove intersection from each array
for (var i = 0; i < current.length; i++) {
for (var j = 0; j < old.length; j++) {
if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
current.splice(i, 1);
if(i>0){
i--;
}
old.splice(j, 1);
j--;
}
}
}
return {added: current, removed: old};
},
// multi
val: function (val, triggerChange) {
var oldData, self=this;
if (arguments.length === 0) {
return this.getVal();
}
oldData=this.data();
if (!oldData.length) oldData=[];
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.opts.element.val("");
this.updateSelection([]);
this.clearSearch();
if (triggerChange) {
this.triggerChange({added: this.data(), removed: oldData});
}
return;
}
// val is a list of ids
this.setVal(val);
if (this.select) {
this.opts.initSelection(this.select, this.bind(this.updateSelection));
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(oldData, this.data()));
}
} else {
if (this.opts.initSelection === undefined) {
throw new Error("val() cannot be called if initSelection() is not defined");
}
this.opts.initSelection(this.opts.element, function(data){
var ids=$.map(data, self.id);
self.setVal(ids);
self.updateSelection(data);
self.clearSearch();
if (triggerChange) {
self.triggerChange(self.buildChangeDetails(oldData, self.data()));
}
});
}
this.clearSearch();
},
// multi
onSortStart: function() {
if (this.select) {
throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
}
// collapse search field into 0 width so its container can be collapsed as well
this.search.width(0);
// hide the container
this.searchContainer.hide();
},
// multi
onSortEnd:function() {
var val=[], self=this;
// show search and move it to the end of the list
this.searchContainer.show();
// make sure the search container is the last item in the list
this.searchContainer.appendTo(this.searchContainer.parent());
// since we collapsed the width in dragStarted, we resize it here
this.resizeSearch();
// update selection
this.selection.find(".select2-search-choice").each(function() {
val.push(self.opts.id($(this).data("select2-data")));
});
this.setVal(val);
this.triggerChange();
},
// multi
data: function(values, triggerChange) {
var self=this, ids, old;
if (arguments.length === 0) {
return this.selection
.find(".select2-search-choice")
.map(function() { return $(this).data("select2-data"); })
.get();
} else {
old = this.data();
if (!values) { values = []; }
ids = $.map(values, function(e) { return self.opts.id(e); });
this.setVal(ids);
this.updateSelection(values);
this.clearSearch();
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(old, this.data()));
}
}
}
});
$.fn.select2 = function () {
var args = Array.prototype.slice.call(arguments, 0),
opts,
select2,
method, value, multiple,
allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
valueMethods = ["opened", "isFocused", "container", "dropdown"],
propertyMethods = ["val", "data"],
methodsMap = { search: "externalSearch" };
this.each(function () {
if (args.length === 0 || typeof(args[0]) === "object") {
opts = args.length === 0 ? {} : $.extend({}, args[0]);
opts.element = $(this);
if (opts.element.get(0).tagName.toLowerCase() === "select") {
multiple = opts.element.prop("multiple");
} else {
multiple = opts.multiple || false;
if ("tags" in opts) {opts.multiple = multiple = true;}
}
select2 = multiple ? new MultiSelect2() : new SingleSelect2();
select2.init(opts);
} else if (typeof(args[0]) === "string") {
if (indexOf(args[0], allowedMethods) < 0) {
throw "Unknown method: " + args[0];
}
value = undefined;
select2 = $(this).data("select2");
if (select2 === undefined) return;
method=args[0];
if (method === "container") {
value = select2.container;
} else if (method === "dropdown") {
value = select2.dropdown;
} else {
if (methodsMap[method]) method = methodsMap[method];
value = select2[method].apply(select2, args.slice(1));
}
if (indexOf(args[0], valueMethods) >= 0
|| (indexOf(args[0], propertyMethods) && args.length == 1)) {
return false; // abort the iteration, ready to return first matched value
}
} else {
throw "Invalid arguments to select2 plugin: " + args;
}
});
return (value === undefined) ? this : value;
};
// plugin defaults, accessible to users
$.fn.select2.defaults = {
width: "copy",
loadMorePadding: 0,
closeOnSelect: true,
openOnEnter: true,
containerCss: {},
dropdownCss: {},
containerCssClass: "",
dropdownCssClass: "",
formatResult: function(result, container, query, escapeMarkup) {
var markup=[];
markMatch(result.text, query.term, markup, escapeMarkup);
return markup.join("");
},
formatSelection: function (data, container, escapeMarkup) {
return data ? escapeMarkup(data.text) : undefined;
},
sortResults: function (results, container, query) {
return results;
},
formatResultCssClass: function(data) {return undefined;},
formatSelectionCssClass: function(data, container) {return undefined;},
formatNoMatches: function () { return "No matches found"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Loading more results..."; },
formatSearching: function () { return "Searching..."; },
minimumResultsForSearch: 0,
minimumInputLength: 0,
maximumInputLength: null,
maximumSelectionSize: 0,
id: function (e) { return e.id; },
matcher: function(term, text) {
return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
},
separator: ",",
tokenSeparators: [],
tokenizer: defaultTokenizer,
escapeMarkup: defaultEscapeMarkup,
blurOnChange: false,
selectOnBlur: false,
adaptContainerCssClass: function(c) { return c; },
adaptDropdownCssClass: function(c) { return null; },
nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }
};
$.fn.select2.ajaxDefaults = {
transport: $.ajax,
params: {
type: "GET",
cache: false,
dataType: "json"
}
};
// exports
window.Select2 = {
query: {
ajax: ajax,
local: local,
tags: tags
}, util: {
debounce: debounce,
markMatch: markMatch,
escapeMarkup: defaultEscapeMarkup,
stripDiacritics: stripDiacritics
}, "class": {
"abstract": AbstractSelect2,
"single": SingleSelect2,
"multi": MultiSelect2
}
};
}(jQuery));
return module.exports;
}).call(this);
// src/js/aui/select2.js
(typeof window === 'undefined' ? global : window).__dfd5f5c723e08e5f95e38718fe4f73eb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__b2190710f2822b5d7286528d3eaff37f;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Wraps a vanilla Select2 with ADG _style_, as an auiSelect2 method on jQuery objects.
*
* @since 5.2
*/
/**
* We make a copy of the original select2 so that later we might re-specify $.fn.auiSelect2 as $.fn.select2. That
* way, calling code will be able to call $thing.select2() as if they were calling the original library,
* and ADG styling will just magically happen.
*/
var originalSelect2 = _jquery2.default.fn.select2;
// AUI-specific classes
var auiContainer = 'aui-select2-container';
var auiDropdown = 'aui-select2-drop aui-dropdown2 aui-style-default';
var auiHasAvatar = 'aui-has-avatar';
_jquery2.default.fn.auiSelect2 = function (first) {
var updatedArgs;
if (_jquery2.default.isPlainObject(first)) {
var auiOpts = _jquery2.default.extend({}, first);
var auiAvatarClass = auiOpts.hasAvatar ? ' ' + auiHasAvatar : '';
//add our classes in addition to those the caller specified
auiOpts.containerCssClass = auiContainer + auiAvatarClass + (auiOpts.containerCssClass ? ' ' + auiOpts.containerCssClass : '');
auiOpts.dropdownCssClass = auiDropdown + auiAvatarClass + (auiOpts.dropdownCssClass ? ' ' + auiOpts.dropdownCssClass : '');
updatedArgs = Array.prototype.slice.call(arguments, 1);
updatedArgs.unshift(auiOpts);
} else if (!arguments.length) {
updatedArgs = [{
containerCssClass: auiContainer,
dropdownCssClass: auiDropdown
}];
} else {
updatedArgs = arguments;
}
return originalSelect2.apply(this, updatedArgs);
};
return module.exports;
}).call(this);
// src/js-vendor/raf/raf.js
(typeof window === 'undefined' ? global : window).__c814de1f9f57536916ee97e53618b317 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = Date.now(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window));
return module.exports;
}).call(this);
// src/js/aui/internal/has-touch.js
(typeof window === 'undefined' ? global : window).__2bddeae7bba6bcfe91954e333e4fbeb4 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var DocumentTouch = window.DocumentTouch;
var hasTouch = 'ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch;
exports.default = hasTouch;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/is-input.js
(typeof window === 'undefined' ? global : window).__5440f08d566da1cac4a925f4a02d99bd = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (el) {
return 'value' in el || el.isContentEditable;
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/mediaQuery.js
(typeof window === 'undefined' ? global : window).__2f005a42739e074aa33083fd59d18ccb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**
* Inspired by matchMedia() polyfill
* https://github.com/paulirish/matchMedia.js/blob/953faa1489284655ed9d6e03bf48d39df70612c4/matchMedia.js
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mediaQuery;
function mediaQuery(mq) {
if (window.matchMedia) {
return window.matchMedia(mq).matches;
}
// fallback support for <=IE9 (remove this code if we don't want to support IE9 anymore)
var style = document.createElement('style');
style.type = 'text/css';
style.id = 'testMedia';
style.innerText = '@media ' + mq + ' { #testMedia { width: 1px; } }';
document.head.appendChild(style);
var info = window.getComputedStyle(style, null);
var testMediaQuery = info.width === '1px';
style.parentNode.removeChild(style);
return testMediaQuery;
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/sidebar.js
(typeof window === 'undefined' ? global : window).__810b6deefd6627f937e4a4d2fae0520a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
__c814de1f9f57536916ee97e53618b317;
__be3e01199078cdf5ded88dda6a8fbec9;
var _clone = __dcc3fd3e77e47fb48e5c0c44ee208201;
var _clone2 = _interopRequireDefault(_clone);
var _deprecation = __4ddcc788b1704f76a51559fc0e0d2968;
var deprecate = _interopRequireWildcard(_deprecation);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _hasTouch = __2bddeae7bba6bcfe91954e333e4fbeb4;
var _hasTouch2 = _interopRequireDefault(_hasTouch);
var _isInput = __5440f08d566da1cac4a925f4a02d99bd;
var _isInput2 = _interopRequireDefault(_isInput);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _mediaQuery = __2f005a42739e074aa33083fd59d18ccb;
var _mediaQuery2 = _interopRequireDefault(_mediaQuery);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
var _widget = __2d1b5481970dd1547e294d829464e03f;
var _widget2 = _interopRequireDefault(_widget);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SUPPORTS_TRANSITIONS = typeof document.documentElement.style.transition !== 'undefined' || typeof document.documentElement.style.webkitTransition !== 'undefined';
function sidebarOffset(sidebar) {
return sidebar.offset().top;
}
function Sidebar(selector) {
this.$el = (0, _jquery2.default)(selector);
if (!this.$el.length) {
return;
}
this.$body = (0, _jquery2.default)('body');
this.$wrapper = this.$el.children('.aui-sidebar-wrapper');
// Sidebar users should add class="aui-page-sidebar" to the
// <body> in the rendered markup (to prevent any potential flicker),
// so we add it just in case they forgot.
this.$body.addClass('aui-page-sidebar');
this._previousScrollTop = null;
this._previousViewportHeight = null;
this._previousViewportWidth = null;
this._previousOffsetTop = null;
this.submenus = new SubmenuManager();
initializeHandlers(this);
constructAllSubmenus(this);
}
var FORCE_COLLAPSE_WIDTH = 1240;
var EVENT_PREFIX = '_aui-internal-sidebar-';
function namespaceEvents(events) {
return _jquery2.default.map(events.split(' '), function (event) {
return EVENT_PREFIX + event;
}).join(' ');
}
Sidebar.prototype.on = function () {
var events = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var namespacedEvents = namespaceEvents(events);
this.$el.on.apply(this.$el, [namespacedEvents].concat(args));
return this;
};
Sidebar.prototype.off = function () {
var events = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var namespacedEvents = namespaceEvents(events);
this.$el.off.apply(this.$el, [namespacedEvents].concat(args));
return this;
};
Sidebar.prototype.setHeight = function (scrollTop, viewportHeight, headerHeight) {
var visibleHeaderHeight = Math.max(0, headerHeight - scrollTop);
this.$wrapper.height(viewportHeight - visibleHeaderHeight);
return this;
};
Sidebar.prototype.setPosition = function (scrollTop) {
scrollTop = scrollTop || window.pageYOffset;
this.$wrapper.toggleClass('aui-is-docked', scrollTop > sidebarOffset(this.$el));
return this;
};
Sidebar.prototype.setCollapsedState = function (viewportWidth) {
// Reflow behaviour is implemented as a state machine (hence all
// state transitions are enumerated). The rest of the state machine,
// e.g., entering the expanded narrow (fly-out) state, is implemented
// by the toggle() method.
var transition = { collapsed: {}, expanded: {} };
transition.collapsed.narrow = {
narrow: _jquery2.default.noop,
wide: function wide(s) {
s._expand(viewportWidth, true);
}
};
transition.collapsed.wide = {
narrow: _jquery2.default.noop, // Becomes collapsed narrow (no visual change).
wide: _jquery2.default.noop
};
transition.expanded.narrow = {
narrow: _jquery2.default.noop,
wide: function wide(s) {
s.$body.removeClass('aui-sidebar-collapsed');
s.$el.removeClass('aui-sidebar-fly-out');
}
};
transition.expanded.wide = {
narrow: function narrow(s) {
s._collapse(true);
},
wide: _jquery2.default.noop
};
var collapseState = this.isCollapsed() ? 'collapsed' : 'expanded';
var oldSize = this.isViewportNarrow(this._previousViewportWidth) ? 'narrow' : 'wide';
var newSize = this.isViewportNarrow(viewportWidth) ? 'narrow' : 'wide';
transition[collapseState][oldSize][newSize](this);
return this;
};
Sidebar.prototype._collapse = function (isResponsive) {
if (this.isCollapsed()) {
return this;
}
var startEvent = _jquery2.default.Event(EVENT_PREFIX + 'collapse-start', { isResponsive: isResponsive });
this.$el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return this;
}
this.$body.addClass('aui-sidebar-collapsed');
this.$el.attr('aria-expanded', 'false');
this.$el.removeClass('aui-sidebar-fly-out');
this.$el.find(this.submenuTriggersSelector).attr('tabindex', 0);
(0, _jquery2.default)(this.inlineDialogSelector).attr('responds-to', 'hover');
if (!this.isAnimated()) {
this.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + 'collapse-end', { isResponsive: isResponsive }));
}
return this;
};
Sidebar.prototype.collapse = function () {
return this._collapse(false);
};
Sidebar.prototype._expand = function (viewportWidth, isResponsive) {
var startEvent = _jquery2.default.Event(EVENT_PREFIX + 'expand-start', { isResponsive: isResponsive });
this.$el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return this;
}
var isViewportNarrow = this.isViewportNarrow(viewportWidth);
this.$el.attr('aria-expanded', 'true');
this.$body.toggleClass('aui-sidebar-collapsed', isViewportNarrow);
this.$el.toggleClass('aui-sidebar-fly-out', isViewportNarrow);
this.$el.find(this.submenuTriggersSelector).removeAttr('tabindex');
(0, _jquery2.default)(this.inlineDialogSelector).removeAttr('responds-to');
if (!this.isAnimated()) {
this.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + 'expand-end', { isResponsive: isResponsive }));
}
return this;
};
Sidebar.prototype.expand = function () {
if (this.isCollapsed()) {
this._expand(this._previousViewportWidth, false);
}
return this;
};
Sidebar.prototype.isAnimated = function () {
return SUPPORTS_TRANSITIONS && this.$el.hasClass('aui-is-animated');
};
Sidebar.prototype.isCollapsed = function () {
return this.$el.attr('aria-expanded') === 'false';
};
Sidebar.prototype.isViewportNarrow = function (viewportWidth) {
viewportWidth = viewportWidth === undefined ? this._previousViewportWidth : viewportWidth;
return viewportWidth < FORCE_COLLAPSE_WIDTH;
};
Sidebar.prototype._removeAllTooltips = function () {
// tooltips are orphaned when sidebar is expanded, so if there are any visible on the page we remove them all.
// Can't scope it to the Sidebar (this) because the tooltip div is a direct child of <body>
(0, _jquery2.default)(this.tooltipSelector).remove();
};
Sidebar.prototype.responsiveReflow = function responsiveReflow(isInitialPageLoad, viewportWidth) {
if (isInitialPageLoad) {
if (!this.isCollapsed() && this.isViewportNarrow(viewportWidth)) {
var isAnimated = this.isAnimated();
if (isAnimated) {
this.$el.removeClass('aui-is-animated');
}
// This will trigger the "collapse" event before non-sidebar
// JS code has a chance to bind listeners; they'll need to
// check isCollapsed() if they care about the value at that
// time.
this.collapse();
if (isAnimated) {
// We must trigger a CSS reflow (by accessing
// offsetHeight) otherwise the transition still runs.
// eslint-disable-next-line
this.$el[0].offsetHeight;
this.$el.addClass('aui-is-animated');
}
}
} else if (viewportWidth !== this._previousViewportWidth) {
this.setCollapsedState(viewportWidth);
}
};
Sidebar.prototype.reflow = function reflow(scrollTop, viewportHeight, viewportWidth, scrollHeight) {
scrollTop = scrollTop === undefined ? window.pageYOffset : scrollTop;
viewportHeight = viewportHeight === undefined ? document.documentElement.clientHeight : viewportHeight;
scrollHeight = scrollHeight === undefined ? document.documentElement.scrollHeight : scrollHeight;
viewportWidth = viewportWidth === undefined ? window.innerWidth : viewportWidth;
// Header height needs to be checked because in Stash it changes when the CSS "transform: translate3d" is changed.
// If you called reflow() after this change then nothing happened because the scrollTop and viewportHeight hadn't changed.
var offsetTop = sidebarOffset(this.$el);
var isInitialPageLoad = this._previousViewportWidth === null;
if (!(scrollTop === this._previousScrollTop && viewportHeight === this._previousViewportHeight && offsetTop === this._previousOffsetTop)) {
if (this.isCollapsed() && !isInitialPageLoad && scrollTop !== this._previousScrollTop) {
// hide submenu and tooltips on scroll
hideAllSubmenus();
this._removeAllTooltips();
}
var isTouch = this.$body.hasClass('aui-page-sidebar-touch');
var isTrackpadBounce = scrollTop !== this._previousScrollTop && (scrollTop < 0 || scrollTop + viewportHeight > scrollHeight);
if (!isTouch && (isInitialPageLoad || !isTrackpadBounce)) {
this.setHeight(scrollTop, viewportHeight, offsetTop);
this.setPosition(scrollTop);
}
}
var isResponsive = this.$el.attr('data-aui-responsive') !== 'false';
if (isResponsive) {
this.responsiveReflow(isInitialPageLoad, viewportWidth);
} else {
var isFlyOut = !this.isCollapsed() && this.isViewportNarrow(viewportWidth);
this.$el.toggleClass('aui-sidebar-fly-out', isFlyOut);
}
this._previousScrollTop = scrollTop;
this._previousViewportHeight = viewportHeight;
this._previousViewportWidth = viewportWidth;
this._previousOffsetTop = offsetTop;
return this;
};
Sidebar.prototype.toggle = function () {
if (this.isCollapsed()) {
this.expand();
this._removeAllTooltips();
} else {
this.collapse();
}
return this;
};
/**
* Returns a jQuery selector string for the trigger elements when the
* sidebar is in a collapsed state, useful for delegated event binding.
*
* When using this selector in event handlers, the element ("this") will
* either be an <a> (when the trigger was a tier-one menu item) or an
* element with class "aui-sidebar-group" (for non-tier-one items).
*
* For delegated event binding you should bind to $el and check the value
* of isCollapsed(), e.g.,
*
* sidebar.$el.on('click', sidebar.collapsedTriggersSelector, function (e) {
* if (!sidebar.isCollapsed()) {
* return;
* }
* });
*
* @returns string
*/
Sidebar.prototype.submenuTriggersSelector = '.aui-sidebar-group:not(.aui-sidebar-group-tier-one)';
Sidebar.prototype.collapsedTriggersSelector = [Sidebar.prototype.submenuTriggersSelector, '.aui-sidebar-group.aui-sidebar-group-tier-one > .aui-nav > li > a', '.aui-sidebar-footer > .aui-sidebar-settings-button'].join(', ');
Sidebar.prototype.toggleSelector = '.aui-sidebar-footer > .aui-sidebar-toggle';
Sidebar.prototype.tooltipSelector = '.aui-sidebar-section-tooltip';
Sidebar.prototype.inlineDialogClass = 'aui-sidebar-submenu-dialog';
Sidebar.prototype.inlineDialogSelector = '.' + Sidebar.prototype.inlineDialogClass;
function getAllSubmenuDialogs() {
return document.querySelectorAll(Sidebar.prototype.inlineDialogSelector);
}
function SubmenuManager() {
this.inlineDialog = null;
}
SubmenuManager.prototype.submenu = function ($trigger) {
sidebarSubmenuDeprecationLogger();
return getSubmenu($trigger);
};
SubmenuManager.prototype.hasSubmenu = function ($trigger) {
sidebarSubmenuDeprecationLogger();
return hasSubmenu($trigger);
};
SubmenuManager.prototype.submenuHeadingHeight = function () {
sidebarSubmenuDeprecationLogger();
return 34;
};
SubmenuManager.prototype.isShowing = function () {
sidebarSubmenuDeprecationLogger();
return Sidebar.prototype.isSubmenuVisible();
};
SubmenuManager.prototype.show = function (e, trigger) {
sidebarSubmenuDeprecationLogger();
showSubmenu(trigger);
};
SubmenuManager.prototype.hide = function () {
sidebarSubmenuDeprecationLogger();
hideAllSubmenus();
};
SubmenuManager.prototype.inlineDialogShowHandler = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.inlineDialogHideHandler = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.moveSubmenuToInlineDialog = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.restoreSubmenu = function () {
sidebarSubmenuDeprecationLogger();
};
Sidebar.prototype.getVisibleSubmenus = function () {
return Array.prototype.filter.call(getAllSubmenuDialogs(), function (inlineDialog2) {
return inlineDialog2.open;
});
};
Sidebar.prototype.isSubmenuVisible = function () {
return this.getVisibleSubmenus().length > 0;
};
function getSubmenu($trigger) {
return $trigger.is('a') ? $trigger.next('.aui-nav') : $trigger.children('.aui-nav, hr');
}
function getSubmenuInlineDialog(trigger) {
var inlineDialogId = trigger.getAttribute('aria-controls');
return document.getElementById(inlineDialogId);
}
function hasSubmenu($trigger) {
return getSubmenu($trigger).length !== 0;
}
function hideAllSubmenus() {
var allSubmenuDialogs = getAllSubmenuDialogs();
Array.prototype.forEach.call(allSubmenuDialogs, function (inlineDialog2) {
inlineDialog2.open = false;
});
}
function showSubmenu(trigger) {
getSubmenuInlineDialog(trigger).open = true;
}
function constructSubmenu(sidebar, $trigger) {
if ($trigger.data('_aui-sidebar-submenu-constructed')) {
return;
} else {
$trigger.data('_aui-sidebar-submenu-constructed', true);
}
if (!hasSubmenu($trigger)) {
return;
}
var submenuInlineDialog = document.createElement('aui-inline-dialog');
var uniqueId = (0, _uniqueId2.default)('sidebar-submenu');
$trigger.attr('aria-controls', uniqueId);
$trigger.attr('data-aui-trigger', '');
_skate2.default.init($trigger); //Trigger doesn't listen to attribute modification
submenuInlineDialog.setAttribute('id', uniqueId);
submenuInlineDialog.setAttribute('alignment', 'right top');
submenuInlineDialog.setAttribute('aria-hidden', 'true');
if (sidebar.isCollapsed()) {
submenuInlineDialog.setAttribute('responds-to', 'hover');
}
(0, _jquery2.default)(submenuInlineDialog).addClass(Sidebar.prototype.inlineDialogClass);
document.body.appendChild(submenuInlineDialog);
_skate2.default.init(submenuInlineDialog); //Needed so that sidebar.submenus.isShowing() will work on page load
addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog);
return submenuInlineDialog;
}
function addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog) {
submenuInlineDialog.addEventListener('aui-layer-show', function (e) {
if (!sidebar.isCollapsed()) {
e.preventDefault();
return;
}
inlineDialogShowHandler($trigger, submenuInlineDialog);
});
submenuInlineDialog.addEventListener('aui-layer-hide', function () {
inlineDialogHideHandler($trigger);
});
}
function inlineDialogShowHandler($trigger, submenuInlineDialog) {
$trigger.addClass('active');
submenuInlineDialog.innerHTML = SUBMENU_INLINE_DIALOG_CONTENTS_HTML;
var title = $trigger.is('a') ? $trigger.text() : $trigger.children('.aui-nav-heading').text();
var $container = (0, _jquery2.default)(submenuInlineDialog).find('.aui-navgroup-inner');
$container.children('.aui-nav-heading').attr('title', title).children('strong').text(title);
var $submenu = getSubmenu($trigger);
cloneExpander($submenu).appendTo($container);
/**
* Workaround to show all contents in the expander.
* This function should come from the expander component.
*/
function cloneExpander(element) {
var $clone = (0, _clone2.default)(element);
if ($clone.hasClass('aui-expander-content')) {
$clone.find('.aui-expander-cutoff').remove();
$clone.removeClass('aui-expander-content');
}
return $clone;
}
}
var SUBMENU_INLINE_DIALOG_CONTENTS_HTML = '<div class="aui-inline-dialog-contents">' + '<div class="aui-sidebar-submenu" >' + '<div class="aui-navgroup aui-navgroup-vertical">' + '<div class="aui-navgroup-inner">' + '<div class="aui-nav-heading"><strong></strong></div>' + '</div>' + '</div>' + '</div>' + '</div>';
function inlineDialogHideHandler($trigger) {
$trigger.removeClass('active');
}
function constructAllSubmenus(sidebar) {
(0, _jquery2.default)(sidebar.collapsedTriggersSelector).each(function () {
var $trigger = (0, _jquery2.default)(this);
constructSubmenu(sidebar, $trigger);
});
}
var tipsyOpts = {
trigger: 'manual',
gravity: 'w',
className: 'aui-sidebar-section-tooltip',
title: function title() {
var $item = (0, _jquery2.default)(this);
if ($item.is('a')) {
return $item.attr('title') || $item.find('.aui-nav-item-label').text() || $item.data('tooltip');
} else {
return $item.children('.aui-nav').attr('title') || $item.children('.aui-nav-heading').text();
}
}
};
function showTipsy($trigger) {
$trigger.tipsy(tipsyOpts).tipsy('show');
var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip;
if ($tip) {
// if .aui-sidebar-group does not have a title to display
// Remove "opacity" inline style from Tipsy to allow the our own styles and transitions to be applied
$tip.css({ opacity: '' }).addClass('tooltip-shown');
}
}
function hideTipsy($trigger) {
var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip;
if ($tip) {
var durationStr = $tip.css('transition-duration');
if (durationStr) {
// can be denominated in either s or ms
var timeoutMs = durationStr.indexOf('ms') >= 0 ? parseInt(durationStr.substring(0, durationStr.length - 2), 10) : 1000 * parseInt(durationStr.substring(0, durationStr.length - 1), 10);
// use a timeout because the transitionend event is not reliable (yet),
// more details here: https://bitbucket.atlassian.net/browse/BB-11599
// an example of this at http://labs.silverorange.com/files/webkit-bug/
// further caveats here: https://developer.mozilla.org/en-US/docs/Web/Events/transitionend
// "In the case where a transition is removed before completion,
// such as if the transition-property is removed, then the event will not fire."
setTimeout(function () {
$trigger.tipsy('hide');
}, timeoutMs);
}
$tip.removeClass('tooltip-shown');
}
}
function lazilyInitializeSubmenus(sidebar) {
sidebar.$el.on('mouseenter mouseleave click focus', sidebar.collapsedTriggersSelector, function (e) {
var $trigger = (0, _jquery2.default)(e.target);
constructSubmenu(sidebar, $trigger);
});
}
function initializeHandlers(sidebar) {
var $sidebar = (0, _jquery2.default)('.aui-sidebar');
if (!$sidebar.length) {
return;
}
lazilyInitializeSubmenus(sidebar);
// AUI-2542: only enter touch mode on small screen touchable devices
if (_hasTouch2.default && (0, _mediaQuery2.default)('only screen and (max-device-width:1024px)')) {
(0, _jquery2.default)('body').addClass('aui-page-sidebar-touch');
}
var pendingReflow = null;
var onScrollResizeReflow = function onScrollResizeReflow() {
if (pendingReflow === null) {
pendingReflow = requestAnimationFrame(function () {
sidebar.reflow();
pendingReflow = null;
});
}
};
(0, _jquery2.default)(window).on('scroll resize', onScrollResizeReflow);
sidebar.reflow();
if (sidebar.isAnimated()) {
sidebar.$el.on('transitionend webkitTransitionEnd', function () {
sidebar.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + (sidebar.isCollapsed() ? 'collapse-end' : 'expand-end')));
});
}
sidebar.$el.on('click', '.aui-sidebar-toggle', function (e) {
e.preventDefault();
sidebar.toggle();
});
(0, _jquery2.default)('.aui-page-panel').click(function () {
if (!sidebar.isCollapsed() && sidebar.isViewportNarrow()) {
sidebar.collapse();
}
});
var toggleShortcutHandler = function toggleShortcutHandler(e) {
if (isNormalSquareBracket(e)) {
sidebar.toggle();
}
};
//We use keypress because it captures the actual character that was typed and not the physical key that was pressed.
//This accounts for other keyboard layouts
(0, _jquery2.default)(document).on('keypress', toggleShortcutHandler);
sidebar._remove = function () {
this._removeAllTooltips();
(0, _jquery2.default)(this.inlineDialogSelector).remove();
this.$el.off();
this.$el.remove();
(0, _jquery2.default)(document).off('keypress', toggleShortcutHandler);
(0, _jquery2.default)(window).off('scroll resize', onScrollResizeReflow);
};
sidebar.$el.on('touchend', function (e) {
if (sidebar.isCollapsed()) {
sidebar.expand();
e.preventDefault();
}
});
sidebar.$el.on('mouseenter focus', sidebar.collapsedTriggersSelector, function () {
if (!sidebar.isCollapsed()) {
return;
}
var $trigger = (0, _jquery2.default)(this);
if (!hasSubmenu($trigger)) {
showTipsy($trigger);
}
});
sidebar.$el.on('click blur mouseleave', sidebar.collapsedTriggersSelector, function () {
if (!sidebar.isCollapsed()) {
return;
}
hideTipsy((0, _jquery2.default)(this));
});
sidebar.$el.on('mouseenter focus', sidebar.toggleSelector, function () {
var $trigger = (0, _jquery2.default)(this);
if (sidebar.isCollapsed()) {
$trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.expand.tooltip'));
} else {
$trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.collapse.tooltip'));
}
showTipsy($trigger);
});
sidebar.$el.on('click blur mouseleave', sidebar.toggleSelector, function () {
hideTipsy((0, _jquery2.default)(this));
});
function isNormalTab(e) {
return e.keyCode === _keyCode2.default.TAB && !e.shiftKey && !e.altKey;
}
function isNormalSquareBracket(e) {
return e.which === _keyCode2.default.LEFT_SQUARE_BRACKET && !e.shiftKey && !e.ctrlKey && !e.metaKey && !(0, _isInput2.default)(e.target);
}
function isShiftTab(e) {
return e.keyCode === _keyCode2.default.TAB && e.shiftKey;
}
function isFirstSubmenuItem(item, $submenuDialog) {
return item === $submenuDialog.find(':aui-tabbable')[0];
}
function isLastSubmenuItem(item, $submenuDialog) {
return item === $submenuDialog.find(':aui-tabbable').last()[0];
}
/**
* Force to focus on the first tabbable item in inline dialog.
* Reason: inline dialog will be hidden as soon as the trigger is out of focus (onBlur event)
* This function should come directly from inline dialog component.
*/
function focusFirstItemOfInlineDialog($inlineDialog) {
$inlineDialog.attr('persistent', '');
// don't use :aui-tabbable:first as it will select the first tabbable item in EACH nav group
$inlineDialog.find(':aui-tabbable').first().focus();
// workaround on IE:
// delay the persistence of inline dialog to make sure onBlur event was triggered first
setTimeout(function () {
$inlineDialog.removeAttr('persistent');
}, 100);
}
sidebar.$el.on('keydown', sidebar.collapsedTriggersSelector, function (e) {
if (sidebar.isCollapsed()) {
var triggerEl = e.target;
var submenuInlineDialog = getSubmenuInlineDialog(triggerEl);
if (!submenuInlineDialog) {
return;
}
var $submenuInlineDialog = (0, _jquery2.default)(submenuInlineDialog);
if (isNormalTab(e) && submenuInlineDialog.open) {
e.preventDefault();
focusFirstItemOfInlineDialog($submenuInlineDialog);
$submenuInlineDialog.on('keydown', function (e) {
if (isShiftTab(e) && isFirstSubmenuItem(e.target, $submenuInlineDialog) || isNormalTab(e) && isLastSubmenuItem(e.target, $submenuInlineDialog)) {
triggerEl.focus();
// unbind event and close submenu as the focus is out of the submenu
(0, _jquery2.default)(this).off('keydown');
hideAllSubmenus();
}
});
}
}
});
}
var sidebar = (0, _widget2.default)('sidebar', Sidebar);
(0, _jquery2.default)(function () {
sidebar('.aui-sidebar');
});
var sidebarSubmenuDeprecationLogger = deprecate.getMessageLogger('Sidebar.submenus', {
removeInVersion: '8.0',
sinceVersion: '5.8'
});
(0, _globalize2.default)('sidebar', sidebar);
exports.default = sidebar;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/jquery.tablesorter.js
(typeof window === 'undefined' ? global : window).__f1a3fa76609e6d40a55157a38f5d9723 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**!
* TableSorter 2.17.7 - Client-side table sorting with ease!
* @requires jQuery v1.2.6+
*
* Copyright (c) 2007 Christian Bach
* Examples and docs at: http://tablesorter.com
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* @type jQuery
* @name tablesorter
* @cat Plugins/Tablesorter
* @author Christian Bach/[email protected]
* @contributor Rob Garrison/https://github.com/Mottie/tablesorter
*/
/*jshint browser:true, jquery:true, unused:false, expr: true */
/*global console:false, alert:false */
!(function($) {
$.extend({
/*jshint supernew:true */
tablesorter: new function() {
var ts = this;
ts.version = "2.17.7";
ts.parsers = [];
ts.widgets = [];
ts.defaults = {
// *** appearance
theme : 'default', // adds tablesorter-{theme} to the table for styling
widthFixed : false, // adds colgroup to fix widths of columns
showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered.
headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> (class from cssIcon)
onRenderTemplate : null, // function(index, template){ return template; }, (template is a string)
onRenderHeader : null, // function(index){}, (nothing to return)
// *** functionality
cancelSelection : true, // prevent text selection in the header
tabIndex : true, // add tabindex to header for keyboard accessibility
dateFormat : 'mmddyyyy', // other options: "ddmmyyy" or "yyyymmdd"
sortMultiSortKey : 'shiftKey', // key used to select additional columns
sortResetKey : 'ctrlKey', // key used to remove sorting on a column
usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89"
delayInit : false, // if false, the parsed table contents will not update until the first sort
serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used.
// *** sort options
headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc.
ignoreCase : true, // ignore case while sorting
sortForce : null, // column(s) first sorted; always applied
sortList : [], // Initial sort order; applied initially; updated when manually sorted
sortAppend : null, // column(s) sorted last; always applied
sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained
sortInitialOrder : 'asc', // sort direction on first click
sortLocaleCompare: false, // replace equivalent character (accented characters)
sortReset : false, // third click on the header will reset column to default - unsorted
sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns
emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero
stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero
textExtraction : 'basic', // text extraction method/function - function(node, table, cellIndex){}
textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in textExtraction function)
textSorter : null, // choose overall or specific column sorter function(a, b, direction, table, columnIndex) [alt: ts.sortText]
numberSorter : null, // choose overall numeric sorter function(a, b, direction, maxColumnValue)
// *** widget options
widgets: [], // method to add widgets, e.g. widgets: ['zebra']
widgetOptions : {
zebra : [ 'even', 'odd' ] // zebra widget alternating row class names
},
initWidgets : true, // apply widgets on tablesorter initialization
// *** callbacks
initialized : null, // function(table){},
// *** extra css class names
tableClass : '',
cssAsc : '',
cssDesc : '',
cssNone : '',
cssHeader : '',
cssHeaderRow : '',
cssProcessing : '', // processing icon applied to header during sort/filter
cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent
cssIcon : 'tablesorter-icon', // if this class exists, a <i> will be added to the header automatically
cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!)
// *** selectors
selectorHeaders : '> thead th, > thead td',
selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort
selectorRemove : '.remove-me',
// *** advanced
debug : false,
// *** Internal variables
headerList: [],
empties: {},
strings: {},
parsers: []
// deprecated; but retained for backwards compatibility
// widgetZebra: { css: ["even", "odd"] }
};
// internal css classes - these will ALWAYS be added to
// the table and MUST only contain one class name - fixes #381
ts.css = {
table : 'tablesorter',
cssHasChild: 'tablesorter-hasChildRow',
childRow : 'tablesorter-childRow',
header : 'tablesorter-header',
headerRow : 'tablesorter-headerRow',
headerIn : 'tablesorter-header-inner',
icon : 'tablesorter-icon',
info : 'tablesorter-infoOnly',
processing : 'tablesorter-processing',
sortAsc : 'tablesorter-headerAsc',
sortDesc : 'tablesorter-headerDesc',
sortNone : 'tablesorter-headerUnSorted'
};
// labels applied to sortable headers for accessibility (aria) support
ts.language = {
sortAsc : 'Ascending sort applied, ',
sortDesc : 'Descending sort applied, ',
sortNone : 'No sort applied, ',
nextAsc : 'activate to apply an ascending sort',
nextDesc : 'activate to apply a descending sort',
nextNone : 'activate to remove the sort'
};
/* debuging utils */
function log() {
var a = arguments[0],
s = arguments.length > 1 ? Array.prototype.slice.call(arguments) : a;
if (typeof console !== "undefined" && typeof console.log !== "undefined") {
console[ /error/i.test(a) ? 'error' : /warn/i.test(a) ? 'warn' : 'log' ](s);
} else {
alert(s);
}
}
function benchmark(s, d) {
log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)");
}
ts.log = log;
ts.benchmark = benchmark;
// $.isEmptyObject from jQuery v1.4
function isEmptyObject(obj) {
/*jshint forin: false */
for (var name in obj) {
return false;
}
return true;
}
function getElementText(table, node, cellIndex) {
if (!node) { return ""; }
var te, c = table.config,
t = c.textExtraction || '',
text = "";
if (t === "basic") {
// check data-attribute first
text = $(node).attr(c.textAttribute) || node.textContent || node.innerText || $(node).text() || "";
} else {
if (typeof(t) === "function") {
text = t(node, table, cellIndex);
} else if (typeof (te = ts.getColumnData( table, t, cellIndex )) === 'function') {
text = te(node, table, cellIndex);
} else {
// previous "simple" method
text = node.textContent || node.innerText || $(node).text() || "";
}
}
return $.trim(text);
}
function detectParserForColumn(table, rows, rowIndex, cellIndex) {
var cur,
i = ts.parsers.length,
node = false,
nodeValue = '',
keepLooking = true;
while (nodeValue === '' && keepLooking) {
rowIndex++;
if (rows[rowIndex]) {
node = rows[rowIndex].cells[cellIndex];
nodeValue = getElementText(table, node, cellIndex);
if (table.config.debug) {
log('Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': "' + nodeValue + '"');
}
} else {
keepLooking = false;
}
}
while (--i >= 0) {
cur = ts.parsers[i];
// ignore the default text parser because it will always be true
if (cur && cur.id !== 'text' && cur.is && cur.is(nodeValue, table, node)) {
return cur;
}
}
// nothing found, return the generic parser (text)
return ts.getParserById('text');
}
function buildParserCache(table) {
var c = table.config,
// update table bodies in case we start with an empty table
tb = c.$tbodies = c.$table.children('tbody:not(.' + c.cssInfoBlock + ')'),
rows, list, l, i, h, ch, np, p, e, time,
j = 0,
parsersDebug = "",
len = tb.length;
if ( len === 0) {
return c.debug ? log('Warning: *Empty table!* Not building a parser cache') : '';
} else if (c.debug) {
time = new Date();
log('Detecting parsers for each column');
}
list = {
extractors: [],
parsers: []
};
while (j < len) {
rows = tb[j].rows;
if (rows[j]) {
l = c.columns; // rows[j].cells.length;
for (i = 0; i < l; i++) {
h = c.$headers.filter('[data-column="' + i + '"]:last');
// get column indexed table cell
ch = ts.getColumnData( table, c.headers, i );
// get column parser/extractor
e = ts.getParserById( ts.getData(h, ch, 'extractor') );
p = ts.getParserById( ts.getData(h, ch, 'sorter') );
np = ts.getData(h, ch, 'parser') === 'false';
// empty cells behaviour - keeping emptyToBottom for backwards compatibility
c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' );
// text strings behaviour in numerical sorts
c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max';
if (np) {
p = ts.getParserById('no-parser');
}
if (!e) {
// For now, maybe detect someday
e = false;
}
if (!p) {
p = detectParserForColumn(table, rows, -1, i);
}
if (c.debug) {
parsersDebug += "column:" + i + "; extractor:" + e.id + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n";
}
list.parsers[i] = p;
list.extractors[i] = e;
}
}
j += (list.parsers.length) ? len : 1;
}
if (c.debug) {
log(parsersDebug ? parsersDebug : "No parsers detected");
benchmark("Completed detecting parsers", time);
}
c.parsers = list.parsers;
c.extractors = list.extractors;
}
/* utils */
function buildCache(table) {
var cc, t, tx, v, i, j, k, $row, rows, cols, cacheTime,
totalRows, rowData, colMax,
c = table.config,
$tb = c.$table.children('tbody'),
extractors = c.extractors,
parsers = c.parsers;
c.cache = {};
c.totalRows = 0;
// if no parsers found, return - it's an empty table.
if (!parsers) {
return c.debug ? log('Warning: *Empty table!* Not building a cache') : '';
}
if (c.debug) {
cacheTime = new Date();
}
// processing icon
if (c.showProcessing) {
ts.isProcessing(table, true);
}
for (k = 0; k < $tb.length; k++) {
colMax = []; // column max value per tbody
cc = c.cache[k] = {
normalized: [] // array of normalized row data; last entry contains "rowData" above
// colMax: # // added at the end
};
// ignore tbodies with class name from c.cssInfoBlock
if (!$tb.eq(k).hasClass(c.cssInfoBlock)) {
totalRows = ($tb[k] && $tb[k].rows.length) || 0;
for (i = 0; i < totalRows; ++i) {
rowData = {
// order: original row order #
// $row : jQuery Object[]
child: [] // child row text (filter widget)
};
/** Add the table data to main data array */
$row = $($tb[k].rows[i]);
rows = [ new Array(c.columns) ];
cols = [];
// if this is a child row, add it to the last row's children and continue to the next row
// ignore child row class, if it is the first row
if ($row.hasClass(c.cssChildRow) && i !== 0) {
t = cc.normalized.length - 1;
cc.normalized[t][c.columns].$row = cc.normalized[t][c.columns].$row.add($row);
// add "hasChild" class name to parent row
if (!$row.prev().hasClass(c.cssChildRow)) {
$row.prev().addClass(ts.css.cssHasChild);
}
// save child row content (un-parsed!)
rowData.child[t] = $.trim( $row[0].textContent || $row[0].innerText || $row.text() || "" );
// go to the next for loop
continue;
}
rowData.$row = $row;
rowData.order = i; // add original row position to rowCache
for (j = 0; j < c.columns; ++j) {
if (typeof parsers[j] === 'undefined') {
if (c.debug) {
log('No parser found for cell:', $row[0].cells[j], 'does it have a header?');
}
continue;
}
t = getElementText(table, $row[0].cells[j], j);
// do extract before parsing if there is one
if (typeof extractors[j].id === 'undefined') {
tx = t;
} else {
tx = extractors[j].format(t, table, $row[0].cells[j], j);
}
// allow parsing if the string is empty, previously parsing would change it to zero,
// in case the parser needs to extract data from the table cell attributes
v = parsers[j].id === 'no-parser' ? '' : parsers[j].format(tx, table, $row[0].cells[j], j);
cols.push( c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v );
if ((parsers[j].type || '').toLowerCase() === "numeric") {
// determine column max value (ignore sign)
colMax[j] = Math.max(Math.abs(v) || 0, colMax[j] || 0);
}
}
// ensure rowData is always in the same location (after the last column)
cols[c.columns] = rowData;
cc.normalized.push(cols);
}
cc.colMax = colMax;
// total up rows, not including child rows
c.totalRows += cc.normalized.length;
}
}
if (c.showProcessing) {
ts.isProcessing(table); // remove processing icon
}
if (c.debug) {
benchmark("Building cache for " + totalRows + " rows", cacheTime);
}
}
// init flag (true) used by pager plugin to prevent widget application
function appendToTable(table, init) {
var c = table.config,
wo = c.widgetOptions,
b = table.tBodies,
rows = [],
cc = c.cache,
n, totalRows, $bk, $tb,
i, k, appendTime;
// empty table - fixes #206/#346
if (isEmptyObject(cc)) {
// run pager appender in case the table was just emptied
return c.appender ? c.appender(table, rows) :
table.isUpdating ? c.$table.trigger("updateComplete", table) : ''; // Fixes #532
}
if (c.debug) {
appendTime = new Date();
}
for (k = 0; k < b.length; k++) {
$bk = $(b[k]);
if ($bk.length && !$bk.hasClass(c.cssInfoBlock)) {
// get tbody
$tb = ts.processTbody(table, $bk, true);
n = cc[k].normalized;
totalRows = n.length;
for (i = 0; i < totalRows; i++) {
rows.push(n[i][c.columns].$row);
// removeRows used by the pager plugin; don't render if using ajax - fixes #411
if (!c.appender || (c.pager && (!c.pager.removeRows || !wo.pager_removeRows) && !c.pager.ajax)) {
$tb.append(n[i][c.columns].$row);
}
}
// restore tbody
ts.processTbody(table, $tb, false);
}
}
if (c.appender) {
c.appender(table, rows);
}
if (c.debug) {
benchmark("Rebuilt table", appendTime);
}
// apply table widgets; but not before ajax completes
if (!init && !c.appender) { ts.applyWidget(table); }
if (table.isUpdating) {
c.$table.trigger("updateComplete", table);
}
}
function formatSortingOrder(v) {
// look for "d" in "desc" order; return true
return (/^d/i.test(v) || v === 1);
}
function buildHeaders(table) {
var ch, $t,
h, i, t, lock, time,
c = table.config;
c.headerList = [];
c.headerContent = [];
if (c.debug) {
time = new Date();
}
// children tr in tfoot - see issue #196 & #547
c.columns = ts.computeColumnIndex( c.$table.children('thead, tfoot').children('tr') );
// add icon if cssIcon option exists
i = c.cssIcon ? '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' : '';
// redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683
c.$headers = $(table).find(c.selectorHeaders).each(function(index) {
$t = $(this);
// make sure to get header cell & not column indexed cell
ch = ts.getColumnData( table, c.headers, index, true );
// save original header content
c.headerContent[index] = $(this).html();
// set up header template
t = c.headerTemplate.replace(/\{content\}/g, $(this).html()).replace(/\{icon\}/g, i);
if (c.onRenderTemplate) {
h = c.onRenderTemplate.apply($t, [index, t]);
if (h && typeof h === 'string') { t = h; } // only change t if something is returned
}
$(this).html('<div class="' + ts.css.headerIn + '">' + t + '</div>'); // faster than wrapInner
if (c.onRenderHeader) { c.onRenderHeader.apply($t, [index]); }
this.column = parseInt( $(this).attr('data-column'), 10);
this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2];
this.count = -1; // set to -1 because clicking on the header automatically adds one
this.lockedOrder = false;
lock = ts.getData($t, ch, 'lockedOrder') || false;
if (typeof lock !== 'undefined' && lock !== false) {
this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0];
}
$t.addClass(ts.css.header + ' ' + c.cssHeader);
// add cell to headerList
c.headerList[index] = this;
// add to parent in case there are multiple rows
$t.parent().addClass(ts.css.headerRow + ' ' + c.cssHeaderRow).attr('role', 'row');
// allow keyboard cursor to focus on element
if (c.tabIndex) { $t.attr("tabindex", 0); }
}).attr({
scope: 'col',
role : 'columnheader'
});
// enable/disable sorting
updateHeader(table);
if (c.debug) {
benchmark("Built headers:", time);
log(c.$headers);
}
}
function commonUpdate(table, resort, callback) {
var c = table.config;
// remove rows/elements before update
c.$table.find(c.selectorRemove).remove();
// rebuild parsers
buildParserCache(table);
// rebuild the cache map
buildCache(table);
checkResort(c.$table, resort, callback);
}
function updateHeader(table) {
var s, $th, col,
c = table.config;
c.$headers.each(function(index, th){
$th = $(th);
col = ts.getColumnData( table, c.headers, index, true );
// add "sorter-false" class if "parser-false" is set
s = ts.getData( th, col, 'sorter' ) === 'false' || ts.getData( th, col, 'parser' ) === 'false';
th.sortDisabled = s;
$th[ s ? 'addClass' : 'removeClass' ]('sorter-false').attr('aria-disabled', '' + s);
// aria-controls - requires table ID
if (table.id) {
if (s) {
$th.removeAttr('aria-controls');
} else {
$th.attr('aria-controls', table.id);
}
}
});
}
function setHeadersCss(table) {
var f, i, j,
c = table.config,
list = c.sortList,
len = list.length,
none = ts.css.sortNone + ' ' + c.cssNone,
css = [ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc],
aria = ['ascending', 'descending'],
// find the footer
$t = $(table).find('tfoot tr').children().add(c.$extraHeaders).removeClass(css.join(' '));
// remove all header information
c.$headers
.removeClass(css.join(' '))
.addClass(none).attr('aria-sort', 'none');
for (i = 0; i < len; i++) {
// direction = 2 means reset!
if (list[i][1] !== 2) {
// multicolumn sorting updating - choose the :last in case there are nested columns
f = c.$headers.not('.sorter-false').filter('[data-column="' + list[i][0] + '"]' + (len === 1 ? ':last' : '') );
if (f.length) {
for (j = 0; j < f.length; j++) {
if (!f[j].sortDisabled) {
f.eq(j).removeClass(none).addClass(css[list[i][1]]).attr('aria-sort', aria[list[i][1]]);
}
}
// add sorted class to footer & extra headers, if they exist
if ($t.length) {
$t.filter('[data-column="' + list[i][0] + '"]').removeClass(none).addClass(css[list[i][1]]);
}
}
}
}
// add verbose aria labels
c.$headers.not('.sorter-false').each(function(){
var $this = $(this),
nextSort = this.order[(this.count + 1) % (c.sortReset ? 3 : 2)],
txt = $this.text() + ': ' +
ts.language[ $this.hasClass(ts.css.sortAsc) ? 'sortAsc' : $this.hasClass(ts.css.sortDesc) ? 'sortDesc' : 'sortNone' ] +
ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ];
$this.attr('aria-label', txt );
});
}
// automatically add col group, and column sizes if set
function fixColumnWidth(table) {
if (table.config.widthFixed && $(table).find('colgroup').length === 0) {
var colgroup = $('<colgroup>'),
overallWidth = $(table).width();
// only add col for visible columns - fixes #371
$(table.tBodies[0]).find("tr:first").children(":visible").each(function() {
colgroup.append($('<col>').css('width', parseInt(($(this).width()/overallWidth)*1000, 10)/10 + '%'));
});
$(table).prepend(colgroup);
}
}
function updateHeaderSortCount(table, list) {
var s, t, o, col, primary,
c = table.config,
sl = list || c.sortList;
c.sortList = [];
$.each(sl, function(i,v){
// ensure all sortList values are numeric - fixes #127
col = parseInt(v[0], 10);
// make sure header exists
o = c.$headers.filter('[data-column="' + col + '"]:last')[0];
if (o) { // prevents error if sorton array is wrong
// o.count = o.count + 1;
t = ('' + v[1]).match(/^(1|d|s|o|n)/);
t = t ? t[0] : '';
// 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext
switch(t) {
case '1': case 'd': // descending
t = 1;
break;
case 's': // same direction (as primary column)
// if primary sort is set to "s", make it ascending
t = primary || 0;
break;
case 'o':
s = o.order[(primary || 0) % (c.sortReset ? 3 : 2)];
// opposite of primary column; but resets if primary resets
t = s === 0 ? 1 : s === 1 ? 0 : 2;
break;
case 'n':
o.count = o.count + 1;
t = o.order[(o.count) % (c.sortReset ? 3 : 2)];
break;
default: // ascending
t = 0;
break;
}
primary = i === 0 ? t : primary;
s = [ col, parseInt(t, 10) || 0 ];
c.sortList.push(s);
t = $.inArray(s[1], o.order); // fixes issue #167
o.count = t >= 0 ? t : s[1] % (c.sortReset ? 3 : 2);
}
});
}
function getCachedSortType(parsers, i) {
return (parsers && parsers[i]) ? parsers[i].type || '' : '';
}
function initSort(table, cell, event){
if (table.isUpdating) {
// let any updates complete before initializing a sort
return setTimeout(function(){ initSort(table, cell, event); }, 50);
}
var arry, indx, col, order, s,
c = table.config,
key = !event[c.sortMultiSortKey],
$table = c.$table;
// Only call sortStart if sorting is enabled
$table.trigger("sortStart", table);
// get current column sort order
cell.count = event[c.sortResetKey] ? 2 : (cell.count + 1) % (c.sortReset ? 3 : 2);
// reset all sorts on non-current column - issue #30
if (c.sortRestart) {
indx = cell;
c.$headers.each(function() {
// only reset counts on columns that weren't just clicked on and if not included in a multisort
if (this !== indx && (key || !$(this).is('.' + ts.css.sortDesc + ',.' + ts.css.sortAsc))) {
this.count = -1;
}
});
}
// get current column index
indx = cell.column;
// user only wants to sort on one column
if (key) {
// flush the sort list
c.sortList = [];
if (c.sortForce !== null) {
arry = c.sortForce;
for (col = 0; col < arry.length; col++) {
if (arry[col][0] !== indx) {
c.sortList.push(arry[col]);
}
}
}
// add column to sort list
order = cell.order[cell.count];
if (order < 2) {
c.sortList.push([indx, order]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (col = 1; col < cell.colSpan; col++) {
c.sortList.push([indx + col, order]);
}
}
}
// multi column sorting
} else {
// get rid of the sortAppend before adding more - fixes issue #115 & #523
if (c.sortAppend && c.sortList.length > 1) {
for (col = 0; col < c.sortAppend.length; col++) {
s = ts.isValueInArray(c.sortAppend[col][0], c.sortList);
if (s >= 0) {
c.sortList.splice(s,1);
}
}
}
// the user has clicked on an already sorted column
if (ts.isValueInArray(indx, c.sortList) >= 0) {
// reverse the sorting direction
for (col = 0; col < c.sortList.length; col++) {
s = c.sortList[col];
order = c.$headers.filter('[data-column="' + s[0] + '"]:last')[0];
if (s[0] === indx) {
// order.count seems to be incorrect when compared to cell.count
s[1] = order.order[cell.count];
if (s[1] === 2) {
c.sortList.splice(col,1);
order.count = -1;
}
}
}
} else {
// add column to sort list array
order = cell.order[cell.count];
if (order < 2) {
c.sortList.push([indx, order]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (col = 1; col < cell.colSpan; col++) {
c.sortList.push([indx + col, order]);
}
}
}
}
}
if (c.sortAppend !== null) {
arry = c.sortAppend;
for (col = 0; col < arry.length; col++) {
if (arry[col][0] !== indx) {
c.sortList.push(arry[col]);
}
}
}
// sortBegin event triggered immediately before the sort
$table.trigger("sortBegin", table);
// setTimeout needed so the processing icon shows up
setTimeout(function(){
// set css for headers
setHeadersCss(table);
multisort(table);
appendToTable(table);
$table.trigger("sortEnd", table);
}, 1);
}
// sort multiple columns
function multisort(table) { /*jshint loopfunc:true */
var i, k, num, col, sortTime, colMax,
cache, order, sort, x, y,
dir = 0,
c = table.config,
cts = c.textSorter || '',
sortList = c.sortList,
l = sortList.length,
bl = table.tBodies.length;
if (c.serverSideSorting || isEmptyObject(c.cache)) { // empty table - fixes #206/#346
return;
}
if (c.debug) { sortTime = new Date(); }
for (k = 0; k < bl; k++) {
colMax = c.cache[k].colMax;
cache = c.cache[k].normalized;
cache.sort(function(a, b) {
// cache is undefined here in IE, so don't use it!
for (i = 0; i < l; i++) {
col = sortList[i][0];
order = sortList[i][1];
// sort direction, true = asc, false = desc
dir = order === 0;
if (c.sortStable && a[col] === b[col] && l === 1) {
return a[c.columns].order - b[c.columns].order;
}
// fallback to natural sort since it is more robust
num = /n/i.test(getCachedSortType(c.parsers, col));
if (num && c.strings[col]) {
// sort strings in numerical columns
if (typeof (c.string[c.strings[col]]) === 'boolean') {
num = (dir ? 1 : -1) * (c.string[c.strings[col]] ? -1 : 1);
} else {
num = (c.strings[col]) ? c.string[c.strings[col]] || 0 : 0;
}
// fall back to built-in numeric sort
// var sort = $.tablesorter["sort" + s](table, a[c], b[c], c, colMax[c], dir);
sort = c.numberSorter ? c.numberSorter(a[col], b[col], dir, colMax[col], table) :
ts[ 'sortNumeric' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], num, colMax[col], col, table);
} else {
// set a & b depending on sort direction
x = dir ? a : b;
y = dir ? b : a;
// text sort function
if (typeof(cts) === 'function') {
// custom OVERALL text sorter
sort = cts(x[col], y[col], dir, col, table);
} else if (typeof(cts) === 'object' && cts.hasOwnProperty(col)) {
// custom text sorter for a SPECIFIC COLUMN
sort = cts[col](x[col], y[col], dir, col, table);
} else {
// fall back to natural sort
sort = ts[ 'sortNatural' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], col, table, c);
}
}
if (sort) { return sort; }
}
return a[c.columns].order - b[c.columns].order;
});
}
if (c.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time", sortTime); }
}
function resortComplete($table, callback){
var table = $table[0];
if (table.isUpdating) {
$table.trigger('updateComplete');
}
if ($.isFunction(callback)) {
callback($table[0]);
}
}
function checkResort($table, flag, callback) {
var sl = $table[0].config.sortList;
// don't try to resort if the table is still processing
// this will catch spamming of the updateCell method
if (flag !== false && !$table[0].isProcessing && sl.length) {
$table.trigger("sorton", [sl, function(){
resortComplete($table, callback);
}, true]);
} else {
resortComplete($table, callback);
ts.applyWidget($table[0], false);
}
}
function bindMethods(table){
var c = table.config,
$table = c.$table;
// apply easy methods that trigger bound events
$table
.unbind('sortReset update updateRows updateCell updateAll addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join(c.namespace + ' '))
.bind("sortReset" + c.namespace, function(e, callback){
e.stopPropagation();
c.sortList = [];
setHeadersCss(table);
multisort(table);
appendToTable(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("updateAll" + c.namespace, function(e, resort, callback){
e.stopPropagation();
table.isUpdating = true;
ts.refreshWidgets(table, true, true);
ts.restoreHeaders(table);
buildHeaders(table);
ts.bindEvents(table, c.$headers, true);
bindMethods(table);
commonUpdate(table, resort, callback);
})
.bind("update" + c.namespace + " updateRows" + c.namespace, function(e, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
// update sorting (if enabled/disabled)
updateHeader(table);
commonUpdate(table, resort, callback);
})
.bind("updateCell" + c.namespace, function(e, cell, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
$table.find(c.selectorRemove).remove();
// get position from the dom
var v, t, row, icell,
$tb = $table.find('tbody'),
$cell = $(cell),
// update cache - format: function(s, table, cell, cellIndex)
// no closest in jQuery v1.2.6 - tbdy = $tb.index( $(cell).closest('tbody') ),$row = $(cell).closest('tr');
tbdy = $tb.index( $.fn.closest ? $cell.closest('tbody') : $cell.parents('tbody').filter(':first') ),
$row = $.fn.closest ? $cell.closest('tr') : $cell.parents('tr').filter(':first');
cell = $cell[0]; // in case cell is a jQuery object
// tbody may not exist if update is initialized while tbody is removed for processing
if ($tb.length && tbdy >= 0) {
row = $tb.eq(tbdy).find('tr').index( $row );
icell = $cell.index();
c.cache[tbdy].normalized[row][c.columns].$row = $row;
if (typeof c.extractors[icell].id === 'undefined') {
t = getElementText(table, cell, icell);
} else {
t = c.extractors[icell].format( getElementText(table, cell, icell), table, cell, icell );
}
v = c.parsers[icell].id === 'no-parser' ? '' :
c.parsers[icell].format( t, table, cell, icell );
c.cache[tbdy].normalized[row][icell] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v;
if ((c.parsers[icell].type || '').toLowerCase() === "numeric") {
// update column max value (ignore sign)
c.cache[tbdy].colMax[icell] = Math.max(Math.abs(v) || 0, c.cache[tbdy].colMax[icell] || 0);
}
checkResort($table, resort, callback);
}
})
.bind("addRows" + c.namespace, function(e, $row, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
if (isEmptyObject(c.cache)) {
// empty table, do an update instead - fixes #450
updateHeader(table);
commonUpdate(table, resort, callback);
} else {
$row = $($row).attr('role', 'row'); // make sure we're using a jQuery object
var i, j, l, t, v, rowData, cells,
rows = $row.filter('tr').length,
tbdy = $table.find('tbody').index( $row.parents('tbody').filter(':first') );
// fixes adding rows to an empty table - see issue #179
if (!(c.parsers && c.parsers.length)) {
buildParserCache(table);
}
// add each row
for (i = 0; i < rows; i++) {
l = $row[i].cells.length;
cells = [];
rowData = {
child: [],
$row : $row.eq(i),
order: c.cache[tbdy].normalized.length
};
// add each cell
for (j = 0; j < l; j++) {
if (typeof c.extractors[j].id === 'undefined') {
t = getElementText(table, $row[i].cells[j], j);
} else {
t = c.extractors[j].format( getElementText(table, $row[i].cells[j], j), table, $row[i].cells[j], j );
}
v = c.parsers[j].id === 'no-parser' ? '' :
c.parsers[j].format( t, table, $row[i].cells[j], j );
cells[j] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v;
if ((c.parsers[j].type || '').toLowerCase() === "numeric") {
// update column max value (ignore sign)
c.cache[tbdy].colMax[j] = Math.max(Math.abs(cells[j]) || 0, c.cache[tbdy].colMax[j] || 0);
}
}
// add the row data to the end
cells.push(rowData);
// update cache
c.cache[tbdy].normalized.push(cells);
}
// resort using current settings
checkResort($table, resort, callback);
}
})
.bind("updateComplete" + c.namespace, function(){
table.isUpdating = false;
})
.bind("sorton" + c.namespace, function(e, list, callback, init) {
var c = table.config;
e.stopPropagation();
$table.trigger("sortStart", this);
// update header count index
updateHeaderSortCount(table, list);
// set css for headers
setHeadersCss(table);
// fixes #346
if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); }
$table.trigger("sortBegin", this);
// sort the table and append it to the dom
multisort(table);
appendToTable(table, init);
$table.trigger("sortEnd", this);
ts.applyWidget(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("appendCache" + c.namespace, function(e, callback, init) {
e.stopPropagation();
appendToTable(table, init);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("updateCache" + c.namespace, function(e, callback){
// rebuild parsers
if (!(c.parsers && c.parsers.length)) {
buildParserCache(table);
}
// rebuild the cache map
buildCache(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("applyWidgetId" + c.namespace, function(e, id) {
e.stopPropagation();
ts.getWidgetById(id).format(table, c, c.widgetOptions);
})
.bind("applyWidgets" + c.namespace, function(e, init) {
e.stopPropagation();
// apply widgets
ts.applyWidget(table, init);
})
.bind("refreshWidgets" + c.namespace, function(e, all, dontapply){
e.stopPropagation();
ts.refreshWidgets(table, all, dontapply);
})
.bind("destroy" + c.namespace, function(e, c, cb){
e.stopPropagation();
ts.destroy(table, c, cb);
})
.bind("resetToLoadState" + c.namespace, function(){
// remove all widgets
ts.refreshWidgets(table, true, true);
// restore original settings; this clears out current settings, but does not clear
// values saved to storage.
c = $.extend(true, ts.defaults, c.originalSettings);
table.hasInitialized = false;
// setup the entire table again
ts.setup( table, c );
});
}
/* public methods */
ts.construct = function(settings) {
return this.each(function() {
var table = this,
// merge & extend config options
c = $.extend(true, {}, ts.defaults, settings);
// save initial settings
c.originalSettings = settings;
// create a table from data (build table widget)
if (!table.hasInitialized && ts.buildTable && this.tagName !== 'TABLE') {
// return the table (in case the original target is the table's container)
ts.buildTable(table, c);
} else {
ts.setup(table, c);
}
});
};
ts.setup = function(table, c) {
// if no thead or tbody, or tablesorter is already present, quit
if (!table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true) {
return c.debug ? log('ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized') : '';
}
var k = '',
$table = $(table),
m = $.metadata;
// initialization flag
table.hasInitialized = false;
// table is being processed flag
table.isProcessing = true;
// make sure to store the config object
table.config = c;
// save the settings where they read
$.data(table, "tablesorter", c);
if (c.debug) { $.data( table, 'startoveralltimer', new Date()); }
// removing this in version 3 (only supports jQuery 1.7+)
c.supportsDataObject = (function(version) {
version[0] = parseInt(version[0], 10);
return (version[0] > 1) || (version[0] === 1 && parseInt(version[1], 10) >= 4);
})($.fn.jquery.split("."));
// digit sort text location; keeping max+/- for backwards compatibility
c.string = { 'max': 1, 'min': -1, 'emptyMin': 1, 'emptyMax': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false };
// add table theme class only if there isn't already one there
if (!/tablesorter\-/.test($table.attr('class'))) {
k = (c.theme !== '' ? ' tablesorter-' + c.theme : '');
}
c.table = table;
c.$table = $table
.addClass(ts.css.table + ' ' + c.tableClass + k)
.attr('role', 'grid');
c.$headers = $table.find(c.selectorHeaders);
// give the table a unique id, which will be used in namespace binding
if (!c.namespace) {
c.namespace = '.tablesorter' + Math.random().toString(16).slice(2);
} else {
// make sure namespace starts with a period & doesn't have weird characters
c.namespace = '.' + c.namespace.replace(/\W/g,'');
}
c.$table.children().children('tr').attr('role', 'row');
c.$tbodies = $table.children('tbody:not(.' + c.cssInfoBlock + ')').attr({
'aria-live' : 'polite',
'aria-relevant' : 'all'
});
if (c.$table.find('caption').length) {
c.$table.attr('aria-labelledby', 'theCaption');
}
c.widgetInit = {}; // keep a list of initialized widgets
// change textExtraction via data-attribute
c.textExtraction = c.$table.attr('data-text-extraction') || c.textExtraction || 'basic';
// build headers
buildHeaders(table);
// fixate columns if the users supplies the fixedWidth option
// do this after theme has been applied
fixColumnWidth(table);
// try to auto detect column type, and store in tables config
buildParserCache(table);
// start total row count at zero
c.totalRows = 0;
// build the cache for the tbody cells
// delayInit will delay building the cache until the user starts a sort
if (!c.delayInit) { buildCache(table); }
// bind all header events and methods
ts.bindEvents(table, c.$headers, true);
bindMethods(table);
// get sort list from jQuery data or metadata
// in jQuery < 1.4, an error occurs when calling $table.data()
if (c.supportsDataObject && typeof $table.data().sortlist !== 'undefined') {
c.sortList = $table.data().sortlist;
} else if (m && ($table.metadata() && $table.metadata().sortlist)) {
c.sortList = $table.metadata().sortlist;
}
// apply widget init code
ts.applyWidget(table, true);
// if user has supplied a sort list to constructor
if (c.sortList.length > 0) {
$table.trigger("sorton", [c.sortList, {}, !c.initWidgets, true]);
} else {
setHeadersCss(table);
if (c.initWidgets) {
// apply widget format
ts.applyWidget(table, false);
}
}
// show processesing icon
if (c.showProcessing) {
$table
.unbind('sortBegin' + c.namespace + ' sortEnd' + c.namespace)
.bind('sortBegin' + c.namespace + ' sortEnd' + c.namespace, function(e) {
clearTimeout(c.processTimer);
ts.isProcessing(table);
if (e.type === 'sortBegin') {
c.processTimer = setTimeout(function(){
ts.isProcessing(table, true);
}, 500);
}
});
}
// initialized
table.hasInitialized = true;
table.isProcessing = false;
if (c.debug) {
ts.benchmark("Overall initialization time", $.data( table, 'startoveralltimer'));
}
$table.trigger('tablesorter-initialized', table);
if (typeof c.initialized === 'function') { c.initialized(table); }
};
ts.getColumnData = function(table, obj, indx, getCell){
if (typeof obj === 'undefined' || obj === null) { return; }
table = $(table)[0];
var result, $h, k,
c = table.config;
if (obj[indx]) {
return getCell ? obj[indx] : obj[c.$headers.index( c.$headers.filter('[data-column="' + indx + '"]:last') )];
}
for (k in obj) {
if (typeof k === 'string') {
if (getCell) {
// get header cell
$h = c.$headers.eq(indx).filter(k);
} else {
// get column indexed cell
$h = c.$headers.filter('[data-column="' + indx + '"]:last').filter(k);
}
if ($h.length) {
return obj[k];
}
}
}
return result;
};
// computeTableHeaderCellIndexes from:
// http://www.javascripttoolbox.com/lib/table/examples.php
// http://www.javascripttoolbox.com/temp/table_cellindex.html
ts.computeColumnIndex = function(trs) {
var matrix = [],
lookup = {},
cols = 0, // determine the number of columns
i, j, k, l, $cell, cell, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow;
for (i = 0; i < trs.length; i++) {
cells = trs[i].cells;
for (j = 0; j < cells.length; j++) {
cell = cells[j];
$cell = $(cell);
rowIndex = cell.parentNode.rowIndex;
cellId = rowIndex + "-" + $cell.index();
rowSpan = cell.rowSpan || 1;
colSpan = cell.colSpan || 1;
if (typeof(matrix[rowIndex]) === "undefined") {
matrix[rowIndex] = [];
}
// Find first available column in the first row
for (k = 0; k < matrix[rowIndex].length + 1; k++) {
if (typeof(matrix[rowIndex][k]) === "undefined") {
firstAvailCol = k;
break;
}
}
lookup[cellId] = firstAvailCol;
cols = Math.max(firstAvailCol, cols);
// add data-column
$cell.attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex
for (k = rowIndex; k < rowIndex + rowSpan; k++) {
if (typeof(matrix[k]) === "undefined") {
matrix[k] = [];
}
matrixrow = matrix[k];
for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
matrixrow[l] = "x";
}
}
}
}
// may not be accurate if # header columns !== # tbody columns
return cols + 1; // add one because it's a zero-based index
};
// *** Process table ***
// add processing indicator
ts.isProcessing = function(table, toggle, $ths) {
table = $(table);
var c = table[0].config,
// default to all headers
$h = $ths || table.find('.' + ts.css.header);
if (toggle) {
// don't use sortList if custom $ths used
if (typeof $ths !== 'undefined' && c.sortList.length > 0) {
// get headers from the sortList
$h = $h.filter(function(){
// get data-column from attr to keep compatibility with jQuery 1.2.6
return this.sortDisabled ? false : ts.isValueInArray( parseFloat($(this).attr('data-column')), c.sortList) >= 0;
});
}
table.add($h).addClass(ts.css.processing + ' ' + c.cssProcessing);
} else {
table.add($h).removeClass(ts.css.processing + ' ' + c.cssProcessing);
}
};
// detach tbody but save the position
// don't use tbody because there are portions that look for a tbody index (updateCell)
ts.processTbody = function(table, $tb, getIt){
table = $(table)[0];
var holdr;
if (getIt) {
table.isProcessing = true;
$tb.before('<span class="tablesorter-savemyplace"/>');
holdr = ($.fn.detach) ? $tb.detach() : $tb.remove();
return holdr;
}
holdr = $(table).find('span.tablesorter-savemyplace');
$tb.insertAfter( holdr );
holdr.remove();
table.isProcessing = false;
};
ts.clearTableBody = function(table) {
$(table)[0].config.$tbodies.children().detach();
};
ts.bindEvents = function(table, $headers, core){
table = $(table)[0];
var downTime,
c = table.config;
if (core !== true) {
c.$extraHeaders = c.$extraHeaders ? c.$extraHeaders.add($headers) : $headers;
}
// apply event handling to headers and/or additional headers (stickyheaders, scroller, etc)
$headers
// http://stackoverflow.com/questions/5312849/jquery-find-self;
.find(c.selectorSort).add( $headers.filter(c.selectorSort) )
.unbind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '))
.bind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '), function(e, external) {
var cell, type = e.type;
// only recognize left clicks or enter
if ( ((e.which || e.button) !== 1 && !/sort|keyup/.test(type)) || (type === 'keyup' && e.which !== 13) ) {
return;
}
// ignore long clicks (prevents resizable widget from initializing a sort)
if (type === 'mouseup' && external !== true && (new Date().getTime() - downTime > 250)) { return; }
// set timer on mousedown
if (type === 'mousedown') {
downTime = new Date().getTime();
return /(input|select|button|textarea)/i.test(e.target.tagName) ? '' : !c.cancelSelection;
}
if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); }
// jQuery v1.2.6 doesn't have closest()
cell = $.fn.closest ? $(this).closest('th, td')[0] : /TH|TD/.test(this.tagName) ? this : $(this).parents('th, td')[0];
// reference original table headers and find the same cell
cell = c.$headers[ $headers.index( cell ) ];
if (!cell.sortDisabled) {
initSort(table, cell, e);
}
});
if (c.cancelSelection) {
// cancel selection
$headers
.attr('unselectable', 'on')
.bind('selectstart', false)
.css({
'user-select': 'none',
'MozUserSelect': 'none' // not needed for jQuery 1.8+
});
}
};
// restore headers
ts.restoreHeaders = function(table){
var c = $(table)[0].config;
// don't use c.$headers here in case header cells were swapped
c.$table.find(c.selectorHeaders).each(function(i){
// only restore header cells if it is wrapped
// because this is also used by the updateAll method
if ($(this).find('.' + ts.css.headerIn).length){
$(this).html( c.headerContent[i] );
}
});
};
ts.destroy = function(table, removeClasses, callback){
table = $(table)[0];
if (!table.hasInitialized) { return; }
// remove all widgets
ts.refreshWidgets(table, true, true);
var $t = $(table), c = table.config,
$h = $t.find('thead:first'),
$r = $h.find('tr.' + ts.css.headerRow).removeClass(ts.css.headerRow + ' ' + c.cssHeaderRow),
$f = $t.find('tfoot:first > tr').children('th, td');
if (removeClasses === false && $.inArray('uitheme', c.widgets) >= 0) {
// reapply uitheme classes, in case we want to maintain appearance
$t.trigger('applyWidgetId', ['uitheme']);
$t.trigger('applyWidgetId', ['zebra']);
}
// remove widget added rows, just in case
$h.find('tr').not($r).remove();
// disable tablesorter
$t
.removeData('tablesorter')
.unbind('sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState '.split(' ').join(c.namespace + ' '));
c.$headers.add($f)
.removeClass( [ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone].join(' ') )
.removeAttr('data-column')
.removeAttr('aria-label')
.attr('aria-disabled', 'true');
$r.find(c.selectorSort).unbind('mousedown mouseup keypress '.split(' ').join(c.namespace + ' '));
ts.restoreHeaders(table);
$t.toggleClass(ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false);
// clear flag in case the plugin is initialized again
table.hasInitialized = false;
delete table.config.cache;
if (typeof callback === 'function') {
callback(table);
}
};
// *** sort functions ***
// regex used in natural sort
ts.regex = {
chunk : /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // chunk/tokenize numbers & letters
chunks: /(^\\0|\\0$)/, // replace chunks @ ends
hex: /^0x[0-9a-f]+$/i // hex
};
// Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed)
// this function will only accept strings, or you'll see "TypeError: undefined is not a function"
// I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall
ts.sortNatural = function(a, b) {
if (a === b) { return 0; }
var xN, xD, yN, yD, xF, yF, i, mx,
r = ts.regex;
// first try and sort Hex codes
if (r.hex.test(b)) {
xD = parseInt(a.match(r.hex), 16);
yD = parseInt(b.match(r.hex), 16);
if ( xD < yD ) { return -1; }
if ( xD > yD ) { return 1; }
}
// chunk/tokenize
xN = a.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0');
yN = b.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0');
mx = Math.max(xN.length, yN.length);
// natural sorting through split numeric strings and default strings
for (i = 0; i < mx; i++) {
// find floats not starting with '0', string or 0 if not defined
xF = isNaN(xN[i]) ? xN[i] || 0 : parseFloat(xN[i]) || 0;
yF = isNaN(yN[i]) ? yN[i] || 0 : parseFloat(yN[i]) || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; }
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
if (typeof xF !== typeof yF) {
xF += '';
yF += '';
}
if (xF < yF) { return -1; }
if (xF > yF) { return 1; }
}
return 0;
};
ts.sortNaturalAsc = function(a, b, col, table, c) {
if (a === b) { return 0; }
var e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; }
return ts.sortNatural(a, b);
};
ts.sortNaturalDesc = function(a, b, col, table, c) {
if (a === b) { return 0; }
var e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; }
return ts.sortNatural(b, a);
};
// basic alphabetical sort
ts.sortText = function(a, b) {
return a > b ? 1 : (a < b ? -1 : 0);
};
// return text string value by adding up ascii value
// so the text is somewhat sorted when using a digital sort
// this is NOT an alphanumeric sort
ts.getTextValue = function(a, num, mx) {
if (mx) {
// make sure the text value is greater than the max numerical value (mx)
var i, l = a ? a.length : 0, n = mx + num;
for (i = 0; i < l; i++) {
n += a.charCodeAt(i);
}
return num * n;
}
return 0;
};
ts.sortNumericAsc = function(a, b, num, mx, col, table) {
if (a === b) { return 0; }
var c = table.config,
e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; }
if (isNaN(a)) { a = ts.getTextValue(a, num, mx); }
if (isNaN(b)) { b = ts.getTextValue(b, num, mx); }
return a - b;
};
ts.sortNumericDesc = function(a, b, num, mx, col, table) {
if (a === b) { return 0; }
var c = table.config,
e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; }
if (isNaN(a)) { a = ts.getTextValue(a, num, mx); }
if (isNaN(b)) { b = ts.getTextValue(b, num, mx); }
return b - a;
};
ts.sortNumeric = function(a, b) {
return a - b;
};
// used when replacing accented characters during sorting
ts.characterEquivalents = {
"a" : "\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5", // áàâãäąå
"A" : "\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5", // ÁÀÂÃÄĄÅ
"c" : "\u00e7\u0107\u010d", // çćč
"C" : "\u00c7\u0106\u010c", // ÇĆČ
"e" : "\u00e9\u00e8\u00ea\u00eb\u011b\u0119", // éèêëěę
"E" : "\u00c9\u00c8\u00ca\u00cb\u011a\u0118", // ÉÈÊËĚĘ
"i" : "\u00ed\u00ec\u0130\u00ee\u00ef\u0131", // íìİîïı
"I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ
"o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö
"O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ
"ss": "\u00df", // ß (s sharp)
"SS": "\u1e9e", // ẞ (Capital sharp s)
"u" : "\u00fa\u00f9\u00fb\u00fc\u016f", // úùûüů
"U" : "\u00da\u00d9\u00db\u00dc\u016e" // ÚÙÛÜŮ
};
ts.replaceAccents = function(s) {
var a, acc = '[', eq = ts.characterEquivalents;
if (!ts.characterRegex) {
ts.characterRegexArray = {};
for (a in eq) {
if (typeof a === 'string') {
acc += eq[a];
ts.characterRegexArray[a] = new RegExp('[' + eq[a] + ']', 'g');
}
}
ts.characterRegex = new RegExp(acc + ']');
}
if (ts.characterRegex.test(s)) {
for (a in eq) {
if (typeof a === 'string') {
s = s.replace( ts.characterRegexArray[a], a );
}
}
}
return s;
};
// *** utilities ***
ts.isValueInArray = function(column, arry) {
var indx, len = arry.length;
for (indx = 0; indx < len; indx++) {
if (arry[indx][0] === column) {
return indx;
}
}
return -1;
};
ts.addParser = function(parser) {
var i, l = ts.parsers.length, a = true;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === parser.id.toLowerCase()) {
a = false;
}
}
if (a) {
ts.parsers.push(parser);
}
};
ts.getParserById = function(name) {
/*jshint eqeqeq:false */
if (name == 'false') { return false; }
var i, l = ts.parsers.length;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) {
return ts.parsers[i];
}
}
return false;
};
ts.addWidget = function(widget) {
ts.widgets.push(widget);
};
ts.hasWidget = function(table, name){
table = $(table);
return table.length && table[0].config && table[0].config.widgetInit[name] || false;
};
ts.getWidgetById = function(name) {
var i, w, l = ts.widgets.length;
for (i = 0; i < l; i++) {
w = ts.widgets[i];
if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) {
return w;
}
}
};
ts.applyWidget = function(table, init) {
table = $(table)[0]; // in case this is called externally
var c = table.config,
wo = c.widgetOptions,
widgets = [],
time, w, wd;
// prevent numerous consecutive widget applications
if (init !== false && table.hasInitialized && (table.isApplyingWidgets || table.isUpdating)) { return; }
if (c.debug) { time = new Date(); }
if (c.widgets.length) {
table.isApplyingWidgets = true;
// ensure unique widget ids
c.widgets = $.grep(c.widgets, function(v, k){
return $.inArray(v, c.widgets) === k;
});
// build widget array & add priority as needed
$.each(c.widgets || [], function(i,n){
wd = ts.getWidgetById(n);
if (wd && wd.id) {
// set priority to 10 if not defined
if (!wd.priority) { wd.priority = 10; }
widgets[i] = wd;
}
});
// sort widgets by priority
widgets.sort(function(a, b){
return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1;
});
// add/update selected widgets
$.each(widgets, function(i,w){
if (w) {
if (init || !(c.widgetInit[w.id])) {
// set init flag first to prevent calling init more than once (e.g. pager)
c.widgetInit[w.id] = true;
if (w.hasOwnProperty('options')) {
wo = table.config.widgetOptions = $.extend( true, {}, w.options, wo );
}
if (w.hasOwnProperty('init')) {
w.init(table, w, c, wo);
}
}
if (!init && w.hasOwnProperty('format')) {
w.format(table, c, wo, false);
}
}
});
}
setTimeout(function(){
table.isApplyingWidgets = false;
}, 0);
if (c.debug) {
w = c.widgets.length;
benchmark("Completed " + (init === true ? "initializing " : "applying ") + w + " widget" + (w !== 1 ? "s" : ""), time);
}
};
ts.refreshWidgets = function(table, doAll, dontapply) {
table = $(table)[0]; // see issue #243
var i, c = table.config,
cw = c.widgets,
w = ts.widgets, l = w.length;
// remove previous widgets
for (i = 0; i < l; i++){
if ( w[i] && w[i].id && (doAll || $.inArray( w[i].id, cw ) < 0) ) {
if (c.debug) { log( 'Refeshing widgets: Removing "' + w[i].id + '"' ); }
// only remove widgets that have been initialized - fixes #442
if (w[i].hasOwnProperty('remove') && c.widgetInit[w[i].id]) {
w[i].remove(table, c, c.widgetOptions);
c.widgetInit[w[i].id] = false;
}
}
}
if (dontapply !== true) {
ts.applyWidget(table, doAll);
}
};
// get sorter, string, empty, etc options for each column from
// jQuery data, metadata, header option or header class name ("sorter-false")
// priority = jQuery data > meta > headers option > header class name
ts.getData = function(h, ch, key) {
var val = '', $h = $(h), m, cl;
if (!$h.length) { return ''; }
m = $.metadata ? $h.metadata() : false;
cl = ' ' + ($h.attr('class') || '');
if (typeof $h.data(key) !== 'undefined' || typeof $h.data(key.toLowerCase()) !== 'undefined'){
// "data-lockedOrder" is assigned to "lockedorder"; but "data-locked-order" is assigned to "lockedOrder"
// "data-sort-initial-order" is assigned to "sortInitialOrder"
val += $h.data(key) || $h.data(key.toLowerCase());
} else if (m && typeof m[key] !== 'undefined') {
val += m[key];
} else if (ch && typeof ch[key] !== 'undefined') {
val += ch[key];
} else if (cl !== ' ' && cl.match(' ' + key + '-')) {
// include sorter class name "sorter-text", etc; now works with "sorter-my-custom-parser"
val = cl.match( new RegExp('\\s' + key + '-([\\w-]+)') )[1] || '';
}
return $.trim(val);
};
ts.formatFloat = function(s, table) {
if (typeof s !== 'string' || s === '') { return s; }
// allow using formatFloat without a table; defaults to US number format
var i,
t = table && table.config ? table.config.usNumberFormat !== false :
typeof table !== "undefined" ? table : true;
if (t) {
// US Format - 1,234,567.89 -> 1234567.89
s = s.replace(/,/g,'');
} else {
// German Format = 1.234.567,89 -> 1234567.89
// French Format = 1 234 567,89 -> 1234567.89
s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.');
}
if(/^\s*\([.\d]+\)/.test(s)) {
// make (#) into a negative number -> (10) = -10
s = s.replace(/^\s*\(([.\d]+)\)/, '-$1');
}
i = parseFloat(s);
// return the text instead of zero
return isNaN(i) ? $.trim(s) : i;
};
ts.isDigit = function(s) {
// replace all unwanted chars and match
return isNaN(s) ? (/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g, '')) : true;
};
}()
});
// make shortcut
var ts = $.tablesorter;
// extend plugin scope
$.fn.extend({
tablesorter: ts.construct
});
// add default parsers
ts.addParser({
id: 'no-parser',
is: function() {
return false;
},
format: function() {
return '';
},
type: 'text'
});
ts.addParser({
id: "text",
is: function() {
return true;
},
format: function(s, table) {
var c = table.config;
if (s) {
s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s );
s = c.sortLocaleCompare ? ts.replaceAccents(s) : s;
}
return s;
},
type: "text"
});
ts.addParser({
id: "digit",
is: function(s) {
return ts.isDigit(s);
},
format: function(s, table) {
var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table);
return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s;
},
type: "numeric"
});
ts.addParser({
id: "currency",
is: function(s) {
return (/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s || '').replace(/[+\-,. ]/g,'')); // £$€¤¥¢
},
format: function(s, table) {
var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table);
return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s;
},
type: "numeric"
});
ts.addParser({
id: "ipAddress",
is: function(s) {
return (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s);
},
format: function(s, table) {
var i, a = s ? s.split(".") : '',
r = "",
l = a.length;
for (i = 0; i < l; i++) {
r += ("00" + a[i]).slice(-3);
}
return s ? ts.formatFloat(r, table) : s;
},
type: "numeric"
});
ts.addParser({
id: "url",
is: function(s) {
return (/^(https?|ftp|file):\/\//).test(s);
},
format: function(s) {
return s ? $.trim(s.replace(/(https?|ftp|file):\/\//, '')) : s;
},
type: "text"
});
ts.addParser({
id: "isoDate",
is: function(s) {
return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || s) : "", table) : s;
},
type: "numeric"
});
ts.addParser({
id: "percent",
is: function(s) {
return (/(\d\s*?%|%\s*?\d)/).test(s) && s.length < 15;
},
format: function(s, table) {
return s ? ts.formatFloat(s.replace(/%/g, ""), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "usLongDate",
is: function(s) {
// two digit years are not allowed cross-browser
// Jan 01, 2013 12:34:56 PM or 01 Jan 2013
return (/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s) || (/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat( (new Date(s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd"
is: function(s) {
// testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included
return (/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/).test((s || '').replace(/\s+/g," ").replace(/[\-.,]/g, "/"));
},
format: function(s, table, cell, cellIndex) {
if (s) {
var c = table.config,
ci = c.$headers.filter('[data-column=' + cellIndex + ']:last'),
format = ci.length && ci[0].dateFormat || ts.getData( ci, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat') || c.dateFormat;
s = s.replace(/\s+/g," ").replace(/[\-.,]/g, "/"); // escaped - because JSHint in Firefox was showing it as an error
if (format === "mmddyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2");
} else if (format === "ddmmyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1");
} else if (format === "yyyymmdd") {
s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3");
}
}
return s ? ts.formatFloat( (new Date(s).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "time",
is: function(s) {
return (/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat( (new Date("2000/01/01 " + s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "metadata",
is: function() {
return false;
},
format: function(s, table, cell) {
var c = table.config,
p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
return $(cell).metadata()[p];
},
type: "numeric"
});
// add default widgets
ts.addWidget({
id: "zebra",
priority: 90,
format: function(table, c, wo) {
var $tb, $tv, $tr, row, even, time, k, l,
child = new RegExp(c.cssChildRow, 'i'),
b = c.$tbodies;
if (c.debug) {
time = new Date();
}
for (k = 0; k < b.length; k++ ) {
// loop through the visible rows
$tb = b.eq(k);
l = $tb.children('tr').length;
if (l > 1) {
row = 0;
$tv = $tb.children('tr:visible').not(c.selectorRemove);
// revered back to using jQuery each - strangely it's the fastest method
/*jshint loopfunc:true */
$tv.each(function(){
$tr = $(this);
// style children rows the same way the parent row was styled
if (!child.test(this.className)) { row++; }
even = (row % 2 === 0);
$tr.removeClass(wo.zebra[even ? 1 : 0]).addClass(wo.zebra[even ? 0 : 1]);
});
}
}
if (c.debug) {
ts.benchmark("Applying Zebra widget", time);
}
},
remove: function(table, c, wo){
var k, $tb,
b = c.$tbodies,
rmv = (wo.zebra || [ "even", "odd" ]).join(' ');
for (k = 0; k < b.length; k++ ){
$tb = $.tablesorter.processTbody(table, b.eq(k), true); // remove tbody
$tb.children().removeClass(rmv);
$.tablesorter.processTbody(table, $tb, false); // restore tbody
}
}
});
})(jQuery);
return module.exports;
}).call(this);
// src/js/aui/tables-sortable.js
(typeof window === 'undefined' ? global : window).__118945205868b7541cf0a75d6522abd5 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__f1a3fa76609e6d40a55157a38f5d9723;
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_SORT_OPTIONS = {
sortMultiSortKey: '',
headers: {},
debug: false,
tabIndex: false
};
function sortTable($table) {
var options = DEFAULT_SORT_OPTIONS;
$table.find('th').each(function (index, header) {
var $header = (0, _jquery2.default)(header);
options.headers[index] = {};
if ($header.hasClass('aui-table-column-unsortable')) {
options.headers[index].sorter = false;
} else {
$header.attr('tabindex', '0');
$header.wrapInner("<span class='aui-table-header-content'/>");
if ($header.hasClass('aui-table-column-issue-key')) {
options.headers[index].sorter = 'issue-key';
}
}
});
$table.tablesorter(options);
}
var tablessortable = {
setup: function setup() {
/*
This parser is used for issue keys in the format <PROJECT_KEY>-<ISSUE_NUMBER>, where <PROJECT_KEY> is a maximum
10 character string with characters(A-Z). Assumes that issue number is no larger than 999,999. e.g. not more
than a million issues.
This pads the issue key to allow for proper string sorting so that the project key is always 10 characters and the
issue number is always 6 digits. e.g. it appends the project key '.' until it is 10 characters long and prepends 0
so that the issue number is 6 digits long. e.g. CONF-102 == CONF......000102. This is to allow proper string sorting.
*/
_jquery2.default.tablesorter.addParser({
id: 'issue-key',
is: function is() {
return false;
},
format: function format(s) {
var keyComponents = s.split('-');
var projectKey = keyComponents[0];
var issueNumber = keyComponents[1];
var PROJECT_KEY_TEMPLATE = '..........';
var ISSUE_NUMBER_TEMPLATE = '000000';
var stringRepresentation = (projectKey + PROJECT_KEY_TEMPLATE).slice(0, PROJECT_KEY_TEMPLATE.length);
stringRepresentation += (ISSUE_NUMBER_TEMPLATE + issueNumber).slice(-ISSUE_NUMBER_TEMPLATE.length);
return stringRepresentation;
},
type: 'text'
});
/*
Text parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is not set
or set to 'text'.
*/
_jquery2.default.tablesorter.addParser({
id: 'textSortAttributeParser',
is: function is(nodeValue, table, node) {
return node.hasAttribute('data-sort-value') && (!node.hasAttribute('data-sort-type') || node.getAttribute('data-sort-type') === 'text');
},
format: function format(nodeValue, table, node, offset) {
return node.getAttribute('data-sort-value');
},
type: 'text'
});
/*
Numeric parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is set
to 'numeric'.
*/
_jquery2.default.tablesorter.addParser({
id: 'numericSortAttributeParser',
is: function is(nodeValue, table, node) {
return node.getAttribute('data-sort-type') === 'numeric' && node.hasAttribute('data-sort-value');
},
format: function format(nodeValue, table, node, offset) {
return node.getAttribute('data-sort-value');
},
type: 'numeric'
});
(0, _jquery2.default)('.aui-table-sortable').each(function () {
sortTable((0, _jquery2.default)(this));
});
},
setTableSortable: function setTableSortable($table) {
sortTable($table);
}
};
(0, _jquery2.default)(tablessortable.setup);
(0, _globalize2.default)('tablessortable', tablessortable);
exports.default = tablessortable;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/tipsy.js
(typeof window === 'undefined' ? global : window).__4887de1a729bad7b23da6129072d68ee = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
__dbb945ae8033589d400f8c63e7d01524;
return module.exports;
}).call(this);
// src/js/aui/toggle.js
(typeof window === 'undefined' ? global : window).__f243ae302e1f6512eaf4fb7ada716add = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
__313e15322266d7b6cc6ffb039891d9ce;
__6999efc8461cc8bcf32a985dbca81aa1;
var _attributes = __8f74d35e1223c8eb9f34b79717e74706;
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _enforcer = __65a8b3ca1b55232381cf1e189f6e2c47;
var _enforcer2 = _interopRequireDefault(_enforcer);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getInput(element) {
return element._input || (element._input = element.querySelector('input'));
}
function removedAttributeHandler(attributeName, element) {
getInput(element).removeAttribute(attributeName);
}
function fallbackAttributeHandler(attributeName, element, change) {
getInput(element).setAttribute(attributeName, change.newValue);
}
function getAttributeHandler(attributeName) {
return {
removed: removedAttributeHandler.bind(this, attributeName),
fallback: fallbackAttributeHandler.bind(this, attributeName)
};
}
var formAttributeHandler = {
removed: function removed(element) {
removedAttributeHandler.call(this, 'form', element);
element._formId = null;
},
fallback: function fallback(element, change) {
fallbackAttributeHandler.call(this, 'form', element, change);
element._formId = change.newValue;
}
};
var idAttributeHandler = {
removed: removedAttributeHandler.bind(undefined, 'id'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('id', '' + change.newValue + _constants.INPUT_SUFFIX);
}
};
var checkedAttributeHandler = {
removed: function removed(element) {
removedAttributeHandler.call(this, 'checked', element);
getInput(element).checked = false;
},
fallback: function fallback(element, change) {
fallbackAttributeHandler.call(this, 'checked', element, change);
getInput(element).checked = true;
}
};
var labelHandler = {
removed: function removed(element) {
getInput(element).removeAttribute('aria-label');
},
fallback: function fallback(element, change) {
getInput(element).setAttribute('aria-label', change.newValue);
}
};
function clickHandler(element, e) {
if (!element.disabled && !element.busy && e.target !== element._input) {
element._input.click();
}
(0, _attributes.setBooleanAttribute)(element, 'checked', getInput(element).checked);
}
function setDisabledForLabels(element, disabled) {
if (!element.id) {
return;
}
Array.prototype.forEach.call(document.querySelectorAll('aui-label[for="' + element.id + '"]'), function (el) {
el.disabled = disabled;
});
}
/**
* Workaround to prevent pressing SPACE on busy state.
* Preventing click event still makes the toggle flip and revert back.
* So on CSS side, the input has "pointer-events: none" on busy state.
*/
function bindEventsToInput(element) {
element._input.addEventListener('keydown', function (e) {
if (element.busy && e.keyCode === _keyCode2.default.SPACE) {
e.preventDefault();
}
});
// prevent toggle can be trigger through SPACE key on Firefox
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
element._input.addEventListener('click', function (e) {
if (element.busy) {
e.preventDefault();
}
});
}
}
(0, _skate2.default)('aui-toggle', {
template: (0, _skatejsTemplateHtml2.default)('<input type="checkbox" class="aui-toggle-input">', '<span class="aui-toggle-view">', '<span class="aui-toggle-tick aui-icon aui-icon-small aui-iconfont-success"></span>', '<span class="aui-toggle-cross aui-icon aui-icon-small aui-iconfont-close-dialog"></span>', '</span>'),
created: function created(element) {
element._input = getInput(element); // avoid using _input in attribute handlers
element._tick = element.querySelector('.aui-toggle-tick');
element._cross = element.querySelector('.aui-toggle-cross');
(0, _jquery2.default)(element._input).tooltip({
title: function title() {
return this.checked ? this.getAttribute('tooltip-on') : this.getAttribute('tooltip-off');
},
gravity: 's',
hoverable: false
});
bindEventsToInput(element);
},
attached: function attached(element) {
(0, _enforcer2.default)(element).attributeExists('label');
},
events: {
click: clickHandler
},
attributes: {
id: idAttributeHandler,
checked: checkedAttributeHandler,
disabled: getAttributeHandler('disabled'),
form: formAttributeHandler,
name: getAttributeHandler('name'),
value: getAttributeHandler('value'),
'tooltip-on': {
value: AJS.I18n.getText('aui.toggle.on'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('tooltip-on', change.newValue || AJS.I18n.getText('aui.toggle.on'));
}
},
'tooltip-off': {
value: AJS.I18n.getText('aui.toggle.off'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('tooltip-off', change.newValue || AJS.I18n.getText('aui.toggle.off'));
}
},
label: labelHandler
},
prototype: {
focus: function focus() {
this._input.focus();
return this;
},
get checked() {
return this._input.checked;
},
set checked(value) {
// Need to explicitly set the property on the checkbox because the
// checkbox's property doesn't change with it's attribute after it
// is clicked.
this._input.checked = value;
return (0, _attributes.setBooleanAttribute)(this, 'checked', value);
},
get disabled() {
return this._input.disabled;
},
set disabled(value) {
return (0, _attributes.setBooleanAttribute)(this, 'disabled', value);
},
get form() {
return document.getElementById(this._formId);
},
set form(value) {
formAttributeHandler.fallback.call(this, this, { newValue: value || null });
return this.form;
},
get name() {
return this._input.name;
},
set name(value) {
this.setAttribute('name', value);
return value;
},
get value() {
return this._input.value;
},
set value(value) {
// Setting the value of an input to null sets it to empty string.
this.setAttribute('value', value === null ? '' : value);
return value;
},
get busy() {
return this._input.getAttribute('aria-busy') === 'true';
},
set busy(value) {
(0, _attributes.setBooleanAttribute)(this, 'busy', value);
if (value) {
this._input.setAttribute('aria-busy', 'true');
this._input.indeterminate = true;
if (this.checked) {
(0, _jquery2.default)(this._input).addClass('indeterminate-checked');
(0, _jquery2.default)(this._tick).spin({ zIndex: null });
} else {
(0, _jquery2.default)(this._cross).spin({ zIndex: null, color: 'black' });
}
} else {
(0, _jquery2.default)(this._input).removeClass('indeterminate-checked');
this._input.indeterminate = false;
this._input.removeAttribute('aria-busy');
(0, _jquery2.default)(this._cross).spinStop();
(0, _jquery2.default)(this._tick).spinStop();
}
setDisabledForLabels(this, !!value);
return value;
}
}
});
return module.exports;
}).call(this);
// src/js/aui/trigger.js
(typeof window === 'undefined' ? global : window).__6575f5dae6f74a5f7933cb7c2b4fcebb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isNestedAnchor(trigger, target) {
var $closestAnchor = (0, _jquery2.default)(target).closest('a[href]', trigger);
return !!$closestAnchor.length && $closestAnchor[0] !== trigger;
}
function findControlled(trigger) {
return document.getElementById(trigger.getAttribute('aria-controls'));
}
function triggerMessage(trigger, e) {
if (trigger.isEnabled()) {
var component = findControlled(trigger);
if (component && component.message) {
component.message(e);
}
}
}
(0, _skate2.default)('data-aui-trigger', {
type: _skate2.default.type.ATTRIBUTE,
events: {
click: function click(trigger, e) {
if (!isNestedAnchor(trigger, e.target)) {
triggerMessage(trigger, e);
e.preventDefault();
}
},
mouseenter: function mouseenter(trigger, e) {
triggerMessage(trigger, e);
},
mouseleave: function mouseleave(trigger, e) {
triggerMessage(trigger, e);
},
focus: function focus(trigger, e) {
triggerMessage(trigger, e);
},
blur: function blur(trigger, e) {
triggerMessage(trigger, e);
}
},
prototype: {
disable: function disable() {
this.setAttribute('aria-disabled', 'true');
},
enable: function enable() {
this.setAttribute('aria-disabled', 'false');
},
isEnabled: function isEnabled() {
return this.getAttribute('aria-disabled') !== 'true';
}
}
});
(0, _amdify2.default)('aui/trigger');
return module.exports;
}).call(this);
// src/js/aui/truncating-progressive-data-set.js
(typeof window === 'undefined' ? global : window).__ca2b25ca788dc66f3403f1141687f275 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _progressiveDataSet = __bc3aa98a1624c420c64de6459784d4cc;
var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TruncatingProgressiveDataSet = _progressiveDataSet2.default.extend({
/**
* This is a subclass of ProgressiveDataSet. It differs from the superclass
* in that it works on large data sets where the server truncates results.
*
* Rather than determining whether to request more information based on its cache,
* it uses the size of the response.
*
* @example
* var source = new TruncatingProgressiveDataSet([], {
* model: Backbone.Model.extend({ idAttribute: "username" }),
* queryEndpoint: "/jira/rest/latest/users",
* queryParamKey: "username",
* matcher: function(model, query) {
* return _.startsWith(model.get('username'), query);
* },
* maxResponseSize: 20
* });
* source.on('respond', doStuffWithMatchingResults);
* source.query('john');
*/
initialize: function initialize(models, options) {
this._maxResponseSize = options.maxResponseSize;
_progressiveDataSet2.default.prototype.initialize.call(this, models, options);
},
shouldGetMoreResults: function shouldGetMoreResults(results) {
var response = this.findQueryResponse(this.value);
return !response || response.length === this._maxResponseSize;
},
/**
* Returns the response for the given query.
*
* The default implementation assumes that the endpoint's search algorithm is a prefix
* matcher.
*
* @param query the value to find existing responses
* @return {Object[]} an array of values representing the IDs of the models provided by the response for the given query.
* Null is returned if no response is found.
*/
findQueryResponse: function findQueryResponse(query) {
while (query) {
var response = this.findQueryCache(query);
if (response) {
return response;
}
query = query.substr(0, query.length - 1);
}
return null;
}
});
(0, _globalize2.default)('TruncatingProgressiveDataSet', TruncatingProgressiveDataSet);
exports.default = TruncatingProgressiveDataSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui-experimental.js
(typeof window === 'undefined' ? global : window).__150b2bcd52fe83736fc6bc2287e90b75 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
__452d3f8e5d643ab60faf3f564b8276d8;
__e7296db63088f504f190097510a8efb3;
__133851082a1337b5710e5a2aa98258e9;
__bf3c38e4a0e7481b849a297fccf30258;
__3ac567a4ab4b829d5c6e6c81df33cbe8;
__f165ad68f415362651d0d7f733fcdcea;
__7c68b94bd1e7e5a2f72d197f55d1d459;
__bd4ecc7f267c4325495affa1d72b9196;
__7904d2f802801befa81e22aff0bd1fb6;
__ef3494fdb79b0ce378f14c1810d48a68;
__bc3aa98a1624c420c64de6459784d4cc;
__b12fa1032568f0d561e20a44ba70067a;
__d9778e9495b7a4889d0567cf2b8e1182;
__e9e07e92893b0b7f9f3e6e2ffe018c96;
__1e2a7fafeebd870fc623ea9cf84e84eb;
__c7e0d50b6a65bf58a28e1b310881043e;
__dfd5f5c723e08e5f95e38718fe4f73eb;
__810b6deefd6627f937e4a4d2fae0520a;
__313e15322266d7b6cc6ffb039891d9ce;
__118945205868b7541cf0a75d6522abd5;
__4887de1a729bad7b23da6129072d68ee;
__f243ae302e1f6512eaf4fb7ada716add;
__6999efc8461cc8bcf32a985dbca81aa1;
__6575f5dae6f74a5f7933cb7c2b4fcebb;
__ca2b25ca788dc66f3403f1141687f275;
exports.default = window.AJS;
module.exports = exports['default'];
return module.exports;
}).call(this); |
web/src/components/tooltips/lowcarboninfotooltip.js | corradio/electricitymap | import React from 'react';
import { useTranslation } from '../../helpers/translation';
import Tooltip from '../tooltip';
const LowCarbonInfoTooltip = ({ position, onClose }) => {
const { __ } = useTranslation();
return (
<Tooltip id="lowcarb-info-tooltip" position={position} onClose={onClose}>
<b>{__('tooltips.lowcarbon')}</b>
<br />
<small>{__('tooltips.lowCarbDescription')}</small>
<br />
</Tooltip>
);
};
export default LowCarbonInfoTooltip;
|
user_guide/searchindex.js | jds8899/messenger | Search.setIndex({envversion:42,terms:{represent:[25,110,13,73],mybackup:69,yellow:[6,124],poorli:86,four:[144,82,49,130,50,120,116,125,119],prefix:[82,89,2,29],oldest:125,hate:126,optimize_databas:69,forget:[46,98],whose:29,accur:[0,29,109,146,37,88],aug:86,emailaddress:46,my_control:[96,105],site_url:[91,75,7,29],illustr:[128,91,144],swap:[37,82,89,105,29],up8:86,under:[137,10,89,73,144,29,92,60,30,31,134,104,27,98,126,100,101],up6:86,lord:86,up4:86,up5:86,up2:86,spec:91,myselect:87,up1:86,merchant:71,pg_escape_str:29,kudo:29,everi:[56,48,131,19,141,49,40,73,144,8,134,135,117,105,98,136,38,101],risk:[98,123,29],"void":[132,82,41,7,85,125,88,91,49,92,51,98,100,101,138,139,107,29,110,75,116,37],internet:[30,91,29],mime_typ:92,del_dir:109,stripslash:[130,29],upstream:29,start_cach:[144,29],applicationconfig:120,set_templ:[138,119],rename_t:[70,29],total_seg:[145,29],ci_db_query_build:144,fopen_write_cr:108,email_attachment_unred:29,preg_match:29,csrf_hash:94,raw_data:73,cmd:45,upload:[87,47,96,50,29],previou:[10,51,30,47,29],sri:86,vector:[73,29],red:[137,140,145,125,6,124,9,46,119],wednesdai:119,enjoy:133,mysqli_driv:32,zlib:29,up35:86,abil:[27,29,120,73,117,101],direct:[81,144,29,50,74,75,9,134],str_repeat:[6,130,30,29],enjoi:[57,50],dowload:16,second:[132,0,2,5,93,41,7,82,87,85,44,86,9,46,11,91,129,130,13,51,131,96,6,98,135,72,138,19,139,102,60,21,103,140,143,104,144,107,141,142,23,69,70,29,109,92,30,75,145,76,147,110,101],aggreg:82,clear_var:[103,29],kaliningrad:86,eldoc:74,even:[82,120,7,9,87,46,127,12,49,92,52,134,88,136,59,105,141,27,29,73,44,145,146],hide:29,date_rss:86,item2:[98,30],neg:[120,5,98,29],get_extens:29,item1:98,calcul:[49,37,82,29],poison:29,yoursit:91,blur:39,num_tag_open:56,"new":[0,81,3,5,120,7,134,123,136,44,86,9,46,126,88,47,90,91,129,49,50,143,94,95,96,97,52,53,98,15,16,17,101,56,19,115,66,60,68,104,105,144,107,65,27,67,23,69,70,29,110,30,31,75,145,32,33,34,114,35,61,149,118,148,142,150],net:[29,60,104,134,54,100],ever:[87,125,134],groupid:120,metadata:84,blog_model:72,med:87,elimin:[110,146,29],kilobyt:123,behavior:[0,29],get_month_nam:19,form_button:[87,29],never:[0,129,29,120,110,30,134,104,105,98],last_row:51,here:[0,1,73,5,120,93,87,123,124,44,45,46,11,91,129,49,13,51,131,143,96,6,98,100,72,56,138,19,136,139,142,21,22,103,62,140,68,134,65,27,23,144,29,109,92,30,74,75,146,116,39,37,101,148,119],met:[25,98,60,73],directory_map:[11,29],smtp_timeout:[23,29],ci_calendar:19,path:[11,69,139,29,109,40,72,41,31,83,82,140,85,124,45,89,141,100,127],up45:86,sess_table_nam:[98,30],interpret:29,get_smiley_link:13,forum:[126,136,133,8],row_start:119,anymor:29,characterss:116,loos:[27,48,138,59,120,6],precis:[37,147,31,29],datetim:[91,86,29],"_output":[0,29],niue:86,permit:[0,2,3,40,41,87,123,124,9,46,10,89,63,92,93,6,53,98,100,101,125,59,102,144,143,104,91,107,23,69,70,71,29,73,31,145,76,36,37,119],"_fetch_from_arrai":29,blog_config:7,heading_title_cel:19,"_cooki":[101,30,134,29],portabl:[87,2,75],http_x_client_ip:[101,29],message_kei:132,myanmar:86,get_cooki:[101,85,30,29],another_mark_start:37,invas:29,unix:[19,29,120,60,86,98,101],cell_start:119,strai:29,mysqli:[29,89,141,82,30,32,64,72],newspac:29,cont:23,txt:[69,139,29,102,135,107,100],unit:[47,111,136,86,29],highli:[48,31,100],set_profiler_sect:[77,92],describ:[5,73,120,41,7,123,9,46,126,146,49,13,14,134,136,21,68,106,26,23,144,72,29,31,77,50,119],would:[132,0,81,39,120,7,9,123,87,117,44,86,68,45,46,88,146,89,12,49,130,50,93,14,6,53,98,127,99,56,138,19,142,103,28,105,25,107,27,131,23,144,29,92,72,75,145,34,110,37,134,119],information_about_someth:120,afterward:[123,73,29],get_filenam:[109,29],dnt:29,program:[73,64],call:[136,31,29],asset:[5,134],typo:[3,29],recommend:[142,23,12,29,120,58,103,73,8,146,123,143,134,136,148,100,64],old_nam:70,protect_braced_quot:20,care:[108,0,143,82,60,73,22,25,9,98,141,101],type:[79,5,1,82,120,40,41,31,43,87,85,117,44,86,9,121,11,12,129,130,13,51,95,97,93,134,16,6,114,137,139,102,89,140,144,25,63,147,65,142,28,69,70,29,109,72,74,42,75,76,113,100,36],until:[56,92,29,30,31,85,98,46,37,136],uniqid:29,set_tempdata:[98,29],error_php:65,unescap:29,harden:[100,29],product_id_rul:125,inflect:29,notif:29,error_messag:132,notic:[39,13,120,41,123,124,9,46,91,129,49,92,98,138,19,21,22,144,71,29,110,73,146,116,37,119],unbuffered_row:[51,29],warn:[49,98,120,53,29],glass:125,start_dai:19,exce:46,stdclass:51,wm_opac:49,up7:86,last_tag_clos:56,hold:[73,136,104,29],wma:29,must:[132,0,80,2,3,39,120,93,41,73,87,123,124,86,9,46,126,89,91,72,129,49,13,51,77,143,96,53,98,54,18,138,125,19,60,103,148,140,81,104,105,25,144,107,141,108,23,69,70,29,109,92,30,74,75,34,50,116,37,136,134],composer_autoload:[40,29],sha256:73,join:[120,98,144,29],some_t:[43,51,44],setup:[25,120,54,136],work:[10,136,29],up3:86,krasnoyarsk:86,form_open:[29,22,125,97,87,46,135],sharp:39,undeliv:23,show_other_dai:19,abridg:86,root:[65,0,89,69,136,109,50,93,21,123,98,127,101],a_filter_uri:29,overrid:[108,0,11,29,105,93,94,77,124,27,141],csv_from_result:[69,29],segment_on:82,create_databas:[70,29],num_row:[106,51,29],give:[29,27,73,144,70,57,120,13,41,75,134,85,6,98,138,46,106,136],send_request:91,greater_than_equal_to:46,smtp:[62,23,29],digit:[120,81,51,29],indic:[137,39,10,49,93,29,41,7,120,123,86,125,46,99,141],captcha:29,somefil:109,encypt:73,caution:[73,29],unavail:29,want:[132,0,2,39,40,41,7,31,124,87,46,88,89,12,129,49,130,131,51,143,93,98,127,135,99,100,72,56,138,136,139,59,103,28,104,144,107,73,23,69,70,29,109,110,30,42,75,35,116,117,37,101,78],array_column:[25,29],fieldset:87,mysql_:2,unsign:[98,140,81,70,116],bag:120,read_fil:[109,29],save_queri:[76,77,29],manipul:[84,47,120,29],quot:[137,1,69,82,120,130,20,29,44,87],up575:86,march:29,how:[136,29],enforc:29,hor:49,disappear:39,show_error:[108,74,81,41,29],answer:[130,31],verifi:[143,29,140,98,46,16],"_escape_identifi":29,config:[0,13,5,40,41,87,85,124,44,86,9,127,47,11,142,12,50,93,14,6,100,136,58,89,105,25,144,141,108,27,69,29,109,72,31,75,146,77,117],updat:[82,29,31,44,76,136],lao:86,recogn:[25,29],tablenam:[144,44],some_field_nam:123,after:[29,0,144,70,58,93,50,51,31,146,77,124,130,87,117],altogeth:30,diagram:124,global_xss_filt:29,wrong:[98,123,134,75,29],mark_as_temp:[98,29],offlin:[33,94,95,96,97,52,53,54,55,17,118,115,65,66,67,68,15,30,16,32,112,34,113,114,35,61,148,149,150],random_str:[130,29],mailpath:23,post_imag:6,dbprefix:[65,89,144,72,82,29,44,141],averag:144,allowed_fil:29,util:[84,144,89,12,29],attempt:[0,29,60,75,105,134,101,135,100,88],third:[5,7,87,46,11,129,130,6,98,72,137,19,139,21,22,103,144,142,23,69,29,109,110,30,74,75,76,116],fewer:[89,144,29],username_cal:46,bootstrap:29,greet:91,imposs:[73,104,29],loader:[39,11,69,70,29,40,60,111,32,33,47,105],greek:29,maintain:[10,80,142,29,49,110,30,59,122,104,9,98,126,107,136],environ:[89,31,29],localdomain:29,reloc:29,enter:[137,138],exclus:[109,29],expected_result:138,order:[82,70,29],dblclick:39,wine:124,oper:[108,27,144,29,31,43,100,136],form_submit:[87,125],feedback:98,chunk:110,shorten:[120,116],offici:[122,98,30,29],assing:70,becaus:[0,30,7,8,87,125,46,12,93,18,98,135,100,101,21,104,25,64,108,144,73,75,116],jpeg:[123,92],field_exist:[43,82],privileg:69,affect:[39,12,29,120,30,93,14,82,76,18,144],highlight_phras:[142,29],japan:86,flexibl:[5,48,68,129,29,30,62],vari:[120,29],myfil:[143,103,129],suffix:29,code_to_run:39,cli:29,img:[6,140,23,29],inflector:[83,29],fwrite:29,add_data:107,not_group_start:144,reduce_multipl:[130,29],inadvert:29,better:[27,29,120,73,117,105,9,126,136],or_group_start:144,persist:[137,89,23,82,29,104,98],comprehens:[46,8],hidden:[39,11,0,120,29,22,125,77,87,135],img_url:140,increment_str:[130,29],them:[132,0,50,82,120,40,73,150,125,123,117,86,68,9,46,88,89,90,12,112,49,131,13,93,77,143,94,95,96,97,52,53,148,98,15,16,17,101,56,108,115,144,66,59,135,116,21,103,118,28,105,25,91,110,65,27,67,23,136,70,29,54,30,31,55,32,33,34,113,114,35,36,81,134,149,61],row_end:119,thei:[39,1,73,0,120,93,7,31,82,9,87,45,46,142,12,72,129,49,130,50,51,14,94,95,97,53,98,18,19,136,20,21,62,81,25,91,27,131,23,144,70,29,110,30,74,42,75,37,101],fragment:[81,129],safe:[142,73,63,29,30,42,75,125,98,87,12,135],compress_output:[52,29],"break":[144,29],sqlite3:[30,64,29],db_name:70,get_mim:[108,100,29],"_remove_invisible_charact":29,request_uri:[101,58,29],drop_tabl:[70,29],choic:[73,130,30,7,6,98],grammat:29,mytabl:[144,106,69,31,119],f4v:29,my_mark_start:37,odbc:[89,30,64,29],bonu:9,timeout:[60,23,91,141,82],each:[132,0,131,3,39,120,40,7,82,125,138,124,86,48,87,46,88,11,12,130,50,51,146,133,98,127,137,57,19,116,21,22,103,89,81,25,91,106,107,141,27,23,144,29,110,73,31,77,36,117,37,119],debug:[41,77,12,44,29],went:21,european:86,oblig:7,side:[56,39,131,91,29,120,30,123,144],mean:[39,73,12,86,82,120,124,30,131,22,62,97,52,7,104,125,98,106,136],monolith:78,list:[82,29],wm_vrt_offset:49,saturdai:[19,119],flock:29,ommit:25,extract:[25,23,103,101],tgz:29,depress:6,network:29,goe:[122,30,73,104,29],open:[0,144,10,29,40,72,45,105,27,9,136,127],dst:86,dsn:[89,23,141,29],rewrit:[34,146,29],sprintf:[46,30],got:29,force_download:[69,139,29],forth:142,"_reindex_seg":29,database2_nam:141,is_:29,linear:104,navig:[45,56,135],smtp_host:23,somesit:121,situat:[89,73,144,31,29],quoted_printable_encod:[25,100,29],standard:29,add_drop:69,element:[79,27,131,69,129,103,29,110,30,21,22,39,87,123,137,25,46,119],"_truncat":29,error_url_miss:132,blog_descript:[81,70],memory_usag:[37,92,77],md5:[73,63,29,130,30,134,46],anchor_class:29,angl:49,isp:98,openssl:[30,73],"001_add_blog":81,filter:[93,29],link_tag:[6,29],att:75,mvc:[57,129,72,59,131,126],pagin:[47,11,31,29],prefetch:[51,29],iphon:88,codeignit:29,confus:[110,29],fmt:86,rand:[144,29],rang:[142,49,73,86,126,107],render:[56,0,131,30,29,92,13,74,14,22,21,76,77,128,124,18,110,39,134,135],fetch_directori:29,accent:[142,29],clariti:[120,52,21,86,29],hellip:142,exit_unknown_method:108,restrict:[71,109,123,100,134,78,53],hook:[105,74,29],instruct:[120,40,47,29],alreadi:[132,39,23,69,70,144,29,92,30,98,73,103,43,138,81,116,46,136,107,110],messag:[69,82,29,44,146,45,12,100,136],wasn:[21,29],daylight_sav:86,agre:10,primari:[89,91,70,144,29,82,21,7,43,140,116,98],hood:[27,73],form_label:[87,29],nomin:95,top:[56,39,11,131,29,49,110,50,41,14,46],reverse_nam:51,result_arrai:[144,29,110,51,21,106],downsid:98,cumul:[144,70],master:[49,86,7,136],too:[89,23,29,120,30,134],similarli:[87,98,85,30,132],my_view:29,gilbert:86,john:[91,49,110,87,45,136,119],ci_rout:30,rempath:143,prep_url:[46,75,29],library_src:39,is_doubl:138,namespac:29,tool:29,notice_area:39,albert:137,took:136,user_ag:[32,34,96,29],alpha_numeric_spac:[46,29],sha1:[130,134,63,29],western:86,somewhat:73,local_tim:19,error_:132,crawl:29,technic:[48,131,74,98,134,46],fileperm:109,target:[39,144,82,49,29,75,116,87,107,136],keyword:[120,6,144,29],consequ:96,provid:[132,39,73,82,120,121,41,7,43,123,124,86,125,46,126,88,10,89,63,14,95,6,98,135,101,19,20,22,28,104,134,25,27,23,144,70,71,29,110,30,74,75,145,35,116,78,119],previous_url:19,uri_to_assoc:[145,29],older:[98,30,142,104,29],tree:107,told:[0,46],returned_valu:109,project:[10,89,122,45,126,78,136],matter:[98,37,58],solomon:86,rfc2616:29,entri:[29,91,72,60,30,93,75,6,116],date_rfc1123:86,minut:[98,60,18,86],beginn:73,explicitli:[109,141,75,29],any_in_arrai:27,week_dai:19,ran:[137,22,119],ram:73,mind:[56,137,73,44,104,134,98],auto_clear:23,raw:[138,23,69,29,49,92,60,73,74,98,116,25,46],seed:[73,144,21,29],rar:29,manner:[29,81,73,120,92,30,2,98,136],increment:[19,29,130,60,73,123,104],super_class:120,seen:[128,126,30,116],seem:[120,137,3,18,29],incompat:29,encode_php_tag:[46,63],translate_uri_dash:[93,29],result_object:51,cal_cell_end_oth:19,is_php:[108,100,29],captal:29,is_nul:138,myusernam:[141,72],latter:[120,22],encode_from_legaci:[96,104,29],common_funct:25,thorough:[116,78,29],week_day_cel:19,point2:37,contact:75,transmit:29,data1:110,moscow:86,simplifi:[76,106,82,31,29],set_rul:[46,22,29],endfor:146,trans_complet:[12,82],though:[39,73,29,49,30,7,120,98],option_nam:125,scripto:39,my_arrai:87,legibl:120,unknowingli:134,next_link:[56,29],mario:137,microsecond:[82,29],letter:[29,0,131,104,72,120,130,30,132,86],herebi:71,svg10:6,mdate:86,"_set_uri_str":29,cap:[140,29],everyth:[137,5,73,91,29,30,22,143,125,98],prematur:52,yourdomain:85,tradit:[84,27,72],cal_cell_end:19,simplic:[48,144,72],don:[80,73,82,120,7,86,46,92,93,131,98,135,136,137,19,59,60,62,104,134,141,27,23,29,30,31,44,116],mailtyp:[23,103],doc:[62,14,29],tempdata:29,clean_file_nam:29,flow:[120,47,124,136],blog_author:70,max_width:123,doe:[136,29],dblib:29,dummi:30,declar:[0,70,29,109,138,7,25,120,6,124,105,9,98],probabl:[98,73,31,22],wildcard:[82,144,44,29],item3:98,detriment:31,left:[56,0,142,69,144,39,49,110,131,21,145,120,148,91,135],sum:[144,29],dot:29,class_nam:[28,51,99],reactor:[122,29],visitor:[29,30,52,134,101,88],whitelist:[135,29],random:[137,73,144,29,130,30,140,123,104,45,135],"__ci_var":98,endwhil:146,radiu:137,use_page_numb:[56,29],advisori:[98,30],radio:[87,46,29],earth:29,form_error:[87,46],autoload:[40,27,72,141,29],fennec:29,involv:[10,19,138,49,123,91,99],absolut:[89,143,29,49,102,73,123,87,98],arcfour:73,layout:[80,69,119],acquir:[109,98,122],libari:29,field2:[144,101],menu:[87,46,129,86,29],explain:[57,19,30,98,103,134,123,91,9,46,136],configur:29,apach:[5,123,14,126,101],errantli:29,secretsmittypass:91,wm_pad:49,theme:39,explic:29,rich:[126,78],iconv_en:108,display_respons:91,folder:[0,13,40,45,11,90,50,52,53,15,16,17,18,66,89,140,65,27,67,68,29,109,74,31,32,33,34,35,118,148,149,150],changedir:143,set_head:[119,92,23,75,29],csrf_verifi:29,nasti:22,enable_profil:[77,92],stop:[29,23,144,82,92,37],compli:23,consecut:20,font_path:140,report:29,my_app_index:103,directory_nam:129,tge:29,bat:[120,74],bar:[56,143,120,93,60,92,74,103,117,18,98,9,46,127],first_url:[56,29],emb:[134,23],ietf:29,baz:120,form_hidden:[87,125,29],patch:[101,93,136,29],twice:[144,29],bad:[29,142,73,91,72,30],local_to_gmt:86,septemb:29,steal:98,"_ci_view_fil":29,mssql_get_last_messag:29,guiana:86,odbc_field_:29,urldecod:46,rollback:[12,29],datatyp:[138,91,70],num:[130,6,93,147],mandatori:73,result:[82,2,31,141,29],auto_incr:[81,70,29,21,140,116],fail:[12,29,49,60,73,44,82,96,91,116,46,135,136],themselv:[62,120,28],"_call_hook":29,best:[10,44],subject:[138,23,71,29,121,136],brazil:86,awar:[74,29],set_userdata:98,get_request_head:[101,30,29],new_path:107,databas:29,wikipedia:45,source_dir:[109,11,29],figur:82,"_error_numb":29,mua:29,invalu:120,drawn:29,awai:49,irc:8,approach:136,attribut:[79,70,29,109,30,51,75,125,6,86,87,100],inabl:120,accord:[46,91],socket_typ:60,extend:[45,0,82,29],var_dump:[120,60],column_to_drop:70,session_dummy_driv:98,boss:144,"_execut":29,extens:[27,89,139,129,29,109,40,82,74,140,25,34,9,100],week_row_end:19,html4:6,html5:[6,30,142,29],recent:134,http_raw_post_data:29,natur:[46,144,29],advertis:29,subfold:29,unaffect:29,form_validation_lang:[132,46,29],unfound:29,cop:[91,129],protect:29,accident:29,easi:[56,5,29,73,103,132,96,98,101],howev:[0,30,120,93,7,125,123,124,9,46,126,127,91,49,130,92,51,52,98,100,136,56,138,60,104,105,107,144,110,73,44,117,134],against:[81,144,29,103,116,63],compile_bind:[82,29],logic:[18,82,144,14,29],mydirectori:11,boldlist:6,login:[93,75],browser:[0,92,85,124,45,88,128,129,49,50,14,52,18,98,135,101,139,103,22,21,134,142,131,29,110,30,75,37],com:[0,131,5,120,6,87,85,45,46,126,91,129,130,13,93,97,121,98,101,56,19,140,143,65,23,29,30,31,75,145,76,34,116,39,136,123],col:[87,13],rehash:25,tough:136,debugg:29,log_path:29,set_checkbox:[87,46,29],standardize_newlin:29,height:[137,39,29,49,75,140,123,6],ascii_to_ent:[142,29],wider:49,guid:[28,29,24,9,141,99,136],assum:[73,82,7,87,46,127,89,12,13,131,52,53,56,19,68,104,65,66,67,23,144,29,30,31,44,32,34],"_parse_query_str":29,user_data:[30,148,29],duplic:[92,130,116,29],reciev:121,welcome_messag:[105,103,29],"_request":134,chrome:29,unwant:120,three:[56,23,91,144,29,49,93,20,41,31,22,87,81,44,98,9,46,130,119,134,109],been:[132,39,82,41,124,86,46,63,129,92,51,94,95,96,97,98,100,101,21,103,104,65,81,144,70,29,30,31,113,114,136,119],legend:[49,87],formsuccess:46,plaintext:23,ar_cach:29,trigger:[39,48,5,74,29,41,134,123,124,102,46,135],interest:78,basic:29,clear_attach:23,mytext:139,openssl_random_pseudo_byt:[25,135],hesit:120,quickli:74,up65:86,life:135,rfc5321:29,html_entity_decod:[135,29],unset_userdata:[98,30,29],eastern:86,suppress:[56,120,7,29],magic_quotes_runtim:29,search:[56,5,144,58,130,30,29,75,145,62,44,25,126,101,65,88],anywher:[27,37,77,92,18],lift:141,child:[62,28],"catch":[120,93],suar:6,blog_control:72,ugli:[120,140],east:86,quantiti:[87,125,29],cache_set_path:82,properti:[39,80,81,29,49,92,20,30,125,103,94,120,117,9,98,101],air:119,aim:[30,73],form_upload:87,weren:29,form_validation_:[30,29],get_compiled_upd:[144,29],publicli:[29,13,73,30,7,98],allow_get_arrai:101,aid:29,vagu:136,anchor:[29,39,27,30,75,123,46],opt:[98,126,30],template1:110,form_clos:87,printabl:29,set_delimit:110,somelibrari:120,tabl:[89,82,106,29],toolkit:[126,78],filename2:132,memcach:29,need:[132,0,2,3,39,120,40,7,8,82,9,85,87,5,44,86,45,46,117,123,126,88,128,48,142,12,129,49,13,93,131,94,95,96,97,18,98,127,135,16,72,56,138,125,136,139,58,59,60,89,21,22,103,140,81,144,104,105,91,107,73,27,23,69,141,29,92,30,74,31,75,145,77,113,116,110,124,37,101,134,78,119],marco:29,cond:144,conf:[3,29],wm_shadow_dist:49,tediou:46,master_dim:[49,29],sever:[57,68,91,70,29,82,51,144,62,138,86,105,125,46,148,127],log_date_format:29,disabl:[89,12,29,82,41,31,14,76,146,124,144,100],harmoni:29,incorrectli:29,perform:29,suggest:[27,30,103,29],make:[10,136,70,141,29],db_result:29,camellia:73,fatal:[120,60,93,29],complex:[144,59,131,6,116,46,78],strip_quot:[130,29],split:[57,142,82],chatroom:8,"__set":[98,29],complet:[138,23,12,144,29,49,30,41,103,8,82,142,6,145,116,98,106,119,88],elli:122,prev_link:[56,29],evid:93,http_x_forwarded_for:[101,29],blue:[46,6,124,143,119],rail:122,cache_overrid:124,hand:[87,0,81,46],fairli:[59,98,123,134],rais:[44,29],upload_lang:29,bia:98,techniqu:[134,73,135],dhaka:29,charlim:142,kept:[39,13,29,110,30,104,121,125,98,136,135,101],undesir:134,scenario:46,java:100,post_dat:86,linkifi:75,flush_cach:[144,29],min:[144,29],taint:134,inherit:[0,80,19],stop_cach:[144,29],client:[29,39,89,23,82,30,123],shortli:46,thi:[10,136,29],endif:[125,146],gzip:[69,52,29],programm:[120,126,8],next_row:[51,29],url_suffix:[56,65,75,29],identifi:[82,136,29],just:[137,1,73,82,40,9,87,45,46,12,49,130,97,98,135,101,56,21,22,103,62,81,134,144,27,23,69,70,29,30,74,75],safe_mod:29,wm_font_siz:49,photo:[49,107,139],ordin:75,array_replac:[25,29],up55:86,via:[144,69,70,44,29],stringenc:120,human:[65,5,29,74,75,86,36,46],yet:[12,30,21,22,116,46,100],languag:[11,29,120,40,83,86,105,45,78],previous:[54,29],shoud:7,group_bi:[144,29],xmlhttprequest:29,greenwich:86,expos:[98,29],explictli:56,declin:136,had:[96,30,29],"_end":37,ci_vers:[108,29],is_float:138,x_axi:49,ak_my_design:142,"0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz":140,date_iso8601:[86,29],swap_pr:[89,29],els:[0,120,121,41,123,46,88,12,134,100,101,22,91,144,29,109,30,74,44,145,146,116],ffffff:49,save:[0,23,144,86,129,29,120,93,60,73,41,31,7,125,123,18,104,45],hat:122,transit:[96,6,29],gave:[116,29,8],sanit:[63,29,21,22,134,46,135,100],applic:[0,80,144,105,29,40,82,41,14,31,45,89,24,18,27,9,124,100,141],csprng:25,get_compiled_select:[144,29],hmac_kei:73,preserv:[49,98,116,135,29],disposit:[23,29],regard:[48,19,144,49,41,103,120,134,46,148],exit_unknown_fil:[108,41],lightbox:6,distanc:49,anchor_popup:[75,29],"_parse_request_uri":29,background:[98,140,30,142,29],field_nam:[82,29,51,31,43,123,46],cape:86,database_nam:[89,69],apart:117,measur:[49,50,53],rewrite_short_tag:[34,29],handpick:122,"_csrf_set_hash":29,specif:[89,82,141,29],"_displai":[92,124,29],insert_id:[76,29],arbitrari:[37,91,89,44,29],manual:[89,31,29],get_client_info:2,multiselect:87,night:6,funcion:29,xlarg:87,underli:[98,89,74,82],www:[23,91,29,13,93,75,6,50,116,98,100],right:[56,39,131,91,10,71,0,49,110,29,21,145,125,124,45,144,37,142,78,136],old:[56,140,73,29,92,30,75,134,143,104,98,46,148,64],deal:[132,27,63,71,29,73,82,46,135],negat:[60,29],interv:86,excerpt:116,user_model:72,dead:29,fetchabl:44,born:107,intern:[132,73,29,120,30,51,75,95,34,134,125,98],printer:6,elaps:[37,77,86,82],interf:29,successfulli:[143,29,121,30,41,22,123,116,125,46],password_needs_rehash:25,transmiss:73,less_than_equal_to:46,thu:[46,134,93,91,29],total:[77,82,51,106,29],ico:6,bottom:[65,39,131,29,49,92,77,86],file_get_cont:[109,92,30,29],subclass:[80,29],not_lik:[144,29],raw_nam:123,pmachin:29,equal:[39,144,138,29,46,100,119],word_length:[140,29],rdfa:6,overcom:93,condit:[29,144,71,82,120,30,22,44,98],foo:[138,1,143,29,120,93,60,92,74,103,87,96,117,18,9,98,127],my_tabl:[76,106,51,144,119],localhost:[39,89,91,72,29,98,141],core:[144,29],plu:[87,138,6,75,7],who:[10,72,120,93,105,134],cal_cell_start_todai:19,passwordconfirm:46,name_of_last_city_us:120,someclass:[9,129],insecur:[30,7,29],pose:14,cellpad:[125,138,19,119],add_dir:107,set_alt_messag:23,scrollabl:29,repositori:[132,74,136],post:[137,0,72,29,93,75,77,87,134],"super":[91,29,120,131,103,117,104,9],shuck:142,unsaf:[98,30],um4:86,um7:86,first_tag_clos:56,um1:86,troubl:[30,136],um3:86,um2:86,get_flash_kei:98,invoice_id:144,is_ajax_request:[101,29],um9:86,um8:86,surround:56,reduce_double_slash:[130,29],distinct:[39,144,29],dinner:130,cipher:104,enable_query_str:[56,5,65,29],algo:25,span:[87,142,116,29],commit:[48,136,12,126,29],ci_db_util:[69,103],my_mark_end:37,produc:[56,138,73,12,70,29,30,51,31,75,103,76,96,6,44,86,87,144,106,145,142],match:[0,125,73,144,29,120,131,30,93,103,87,82,25,138,98,9,46,126,72],set_insert_batch:144,email_filed_smtp_login:29,"float":[142,147],encod:[47,29,120,73,75,134,96,111,104,116,25,46,100,101],active_group:[89,30,118],down:[81,49,51,22,120,28,86,87,134],creativ:[126,78],count_al:[76,82,144,29],captcha_id:140,formerli:[144,63,29],wrap:[142,13,29],make_column:[13,119],set_test_item:[138,29],mysql_escape_str:29,ci_typographi:[42,20],git:[38,136],wai:[132,0,73,7,43,123,117,86,45,46,63,129,51,146,18,98,135,100,101,138,59,21,103,62,104,134,91,141,27,81,144,29,109,30,42,77,37,136],"_prep_quoted_print":29,array1:25,post_get:[101,30,29],transform:[44,75,29],additionali:98,avail:[31,29],width:[39,125,140,29,49,75,120,123,6,87],reli:[48,69,70,29,120,30,98],request_method:[101,29],editor:[0,91,129,120,50,7,123,45,46],db_active_rec:[32,29],add_column:[70,29],wav:29,srednekolymsk:86,get_random_byt:[135,29],fork:136,sess_destroi:[98,29],head:29,medium:[87,119],is_cli:[45,101,30,100,29],form:[5,129,29,74,51,121,140,86,27,134,99,136],offer:[25,46,30,84,73],forc:[89,139,58,109,29,75,123,134,126,78],ucfirst:[120,80,30,131,29],forg:29,fore:42,aren:[46,29],sess_driv:[98,30,103,29],upload_path:123,renam:[89,29],nonexistent_librari:103,stand:134,"true":[27,89,51,12,70,29,40,72,41,144,44,43,77,124,74,25,69,100,82,141],something_els:74,table_open:[19,119],reset:29,absent:[37,21],input:[29,72,82,44,105,25,100],function_us:[108,100,29],validation_lang:29,new_nam:70,exact_length:[46,29],heading_row_end:[19,119],filename_bad_char:29,maximum:[142,48,23,144,49,110,73,43,123,18,104,25,46,126],tell:[132,27,89,81,69,70,144,72,49,103,145,62,138,98],independ:[2,144,82,103,125,12],toggl:[19,29],my_articl:5,field3:144,emit:29,trim:[46,130,30,29],up11:86,e_warn:29,featur:[132,0,30,5,120,40,84,124,9,46,47,49,92,51,53,98,141,136,19,60,68,134,144,64,23,69,29,73,31,145,146,148],p7r:29,delete_cach:[18,29],stronger:73,"abstract":[12,29,120,21,84,64],mirror:143,myotherclass:124,futur:[98,30,73,29],some_data:101,uri:[18,82,31,29],input_stream:[101,30,29],cal_row_start:19,exist:[82,70,136,31,29],p7c:29,"_ci_load":29,p7a:29,request:[0,23,144,29,92,30,51,103,77,5,18,93,134,136,100,101],umark_temp:98,stanleyxu:29,p7m:29,check:[69,29,120,102,41,87,121,45,96,124,36,25,134,76,100,136],assembl:144,site_nam:7,mp4:29,is_load:[108,103,7,29],"7zip":29,higher:[49,93,73,41,25,98],download_help:[32,29],when:[0,89,12,70,29,40,74,51,31,44,82,76,18,25,144,141,100,136],refactor:29,active_record:[118,30,29],"_set_head":29,test:[89,82,136,29],presum:[6,73],uri_protocol:[3,29],roll:[81,12,82],realiti:137,is_http:[108,100,29],relat:[63,70,29,120,30,22,123,6,98,3],intend:[56,0,23,144,86,29,49,57,30,98,82,138,116,50,104,27,125,46,127],phoenix:86,benefici:31,get_output:[92,124],image_properti:6,min_height:[123,29],query_toggle_count:[77,29],insensit:[135,92,93,29],intent:[120,98,30],consid:[0,73,19,141,29,40,30,74,42,44,145,82,144,138,98,87,46,37,119,126,110],sql:[89,69,82,29,144,44,76,12,106,64],iso8601:[91,29],idenitif:92,shortnam:29,outdat:134,bitbucket:29,receiv:[0,23,29,103,98,46],known_str:25,longer:[39,73,29,120,30,51,103,96,18,104,98,46,136],furthermor:[120,30,73],function_nam:100,htdoc:[109,134],pseudo:[138,73,19,29,110,92,37,126],withhold:29,dohash:[96,63,29],vietnam:86,ignor:[56,1,73,69,144,29,59,110,20,30,42,81,98,107],cal_novemb:29,time:[82,40,9,75,86,87,72,130,6,18,134,99,100,136,137,140,105,69,29,30,31,44,77],reply_to:23,backward:[29,39,30,0,121,13,51,96,81,104,125,98,101],stick:[73,136],"_data_seek":29,recipi:[121,23,29],concept:[9,98,21,26,138],session_destroi:98,flac:29,chain:[82,70,29],whoever:136,skip:[69,70,29,109,41,51,144,96,87,98],global:[132,3,40,41,7,124,9,46,48,72,134,135,100,101,89,103,98,141,27,29,30,31],focus:48,invent:134,cyril:29,function_trigg:[65,5],unit_test:138,superglob:[98,30,29],seriou:[134,96],set_valu:[87,46,29],archive_filepath:107,blog_titl:[110,81,70],"_insert_batch":29,insert_entri:72,menubar:29,millisecond:39,form_textarea:[87,29],middl:[49,142,29],depend:[89,82,31,44,29],zone:[86,29],pem:29,decim:[46,37,82,29],readabl:[139,29,109,74,120,86,98,136],worth:[98,73],deject:6,certainli:[30,73],decis:[23,104,29],text:[0,144,70,29,74,41,31,45,27,25,134,100],get_the_file_properties_from_the_fil:120,oversight:29,query_str:[3,29],update_str:[76,82,29],sourc:[10,11,143,29,49,73,6,25,126,141,136],string:[89,82,141,29],wm_font_color:[49,29],unfamiliar:22,revalid:92,lru:60,url_encod:100,octob:29,word:[65,5,89,142,29,120,93,30,51,75,140,36,125,37,141],brows:[125,27,98,88],cool:39,set_messag:[46,29],save_handl:98,level:[11,29,120,30,41,6,98,107],did:[0,144,129,29,49,131,41,22,8,120,116,45,136],die:[120,92],hawaii:86,iter:[120,110,60,130,25,119],item:[65,5,144,129,29,40,82,137,146,87,105,47,53,27,9,124,117,130,100],unsupport:29,public_html:143,team:[122,81,29],cooki:[27,134,29],div:[56,39,19,29,74,21,87,46],exit_databas:108,"15t16":86,round:[137,39,6,91],dir:11,prevent:[29,39,73,91,0,120,93,50,41,144,22,140,81,137,75,134,132,135,100,101],slower:98,secrion:73,user_str:25,"_file_mime_typ":29,sign:[10,29],shuffl:27,first_link:[56,29],product_name_saf:[125,29],last_activity_idx:95,myarchiv:107,afghanistan:86,appear:[65,39,73,19,5,49,20,29,93,42,140,18,86,91,46,142],repli:23,scaffold:[65,66,90,3,29,96,34,53],favour:29,current:[132,39,2,82,121,7,43,86,125,46,11,13,51,97,18,100,101,19,103,148,143,144,64,81,69,70,29,92,74,31,75,77,136,38],sinc:[0,82,9,87,46,126,88,12,49,92,52,18,98,135,101,125,59,103,62,104,25,144,107,108,27,69,70,29,110,30,31,75,145],ampersand:1,screenx:75,boost:31,file_path:123,or_not_group_start:144,if_exist:70,burn:137,deriv:[25,73,22],dropdown:87,compos:[40,29],gener:[144,70,82,29,31,84,136],db_backup:29,unauthor:[92,100],french:[132,86],check_exist:102,satisfi:[25,98],add_field:[81,70,29],slow:39,modif:[10,30,94,95,34,97,98],address:[29,121,14,75,6,87,136],myradio:87,along:[91,29,49,92,74,7,123,46],window_nam:75,userguid:29,latest_stuff:107,wait:91,box:[87,98,73,134],insan:53,error_suffix:[46,29],my_email:[9,30],ini_set:120,shift:[31,29],bot:[75,88],"_version":29,odbc_insert_id:29,newfoundland:86,membership:86,"_trans_depth":29,filename_help:96,valid_url:[46,29],commonli:[132,134,46,126,135,78,88],ourselv:30,some_act:123,semant:[120,42,29],regardless:[0,81,29,49,73,44,142,23,101],iana:23,extra:[56,39,73,0,29,21,22,98,87,46],activ:[5,144,29,30,138,76,96,86,125,98,37,126],modul:49,prefer:[70,144,31,141,29],ellislab:[122,30,29],instad:29,paramat:[23,29],ftp_unable_to_remam:29,default_templ:19,visibl:[39,138,29],marker:[49,98,37,29],instal:[89,74,100,29],mobil:[88,29],eccentr:29,regex:[93,29],newslett:87,serpent:73,memori:[0,69,29,51,77,18],sake:[21,72],pref:[69,19],visit:[0,30,91,129,13,131,8,144,123,104,45,46,88],test_mod:82,perm:[109,143],subvers:29,permitted_uri_char:[30,53,29],live:[98,60,14,44],handler:[98,30,93,139,29],form_reset:[87,29],value2:23,value1:23,criteria:[46,93],msg:[104,116],scope:[41,29],australian:86,checkout:125,prep:[87,134,29],heading_previous_cel:19,um5:86,capit:[0,131,72,120,30,36,9],mcrypt_mode_ecb:[104,29],minim:[48,144,59,146,133,134,87,46,126,78],python:74,peopl:[23,93,116,125,134,126,148,78,141],claus:[120,76,144,70,29],array_item:98,enhanc:29,uniquid:29,visual:[49,29],um6:86,list_fil:143,prototyp:[132,89,91,141,72,93,7,145,140,123,124,86,116,9,46,119,118],omsk:86,postgresql:[89,29,30,44,76,98,64],effort:[30,38,133,116],easiest:120,is_imag:[135,123,63,29],fly:[23,29,34,146,96,107],orwher:[96,144,29],graphic:[128,6],auto_link:[75,29],prepar:[137,123,22],pretend:29,judg:62,uniqu:[130,144,29],image_arrai:13,cat:37,json_pretty_print:92,reappear:39,invalid_select:120,is_count:36,whatev:[137,81,82,120,29,103,44,143,75],purpos:[132,48,73,71,29,49,92,30,41,103,75,109,120,86,110,98,101],misc_kei:132,materi:[73,82],object_nam:103,problemat:[30,29],heart:0,validli:121,explor:[57,29,133,30,8],stream:[73,29],"_applic":[60,30,113,114],slightli:[120,142,144],backslash:93,agent:[29,47,23,111,30,95,123,114,134,101],choke:136,crazi:144,abort:[92,41,29],indefinit:10,uruguai:86,unfortun:[134,73,31,100],occur:[29,120,130,74,103,44,14,7],contribut:[10,29],pink:6,alwai:[0,30,39,120,7,87,45,88,11,9,93,94,98,101,60,134,25,70,29,109,73,74,44,145,37,136],differenti:[134,14,29],multipl:[89,136,29],keep_flashdata:[98,29],filename1:132,charset:[82,29,42,87,6,25],ping:141,write:[69,82,29,31,44,76,144,136],set_item:[39,7],purg:93,foreach:[27,23,69,129,120,110,146,51,21,145,43,123,86,125,144,106,126],pure:[9,110,37,51,146],familiar:[56,138,12,129,73,74,146,116,98],tild:134,xhtml:[6,23,29],tbodi:119,clean_str:29,map:[11,131,91,13,93,103],example_field:44,pg_escape_liter:29,http_refer:29,http_x_requested_with:101,max:[43,116,144,29],sql_mode:29,spot:36,usabl:[30,135,100,73],mac:[45,120,88,29],socket:[60,116,29],mymethod:124,query_string_seg:56,"_ci_class":29,mai:[79,0,73,39,120,41,7,31,125,124,48,87,46,88,10,11,91,129,49,82,93,14,132,96,98,127,135,100,21,103,104,134,144,142,131,81,69,70,29,110,30,42,116,117],end:[30,120,7,124,86,46,89,130,92,51,52,98,135,138,104,107,142,143,144,29,73,31,146,116,37],underscor:[0,29,120,93,75,36,134,136],validation_error:[87,46,22],data:[82,29,31,44,43,76,106,141],grow:126,man:29,statu:[39,92,69,29,150,30,41,144,75,82,76,44,98,100],practic:[27,14,44,72],conscious:122,foo_bar:103,stdin:[101,100,29],"_get_ip":29,inform:[10,89,29,31,141,136],"switch":[29,89,73,82,120,30,46,141],preced:[29,120,20,93,86,107],combin:[0,144,29,120,30,51,6,86,87,134,135,101],block:[29,120,110,74,146,77,98,126,136,119],"_clean_input_data":29,callabl:29,tbody_open:119,purifi:30,remove_invisible_charact:[108,100],pipe:[46,123,29],search_path:29,old_encrypted_str:104,approv:[132,135],show_prev_next:29,upload_form:123,increas:[120,98,130,50,29],nbsp:[119,6,30,19,29],or_where_not_in:[144,29],ttl:[98,60,29],get_magic_quotes_gpc:29,file_permiss:[49,29],still:[89,73,29,120,30,21,8,98,25,46,58],mark_as_flash:98,ttf:[49,140],dynam:[5,29,74,31,18,9],entiti:[142,1,63,29,130,20,30,42,6,116,46,135],smitti:91,conjunct:20,newprefix_tablenam:44,group:[89,82,141,29],thank:[98,29],polici:100,form_multiselect:[87,29],"_backup":29,users_model:46,mybutton:87,platform:[89,2,69,29,82,144,62,76,98,12,100,88],window:[136,29,120,60,75,45,101,135,100,88],new_table_nam:70,unset_tempdata:[98,29],intl:29,javascript_loc:39,mail:[23,29,121,30,75,62,87,98],main:[65,0,11,29,109,50,41,80,108,89,117,87,136,127],countabl:36,getfileproperti:120,explanatori:123,non:[142,30,70,29,120,102,20,92,93,96,6,134,25,98,119,100,101],halt:[98,29],jame:144,displai:[89,29,41,13,74,82,76,77,124,18,86,87,134],thumb_mark:49,initi:[89,82,31,29],alt_path:132,or_not_lik:[144,29],date_rfc822:[30,86],safari:[88,29],disappoint:46,ci_cart:125,now:[45,0,29],discuss:[134,131,28,144,99],nor:[30,144,44,73],havingor:29,pastebin:136,term:[56,27,2,73,103,132,9,98],argentina:86,name:[89,2,144,70,29,82,51,31,44,43,76,106,141],mysql_get_client_info:2,opera:29,cellspac:[125,138,19,119],didn:[137,98,30,29],separ:[144,29,120,130,41,75,36,9,141],is_really_writ:[108,100,29],allman:[120,136],januari:[19,29],hijack:[134,135],pizza:6,compil:[91,82,49,29,44,77,144],failov:[89,29],domain:[98,85,101,74,29],"_get_mod_tim":29,img_path:140,cal_cell_no_content_todai:19,cookie_httponli:[98,29],replac:[69,29,44,43,146,25,144],individu:[69,70,29,60,31,106],um95:86,continu:[91,129,29,120,93,22,104,116,46,37],ensur:[137,89,29,120,60,73,103,104,134],redistribut:10,backport:25,significantli:[126,105],viewpath:[108,29],year:[122,19,86,29],min_width:[123,29],happen:[23,129,29,73,31,30,124,98,37,107,136],set_realpath:[102,29],heading_row_start:[19,119],html_escap:[87,108,30,100,29],slide:39,shown:[56,27,131,73,19,144,29,49,110,30,123,75,146,140,77,125,46,37,132,142,150],accomplish:[91,70],referenc:[110,86,29],"3rd":29,space:[134,29],old_fil:143,storag:[82,29],"_remap":[45,0],trans_commit:[12,29],profil:[24,29],mess:105,get_file_properti:120,danijelb:29,tb_data:116,is_int:138,correct:[29,138,143,144,82,120,73,42,76,123,134,46],image_lib:[32,49,11,29],group_two:141,get_head:[92,29],state:[39,48,23,144,0,29,138,18,86,87,98],migrat:[47,111,148,29],ibas:[64,29],xhtml1:6,tmpf:98,cart:[47,29],"_error_messag":29,ajax:[39,101,135,98,29],ident:[0,2,120,7,31,9,85,86,87,46,49,51,96,6,101,125,20,105,108,27,28,144,70,29,110,42,75,145,37],mime:[139,29,109,53,35,100],set_update_batch:[144,29],org:[6,23,29],"byte":[29,120,73,77,147,135],card:[125,73,104],error_str:[46,81],insert_str:[76,140,82,116],reusabl:48,time_refer:[86,29],suffici:98,befor:[0,144,29,105,93,44,43,124,18,27,141,136],nice_d:[86,29],yup:104,modest:29,british:[122,71],unavoid:96,turn:[56,30,12,129,29,13,31,75,145,76,123,143,144,134,87,98,100,101],place:[0,50,82,120,7,134,123,124,9,46,89,91,49,13,93,14,18,98,136,56,138,19,60,21,103,81,105,107,142,23,144,70,29,92,30,31,77,37,148],cal_days_in_month:[86,29],legacy_mod:104,log_messag:[108,41,12,29],okai:120,row_id:125,principl:[9,57],nicknam:91,think:[73,104,136],lambda:124,ci_benchmark:37,loki97:73,directli:[0,30,82,117,9,10,129,130,50,18,134,101,138,128,21,98,144,28,69,70,29,72],ci_lang:[79,132],onc:[132,39,41,125,123,117,9,88,91,49,29,18,133,98,99,101,138,19,20,21,103,140,104,134,106,107,27,143,69,70,72,110,73,31,116,119],arrai:[89,82,141,29],zab:120,housekeep:31,yourself:[132,0,39,120,125,98,136],tag_open:142,fast:[137,39,60,84,18,98],oppos:[30,73,29],happi:6,fiji:86,ruri_to_assoc:[145,29],"__construct":[0,72,120,29,21,96,117,105,9,98,123],size:[137,140,125,91,29,49,73,145,109,123,6,147,134,87,46,119],truncate_t:29,given:[132,125,19,29,49,30,98,103,109,46,116,86,36,25,12,126,145,107,78],twofish:73,silent:[30,29],convent:29,gif:[49,39,123],w43l:29,associ:[0,125,73,19,70,144,29,30,51,31,75,43,76,85,6,124,100,140,87,69,82],bite:39,malform:29,cubrid_affected_row:29,assort:29,max_length:[43,46,142],utliz:144,circl:6,where_in:[144,29],white:[140,29],conveni:[0,81,39,109,40,135,101],my_foo:60,get_package_path:103,especi:98,programat:44,copi:[73,7,9,90,112,49,130,131,94,95,96,97,52,53,54,55,17,118,115,65,66,67,68,71,29,15,30,16,32,33,34,113,114,35,61,136,148,149,150],specifi:[132,0,92,5,93,7,125,123,124,44,86,87,46,88,89,91,129,49,130,82,51,6,137,53,98,100,72,56,19,142,60,103,140,143,104,25,144,107,141,27,23,69,70,29,109,73,75,76,101,119],oci_execut:29,cfb8:73,xhtml11:6,"short":[136,29],enclos:144,mostli:69,full_tag_open:56,necessarili:98,alnum:130,"_compile_queri":29,png:[49,109,123,75,29],imagecr:29,serv:[0,73,91,58,59,92,29,41,31,120,128,101,72],wide:[77,73,101],ciphertext:73,client_nam:123,instanc:[132,82,120,93,31,123,124,9,46,91,130,92,51,96,56,19,103,104,141,142,23,144,70,29,73,42,117,119],form_item_id:79,sha512:73,posix:29,param2:2,param1:2,were:[29,39,73,91,0,6,134,30,135,94,95,81,52,98,87,97,126,54,78],posit:[142,91,70,29,49,60,82,51,25],get_csrf_hash:[94,135],zsh:29,typographi:[83,29],seri:[108,39,29],pre:[91,29,20,92,42,125,46,101],lowest:[23,41],sai:[132,0,2,29,49,72,93,31,73,120,75,104,98,125,46,127],explode_nam:29,upload_success:123,xml_from_result:[69,29],"_prep_q_encod":29,delim:69,ani:[79,0,2,5,120,150,41,43,87,124,44,86,9,90,12,100,130,13,93,77,52,53,134,15,16,17,18,137,108,136,66,140,68,105,141,65,27,67,28,144,29,109,74,31,75,32,33,34,50,35,117,118,148,149,82],month_typ:19,dash:[1,29,93,75,36,134],db2:141,properli:[0,73,144,29,110,30,74,21,44,134,98,150],suhosin:[100,29],post_model:137,exclud:[107,5,23,92,109],num_field:[51,31],seppo:29,page1:144,"_env":29,caus:[39,23,12,29,120,93,30,41,14,82,87,123,124,102,9,98,107,142],"_create_databas":[96,29],engin:[65,5,70,58,110,30,29,75,146,44,98],squar:[46,6],advic:134,alias:[82,93,29],destroi:[125,101,104,29],"_pi":29,note:[144,70,29,51,44,106,141,136],date_rfc2822:86,ideal:46,jefferson:137,take:[0,1,13,82,120,124,44,86,9,46,145,61,91,112,50,93,94,95,96,97,52,53,133,98,54,16,17,101,137,115,116,103,22,140,104,141,65,66,67,68,70,29,109,15,30,31,75,55,32,33,34,113,114,35,36,118,148,149,150,119],advis:[98,73,44,75,64],interior:120,green:[46,6,143,119],wonder:136,bcrypt:134,noth:[56,132,23,142,21,62,52,98,46],getwher:[96,144,29],error_messages_lang:132,realpath:29,begin:[57,50,144,29,120,130,13,18,46,38],sure:[132,0,5,120,9,123,125,12,92,51,94,52,98,19,60,21,22,143,105,107,23,144,72,116,134],incorpor:[59,132],trace:29,normal:[0,50,39,93,7,9,117,86,45,46,128,49,130,92,51,131,18,101,56,138,59,105,142,23,144,29,145,146],"_update_batch":29,mydata2:107,price:[125,126],group_on:141,compress:[107,69,89,52,29],clearer:136,"_assign_to_config":29,abus:29,sublicens:71,pair:[56,19,29,30,51,82,144,37],henc:30,hotfix:136,get_total_dai:[19,29],fetch_class:29,icon:[6,75],exact:[46,30,142],image_res:49,view_fil:29,synonym:[5,126],textarea:[87,13,22,29],view_fold:[50,29],later:[131,81,144,30,21,22,95,98],option_valu:125,escape_like_str:[82,44,29],rotation_angl:49,runtim:[120,135],pattern:[144,29,59,131,93,8,84,134,106],addit:[79,5,30,39,120,93,41,125,87,46,126,88,91,49,13,51,14,132,95,98,137,19,23,70,29,92,73,50,37],mb_strpo:25,axi:49,salt:[25,73],sess_expir:[98,30],gracefulli:141,shop:47,shot:[125,101],signoff:136,uncondit:29,show:[0,144,29,102,13,41,44,86,87,37,106],german:132,pconnect:[89,72,141,29],hmac:29,crime_is_up:145,concurr:30,shoe:[65,0,145,5],permiss:[143,71,49,123,109,34,18,45,98],hack:[63,29,76,124,135,101],threshold:[34,41,29],pull:[6,136,129,86,29],line:[89,69,29,144,146,12,141,136],fifth:125,help:[39,50,120,41,31,43,44,86,46,88,142,91,13,131,96,6,134,135,136,56,20,59,81,108,27,23,69,70,29,74,42,75,145,77,147],exit_user_input:108,userdata:[98,30,29],onli:[132,0,13,39,120,93,41,7,82,87,85,124,44,86,48,9,46,126,123,88,11,91,49,130,50,51,137,6,52,53,121,98,127,135,100,18,56,138,125,136,20,60,89,21,22,62,140,143,73,104,134,25,144,64,142,23,69,70,141,29,109,92,30,74,31,75,116,110,117,37,101,58,119],snack:124,ratio:49,favor:[137,63,78,29],romanian:29,transact:[84,82,29],ini_get:[120,29],xma:125,next_tag_clos:56,black:140,datestr:86,mydata1:107,filectim:29,first:[132,0,2,5,120,93,41,114,7,82,87,85,117,86,9,46,90,12,72,76,130,125,13,51,77,143,94,95,96,97,52,53,118,136,15,16,17,18,101,19,115,139,58,6,103,140,68,134,25,144,106,66,141,65,27,67,23,69,70,29,54,112,30,31,75,55,32,33,34,113,100,35,61,149,37,81,148,142,150],overwritten:[123,30,29],query2:51,over:[39,19,57,49,29,93,21,75,82,120,6,86,87,91,100],mypic:[49,123],nearli:[49,75,125,105,9,78],variou:[27,19,29,123,35,46,107,88],get:[0,73,82,93,41,84,85,124,125,46,47,50,51,96,52,53,134,72,60,106,23,144,29,30,31,44,77],sst:29,imagecreatetruecolor:29,sss:74,secondari:44,isn:[132,137,69,70,29,93,73,41,144,46,101],ssl:[23,143,100,29],cannot:[108,27,89,29,102,73,98,38,136],mypic_thumb:49,neither:[49,73],requir:[89,12,70,29,76,144,106,141,136],truli:126,reveal:[62,39],item_nam:7,output_compress:29,outperform:98,borrow:122,email:[11,29,76,9,106,99],todo_list:[91,129],twelv:119,euro:86,default_control:[0,93,29],ini:[142,29,120,102,146,123,98],ci_cach:60,ent_compat:135,where:[0,82,120,124,86,9,89,129,51,14,18,99,100,136,142,140,25,141,65,27,28,144,29,72,31,44,76],summari:[9,39],wiki:[133,8],msdownload:29,a_long_link_that_should_not_be_wrap:23,smiley_j:[13,29],marquesa:86,password_get_info:25,send_email:[121,30,29],smiley_t:13,"_display_cach":[124,29],my_input:105,calendar:[47,96,29],another_method:28,element_path:39,concern:[125,98,30,135],infinit:29,detect:[81,3,29,49,92,73,75,82,123,25,135,88],"_base_class":29,controller_trigg:[65,5],review:30,auto_head:29,ubiquit:98,label:[79,46,70,87,29],db_pconnect:[82,29],enough:[137,46,73,134],between:[2,120,9,46,126,89,12,49,130,93,14,18,134,100,59,107,23,144,29,110,36,37],my_app:103,"import":[73,8,146,52,104,134,9,98,126],paramet:[2,136,31,29],across:[30,14,73],dir_read_mod:108,assumpt:48,"_clean_input_kei":29,aleutian:86,august:29,parent:[0,28,72,29,105,9],sku_567zyx:125,cycl:[130,23,18],reorgan:29,set_content_typ:[92,29],blog_nam:[70,116],come:[132,39,131,29,40,60,30,93,14,7,84,134,123,110,98,126,135,101],sess_upd:29,unnecessari:107,repertoir:39,fit:71,rsa:29,file_read_mod:108,controller_info:77,pertain:31,config_item:[108,30,100,29],groupbi:[96,144,29],contract:71,inconsist:29,open_basedir:109,improv:29,log_threshold:29,create_link:[56,29],among:[125,98,88,29],undocu:30,frameset:6,color:[137,140,125,142,29,49,30,145,87,6,9,46,119],colspan:[125,19,119],list_field:[43,82,51,29],period:[91,29,20,123,86,125,134,101],pop:75,photo2:23,photo3:23,exploit:[135,29],up13:86,colon:[125,98,146,134,29],example_t:44,parse_exec_var:[92,29],cancel:[144,91],up14:86,consider:[49,29],returned_email:23,damag:[73,71],needlessli:29,"_remove_url_suffix":29,semicolon:[146,135,29],coupl:[48,91,58,29,105,9,46],dynamic_output:49,west:86,rebuild:29,fopen_read:108,mari:119,mark:[29,142,58,30,44,95,77,87,98,37,100],locpath:143,certifi:[10,136],trig:29,thead:119,ci_sha:29,short_open_tag:120,repons:[100,116],decrypt:[134,104],thousand:29,georgia:86,rubi:122,get_id:116,proven:[134,30,73],"_drop_databas":[96,29],thing:[92,120,8,45,46,131,14,134,135,136,19,60,103,22,21,98,144,70,29,30,74,75],repres:[56,5,29,49,93,30,51,21,59,116,25],former:29,those:[132,5,30,120,7,134,125,46,88,91,49,130,92,93,131,94,98,72,56,20,105,29,73,31,136,119],sound:136,blowfish:73,firstnam:[110,91],amend:29,rtype:74,singleton:103,trick:[98,134,29],cast:[120,73,29],netpbm:[49,62,29],is_robot:[88,29],base64:[46,73,91,134],outcom:144,send_success:116,bufferedtext:120,margin:[87,126],show_next_prev:19,assoc_to_uri:145,glanc:47,advantag:[70,120,8,87,104,133,9,98,100,101],protect_identifi:[82,44,29],cache_item_id:60,up9:86,destin:[49,123,143,93],prev_tag_open:56,or_hav:[144,29],list_databas:[69,29],my_dog_spot:36,eras:98,img_width:140,hash:29,blog_id:[81,70],ascii:[142,143,29,140,116,100],ship:125,subtot:125,par:29,ci_image_lib:[49,29],xml_encod:120,author:[120,125,44,71,29],obfusc:75,alphabet:46,intermediari:59,same:[0,2,144,10,141,29,51,45,27,9,136,70],jsmith:91,binari:[143,29,107,73,25,135],html:[5,11,129,29,74,41,86,87,134,100],pad:[49,73,29],file_4:130,raw_output:25,pai:29,document:29,form_fieldset:[87,29],week:[19,86],php_sapi_nam:29,screenshot:136,utf8:[89,118,70,141,105],nest:[144,72,12,103,29],assist:[79,27,1,142,140,29,109,41,74,11,75,130,85,6,137,121,87,134],driver:[89,2,31,141,29],someon:[23,73,140,53,104,125,46],modify_column:[70,29],companion:142,driven:136,capabl:[5,48,29],cache_query_str:29,mani:[89,12,70,130,31,44,122,6,45,134,136],extern:[120,98,135,29],encrypt:[47,89,63,29,130,50,134],rewriterul:5,disallow:[142,135,53,29],return_object:82,sanitize_filenam:[135,63,29],"_ci":29,appropri:[56,10,131,91,29,120,73,41,144,82,76,147,98],new_entri:91,mcrypt_blowfish:104,markup:[39,123,6],page:[106,141,144,31,29],custom_row_object:51,without:[132,0,2,39,120,41,7,9,123,87,124,44,86,45,46,12,49,92,51,98,54,101,102,60,21,103,140,104,134,27,28,144,70,71,29,73,75,77,116,117,37,136],compression_level:107,titl:[13,123,75,46,91,129,130,131,51,6,135,137,21,22,106,144,29,110,72,74,44,116,119],index_kei:25,model:[29,40,45,24,9,117,136,127],get_content_typ:[92,29],dimension:[89,129,29,110,6,124,125,119],insert_batch:[144,29],keyup:39,execut:[82,70,29],mypassword:[46,141,72],rule3:46,rule2:46,rule1:46,allowed_typ:[123,29],directory_separ:29,gd_load:29,"_post":[29,137,72,120,30,140,77,134],"_get_config":29,kill:29,cambodia:86,aspect:[49,19,29],touch:98,monei:137,less_than:[46,29],speed:[39,18,98,29],filter_var:[121,30,29],product_lookup_by_id:93,versu:120,is_cal:[46,29],fh4kdkkkaoe30njgoe92rkdkkobec333:125,except:[5,120,51,7,9,85,86,87,46,49,130,93,96,98,20,60,105,144,70,29,110,30,42,75,145,32,146,37,78,119],param:[29,0,73,69,39,120,30,74,98,103,124,91,9,46,56,119],desktop:[107,91,69,139],non_existent_fil:102,my_shap:137,blob:[98,30],versa:49,img_id:[140,29],constant:[100,29],mb_convert_encod:29,process_:0,word_censor:[142,29],earli:124,gd2:49,hover:39,around:[29,82,120,60,13,44,87,46],code:[136,141,29],read:[131,82,120,8,46,126,72,129,50,96,133,98,99,100,101,57,139,103,22,143,4,134,106,107,27,28,144,29,109,30,31,44,77,37,148],escape_str:[82,44,29],messsag:23,"_convert_text":120,is_allowed_filetyp:29,grid:[140,29],darn:142,mom:[91,129],world:29,js_insert_smilei:[30,29],"_write_cach":0,blackberri:29,whitespac:29,some_funct:[87,2],changelog:29,preg_replace_ev:29,integ:[138,11,144,70,29,49,51,76,120,98,46],server:[89,69,29,82,41,31,14,146,18,141,100,127],set_status_head:[108,92,100,29],benefit:[28,12,120,144,44,86,87,46],photo1:23,bsd:126,either:[39,73,120,123,2,86,46,87,97,91,49,93,96,6,98,135,72,56,138,20,104,144,141,23,69,29,30,31,75,136],cascad:29,output:[69,70,29,44,45,18,25,76],tower:136,nice:[46,22,142],json_unescaped_slash:92,yyyi:86,what:[89,136,31,44,29],affected_row:[76,106,144,29],method_exist:0,juli:29,blog_label:70,http_header:77,refresh:[18,75,29],word_wrap:[142,29],error_db:[65,82],set_new:22,first_row:51,form_help:32,slice:6,caribbean:86,mood:6,easili:[5,92,144,73,21,96,117,104,126],deliveri:[119,29],kml:29,definit:[70,29,30,74,87,117,9],token:[120,92,135,29],protocol:[23,3,58,130,29,75,62,143,98,101],ac3:29,exit:[81,29,120,92,41,9],inject:[123,29],xtea:73,"_parse_cli_arg":29,apostroph:20,complic:98,kmz:29,exp_pre_email_address:120,refer:29,get_last_ten_entri:72,total_item:[125,29],shadow:49,power:[39,131,22],cal_cell_end_todai:19,garbag:98,inspect:125,max_height:123,broken:[134,23,28,29],apantbyigi1bpvxztjgcsag8gzl8pdwwa84:104,fopen_read_write_cr:108,found:[132,0,81,40,41,7,85,124,86,130,92,93,131,98,100,101,60,103,28,134,25,73,23,69,29,30,145,147,116,136,150],mime_content_typ:29,thailand:86,referr:88,appli:[29,136,82,49,30,120,85,98,46,119,134,101],isset:[120,98,101,14,29],earlier:[131,144,129,116,21,22,98,46],callback_:46,src:[6,140,23,29],central:86,greatli:12,discern:[123,29],island:86,previous_row:51,request_filenam:5,exit__auto_max:[108,41],greater:[1,68,120,86,46,100],mcrypt_dev_urandom:[25,73],is_numer:[134,138,29],degre:[49,110,48],intens:[109,42,31],phpdomain:74,reset_queri:[144,29],table_nam:[69,70,82,30,51,44,43,76,106],slash_rseg:145,luck:137,backup:29,processor:42,routin:[27,48,69,29,31,123,134,46],effici:[88,29],max_siz:123,status_cod:41,coupon:125,lastli:[74,145,3,31,91],image_width:123,date_rang:[86,29],quietli:120,super_class_vers:120,strip:[142,23,63,29,130,22,134,116,46],your:[136,29],clipperton:86,call_user_func_arrai:0,unit_test_lang:32,wm_font_path:49,"_detect_uri":29,area:[49,13,93],met_win_open:75,odbc_num_row:29,"_explode_seg":29,overwrit:[123,7,29],xw82g9q3r495893iajdh473990rikw23:125,ci_unit_test:138,start:[82,29],pre_system:124,interfac:[144,29,49,41,45,98,126,78,101],low:[120,142,30,73,29],mbstring:[25,29],ipv6:[46,101,113,29],submiss:[120,140,86,134,46,135],strictli:109,strict:[89,82,29],filter_uri:29,lang:[79,108,132,29,120,30,103,7,46,88],up10:86,programmat:[27,30,81,29],str_replac:120,bsc:110,conclud:98,bundl:[98,74],designfellow:29,"_session":[98,30,29],mb_strlen:[25,29],procedur:[46,27,124,41,29],encrypt_nam:123,cryptograph:[30,135,104,73],openxml:29,conclus:47,sess_expire_on_clos:[98,30,29],orlik:[96,144,29],notat:[49,109,29],mathml:6,possibl:[73,120,117,125,127,48,49,92,93,131,96,53,133,134,136,56,103,21,104,105,144,28,69,29,110,30,31,50,148],"default":[89,12,70,29,51,144,76,69,141,136],error_prefix:[46,29],delete_fil:[109,143,29],lowercas:[29,72,120,30,75,22,104,101],eschew:78,grasp:74,ci_sessions_id_ip:98,embed:[129,29],deadlock:[98,29],remove_spac:123,up12:86,connect:[89,2,29],cbc:[73,29],creat:[10,136,31,141,29],multibyt:29,certain:[65,0,89,30,144,39,40,29,74,31,5,25,134,136],tahiti:86,site_id:70,valid_usernam:46,mode:[89,82,29],strongli:[30,53,64],undergon:29,print_debugg:[23,29],file:[10,136,29],next_url:19,fill:[46,29],incorrect:[87,120,73,103,29],again:[39,73,131,103,46,98],image_typ:123,googl:[138,29],hex:[49,73,63,29],collector:98,bhutan:86,conn_id:[2,31,29],prepend:[144,29,73,103,44,145,85,46,101],field:[89,82,29],valid:[0,89,12,29,93,25,99],collis:[132,29,60,30,103,7,101],rdbm:29,is_unix:86,vanuatu:86,writabl:[29,109,41,31,140,34,18,123,107,100],you:[0,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,25,27,28,29,30,31,32,33,34,35,36,37,39,40,41,42,43,45,46,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,72,73,74,75,76,77,78,132,81,82,85,86,87,97,88,89,90,91,92,93,94,95,96,6,98,99,100,101,102,103,104,105,106,107,108,109,110,44,112,113,114,115,116,117,118,119,120,123,124,125,126,127,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150],mcrypt_create_iv:[25,135],architectur:[47,80],poor:62,create_kei:73,sequenc:[89,81,29,73,76,6],symbol:[109,102,29],pear:[78,29],multidimension:[87,46,6],track:[41,81,12,98,29],dropbox:136,rsegment:[30,145,29],localhost1:89,typecast:29,reduc:[130,60,134,42,31],deliber:104,ci_zip:107,segment_two:82,redud:30,cookie_domain:[98,3],wm_use_drop_shadow:29,descript:[89,136],session_id:[98,30,29],smtp_user:23,mimic:20,mass:96,potenti:[134,1,28,64,29],up115:86,escap:[76,106,82,29],w3c:[6,86,29],newli:[46,104],unset:[98,30,134,29],"_remove_evil_attribut":29,disp:23,file_upload:11,all:[10,136,29],db_backup_filenam:69,new_field:30,filename_pi:96,lack:[98,30],dollar:[93,29],month:[120,86,29],new_list:119,atlant:86,correl:[124,18],mp3:29,microtim:140,wm_type:49,follow:[0,1,3,5,7,9,11,12,13,18,20,21,22,23,25,26,27,28,29,30,31,35,36,37,39,40,41,42,43,45,46,48,49,52,53,56,57,60,63,65,66,67,68,69,70,71,72,73,74,75,77,79,81,85,86,87,88,90,91,92,93,95,96,6,98,99,101,102,103,105,106,108,109,44,116,117,118,120,121,123,124,128,129,130,131,132,134,135,137,138,139,140,141,142,144,147],alt:[6,23,29],disk:[49,60,73],children:29,abid:50,library_path:49,content:29,iconv:[25,29],number:[82,120,51,83,85,86,89,93,77,6,18,134,100,137,140,25,28,144,70,29,76,146],get_file_info:[109,29],script_nam:29,sess_regenerate_destroi:98,wmv:29,spirit:29,mistakenli:29,init:[65,66,67,68,3,29,90,53],use_sect:[103,7],spearhead:122,queri:[2,31,29],read_dir:[107,29],max_filename_incr:[123,29],cgi:29,introduc:[57,120,21,8,148,100],adapt:[60,144,82],"case":[132,0,80,73,5,120,93,9,123,117,87,46,89,12,49,50,51,121,98,135,99,100,101,125,144,142,60,103,22,104,105,91,110,27,143,69,70,29,109,92,30,75,36,134,150],liter:[134,138,93,29],straightforward:98,ingredi:73,fals:[27,89,100,12,70,29,51,72,41,144,44,43,77,74,93,25,69,82,141],passconf:46,keydown:39,get_new:21,verb:29,mechan:[138,73,70,29,30,124,104,98],verd:86,failur:[132,82,120,7,123,86,125,46,12,49,51,143,98,135,137,144,60,103,81,25,91,107,23,69,70,29,109,73,74,44,145,116,119],veri:[137,120,84,85,124,44,9,46,126,88,48,12,49,131,143,52,98,56,19,103,62,81,144,65,23,69,110,31,75,37],get_clickable_smilei:13,condition:[49,23,91],subsubsubsubsect:74,mysql_set_charset:29,norfolk:86,"_filter_uri":29,my_array_help:27,tag_clos:142,last_nam:91,e_strict:29,emul:[0,98],small:[57,48,23,29,120,73,76,87,126,78,119],require_onc:65,e_notic:29,dimens:49,trans_strict:[12,82],getimages:29,samoa:86,ten:119,"__get":[98,29],my_blog:91,product_lookup:93,sync:29,past:[73,86],zero:[130,73,41,31,145,34,123,98,125,46,78,101],postgr:[76,89,64,29],db_conn:103,pass:[82,136,141,29],overlin:74,further:[0,48,92,57,29,31,6,116,25,98,141],nba:46,log_file_permiss:29,directory_depth:11,kdb:29,wm_shadow_color:[49,29],server_path:109,sub:[74,31,29],trans_rollback:[12,29],sun:[19,86],section:29,abl:[39,29,120,93,73,51,8,121,77,116,9,46,100],brief:[123,73],ci_encrypt:[73,104],delet:[70,82,29,31,44,76],abbrevi:[49,132,19],db_select:[82,141,29],primary_kei:43,intersect:29,is_bool:138,some_method:[0,28,69,70,74,9],ci_migr:[81,29],method:[82,136,70,141,29],contrast:[126,12],full:[132,0,50,39,120,8,84,123,9,126,88,89,63,49,92,96,6,134,127,100,56,138,144,62,91,106,69,29,109,110,31,75,145,37,119],iran:86,agent_str:88,pacif:86,variat:[51,29],where_not_in:[144,29],misspel:29,decid:[101,73,91,29],behaviour:[23,30,29],coco:86,shouldn:[98,30,7],username_check:46,imap_8bit:29,is_allowed_typ:29,is_object:[138,29],ci_pagin:56,strong:[142,73,29,30,125,134,119],modifi:[10,82,29],preserve_filepath:107,valu:[136,29],leav:[138,23,63,29,49,73,22,75,120,97,124,53,134,46],min_length:46,valid_ip:[46,101,29],ahead:51,get_userdata:[132,98],server_info:29,popen:29,observ:29,prior:[81,29,123,68,124,104],amount:[12,49,92,144,77,18,125,46,37,135,126,78],pick:120,action:[39,125,144,71,0,49,29,74,43,87,123,97,124,45,46,135],another_t:31,narrow:134,diamet:137,hash_algo:63,display_error:[82,29],gost:73,intermedi:8,screeni:75,africa:86,example_librari:9,hash_hmac:73,remap:29,deprec:[63,70,29,109,121,13,75,95,96,6,86,130,87,148,64],href:[19,29,110,21,75,6],famili:73,um45:86,demonstr:[142,23,13,22,123,6,107],decrement:[60,19,29],"_start":37,establish:[141,82],trans_off:[12,82],select:[82,29,31,44,43,76,106],metaweblog:91,test_nam:138,ci_env:[14,29],hexadecim:[25,73],helper:29,internation:29,faint:49,two:[0,73,41,7,31,43,87,125,46,127,12,9,130,93,134,136,140,104,105,141,65,27,23,144,29,30,42,77,37],page_titl:129,fall:[25,60],fopen_read_writ:108,autonom:[48,82],res_datatyp:138,taken:[81,38,29],select_max:[144,29],"_object_to_arrai":29,minor:29,more:[79,0,73,5,120,93,41,114,8,87,124,86,45,46,126,48,12,72,129,49,130,50,51,14,95,96,97,148,121,98,6,31,137,57,125,19,142,59,60,89,22,103,62,91,25,63,141,27,131,23,144,29,92,30,42,75,34,113,100,116,37,134],emoticon:13,flaw:[134,29],desir:[79,132,81,144,141,29,120,20,13,51,14,123,143,134,127,78,119],create_thumb:49,hundr:[88,29],mozilla:88,relative_path:135,photoblog:91,flag:[138,144,70,82,29,134,136],driver_name_subclass_2:80,driver_name_subclass_3:80,broke:[136,29],driver_name_subclass_1:80,known:[144,29,30,134,105,25,98,88],mathml1:6,mathml2:6,trans_statu:[82,12,29],cach:29,fopen_write_create_strict:108,"_stringify_attribut":108,town:70,none:[23,19,29,49,82,134,123,81,98,25,69],endpoint:135,suitabl:[120,30,63],hour:[98,86,140],hous:[91,129],list_tabl:[43,82,29],der:29,outlin:104,dev:[25,120,30,135,73],detect_mim:123,orderbi:[96,144,29],remain:[18,140,31,22,29],paragraph:[46,1,29],nine:119,caveat:98,learn:[12,50,93,103,7,133,98,126,78],group_end:144,male:145,explod:120,typograph:42,subclass_prefix:[9,27,34,105],scan:29,up875:86,challeng:126,server_protocol:101,share:[89,19,29,31,98,3,127],"404_overrid":[93,29],accept:[39,73,82,120,86,46,87,97,88,91,130,131,51,6,98,135,100,101,19,140,134,23,144,70,29,110,30,75,116,136,119],sphere:6,minimum:[56,46,123,144],unreli:[100,29],set_row:51,phrase:142,blog_head:110,ci_upload:[123,29],unlucki:134,cours:[73,30,93,104,98,87,46,126],newlin:[23,69,29,120,130,20,42,6,46,101],first_nam:[46,91],secur:[29,14,44,24,105,124,136,100,64],rather:[132,5,82,9,87,46,126,48,12,129,93,95,136,138,89,103,141,70,29,110,30,44,101],anoth:[0,23,12,70,144,29,30,98,7,103,146,134,123,117,91,69,88,107,73],smtp_port:23,perhap:[9,27,105,98,46],fame:98,narrowli:48,some_cooki:101,url_titl:[75,29],"_unseri":29,reject:48,iso:[23,86],csv:29,simpl:[0,30,5,41,84,87,45,46,126,89,91,129,6,98,56,138,19,142,81,104,27,23,144,29,110,73,74,75,116,39,78],needl:[25,27],css:[39,92,142,30,75,6,86,134],"_thumb":49,convert_accented_charact:[142,29],regener:[98,135,29],plant:91,sandwich:86,resourc:[89,12,82,29,51,31,44,117,144],indian:86,whats_wrong_with_css:75,smiley_view:13,show_404:[108,0,29,41,131,93,21,150],variant:132,invok:[65,5,48,28,124,105,46,37,99,101],reflect:[37,29],catalog:93,buffer:[120,23,52,29],mutat:29,subdriv:29,unlink:29,lanka:86,circumst:92,github:136,product_typ:93,system_path:50,footer:[59,131,21,22,129],onto:92,overnight:119,in_particular:120,callback:29,image_height:123,yyyymmddhhiiss:81,hash_equ:[25,29],media:6,stricton:[89,29],set_hash:29,cal_cell_start_oth:19,checkbox:[87,46,136,29],rotat:[49,62,29],no_result:145,migration_vers:81,azerbaijan:86,file_s:123,cook:86,through:[0,28,19,29,130,57,30,51,21,103,85,98,87,91,126,119,135,100,101],reconnect:29,hierarchi:[74,129],fff:49,helo:29,password_hash:25,orig_path_info:29,style:29,overhead:135,ip_address:[29,30,140,113,116,98,101],border:[138,19,29,140,125,119],end_char:[142,116],dbname:[89,141,29],resort:98,bypass:128,number_lang:147,delici:3,might:[132,0,73,5,93,41,8,85,124,46,89,91,129,49,13,51,131,18,98,100,72,138,136,58,21,22,103,140,106,142,23,69,29,109,30,146,101,148,119],alter:[81,70,29,148,30,95,143,113,105,98,135],wouldn:29,ci_db_result:[144,51,82],"return":[0,80,82,93,41,43,9,117,45,51,100,25,144,106,141,27,69,70,29,72,74,44,76],prev_tag_clos:56,than:[79,0,1,73,5,120,93,41,9,124,44,87,127,89,12,129,51,95,100,136,125,142,104,141,27,144,70,29,30,31,75,78],accept_charset:[88,29],file_5:130,sentenc:20,pollut:29,file_1:130,sess_use_databas:30,slight:30,ff0:[142,30],ssss:74,framework:[9,122,105,29],oci8:[64,29],cer:29,compound:[144,29],timezone_menu:[86,29],custom_result_object:51,bigger:140,"_helper":103,redesign:29,table_data:119,set_mod:104,cubrid:[30,64,29],troubleshoot:47,my_cach:60,userid:91,gmt_to_loc:86,authent:29,micro:140,achiev:[0,30,51,18,98],autoinit:29,innodb:[12,70],sha384:73,is_fals:138,fulli:[11,29,120,50,124,18,53],intervent:[92,104],backtrac:29,errata:29,truncat:[142,144,29],do_upload:[123,29],weight:98,needless:29,korea:86,hard:[49,87,73,98,29],addressbook:126,ci_session_dummy_driv:98,crontab:29,realli:[73,12,29,30,31,75,62,44,134,98,126,100,136],playstat:29,finish:[125,143,103],next_tag_open:56,expect:[57,69,29,120,110,131,41,98,138,8,134,123,97,116,9,91,145,135,136],fist:29,todd:144,attachment_cid:[23,29],http:[0,77,41,100,29],db_forg:29,beyond:[48,144],todo:[146,129],orient:27,some_valu:98,ftp:[120,47,29],vladivostok:86,safeti:98,or_lik:[144,29],miss:[89,29,120,75,140,64],nepal:86,form_fieldset_clos:[87,29],publish:[91,71],thirdparamet:86,send_error:116,health:41,add_kei:[81,70,29],print:[142,23,144,29,102,75,146,6,36,45],dir_write_mod:[108,29],bui:125,subsubsect:74,occurr:130,w3school:75,file_nam:[46,123,103,129,29],textil:74,asp:75,proxi:[91,29],mylibrari:30,advanc:[120,57,30,29],create_captcha:140,samara:86,differ:[132,2,120,7,86,125,46,126,88,10,91,49,93,14,98,127,72,56,138,19,21,22,103,143,107,73,23,144,141,29,30,75,37,148,119],asc:144,quick:136,reason:[56,0,89,73,91,144,29,120,130,30,31,44,103,125,52,116,45,98,134,136],base:[5,2,82,45,124,86,87,10,12,130,50,14,6,136,122,139,30,105,144,106,65,69,70,29,109,72,31,75,147,38],believ:98,sku_123abc:125,ask:[136,29],teach:57,phd:110,basi:[135,18,29],thrown:60,"_blank":75,english:[132,142,3,29,32,46,88],omit:[69,144,29,120,30,98,116,125,19],success:[23,12,70,29,109,74,60,82,51,144,7,44,125,69],caption:[119,29],golli:142,get_config:[108,29],csr:29,threat:135,"_error_handl":[108,29],my_sess:103,undergo:29,file_writ:29,assign:[132,27,131,23,69,70,129,29,72,51,21,7,103,144,123,117,44,9,98,37,73],feed:[6,44,29],major:[49,144,74],notifi:23,obviou:[45,136],row_arrai:[106,51,21],feel:[110,96,133],articl:[5,19,82,21,75,45,98,126],lastnam:[110,91],ci_db:103,mod_mim:123,sometim:[43,46,134,69,91],footprint:[48,78],cell_end:119,done:[132,0,131,30,91,29,92,50,74,21,73,77,128,124,133,27,110,98,136,72],least:[29,73,98,134,46,100],directory_trigg:29,form_open_multipart:[87,123,29],stabl:[38,136],init_unit_test:66,use_t:29,guess:[120,29],error_arrai:[46,29],script:[39,82,120,41,9,124,45,46,63,49,92,51,52,98,135,100,101,138,59,134,81,144,29,109,75,116],column_kei:25,interact:[45,73],gpg:29,yekaterinburg:86,construct:[56,57,29,125,117,9],tradition:12,header2:23,stori:98,underlin:74,order_bi:[144,29],statement:[144,70,82,29,44,146,69],cfg:29,dbdriver:[89,141,72],is_arrai:[120,27,138],scheme:[81,131,29],store:29,schema:[89,116,21,81,29],free:[120,98,51,71],adher:[120,78],error_views_path:29,ctype_digit:[134,29],behind:[49,26],compens:29,php_sapi:100,johndo:[87,46,98],count_all_result:[144,29],php_error:[41,29],apppath:[108,109,29],pars:[120,92,13,75,29],logged_in:[98,75],myclass:[56,79,144,120,124,9],grace:29,fred:[130,143,119],king:70,kind:[98,30,41,71,142],cookie_secur:[98,29],aac:29,abr:19,remot:[143,91,29],orhav:[96,29],remov:[144,70,29,14,18,134,100],migration_en:81,dtd:6,jqueri:29,reus:[98,144,21],pragma:92,str:[1,82,120,87,46,63,130,13,135,100,138,20,36,25,142,23,29,42,75,145,76,116],consumpt:51,stale:96,toward:[49,98],beij:86,"_sanitize_glob":29,fixat:98,randomli:[134,140],cleaner:[126,29],comput:[45,144,91],mpeg3:29,deleg:131,strengthen:29,sssss:74,valid_email:[121,46,30,29],favicon:6,packag:[120,95,50,29],is_support:[60,29],sport:46,expir:[29,92,31,140,85,18,98,101],mod_rewrit:5,reset_valid:[46,29],"null":[144,70,82,29,51,25,100],format_numb:125,query_build:[11,30,89,103],option:[132,0,73,3,5,120,93,41,7,87,123,124,86,9,46,126,88,146,89,12,129,101,49,82,51,14,143,6,18,102,98,135,72,56,138,125,19,144,77,60,103,118,68,104,105,25,91,141,65,142,23,69,70,29,109,92,30,74,75,145,34,147,39,81,148,78,119],sell:71,mountain:86,reset_data:144,nozero:130,"_prep_filenam":29,relationship:93,lib:29,remote_addr:98,replyto:23,self:[108,123,29],violat:29,troublesom:29,port:[89,23,91,29,60,143,98],undeclar:142,also:[132,0,50,39,120,93,41,114,73,82,45,85,87,5,44,86,68,9,46,88,146,89,90,12,129,130,13,51,14,143,136,135,52,53,131,98,15,16,17,101,56,125,115,144,59,77,60,61,21,103,118,28,134,25,91,107,65,66,67,23,69,70,29,109,92,30,74,31,75,145,32,33,34,100,35,116,124,81,38,123,119],useless:[76,77,30,29],elapsed_tim:[37,92,82],brace:[120,110,146,20],signup:46,vnd:29,file_typ:123,distribut:[89,71,29,103,98,38],backtrack_limit:29,victim:134,choos:[39,81,12,144,29,49,73,42,75,104,98,46,141],reach:21,chart:47,font_siz:[140,29],most:[73,3,41,134,123,86,9,46,126,88,142,12,49,51,18,98,141,99,138,19,20,59,60,143,104,105,91,107,64,27,23,29,110,30,44,116,119],plai:62,protect_al:1,whether:[132,39,1,92,82,120,41,7,31,43,125,85,86,87,46,88,10,11,12,49,130,13,14,6,52,98,135,100,101,137,138,19,139,102,60,89,22,103,144,143,104,134,25,63,107,141,131,23,69,71,29,109,110,73,74,42,75,116,123],plan:136,myisam:12,last_act:[95,30,98,29],selector:39,charg:71,tonga:86,x11r6:49,clear:[23,29,49,73,31,103,84,30,98,107,78,119],bdb:12,cover:[10,91,8],ci_db_forg:[70,103],roughli:104,ext:[65,29],part:[132,10,1,23,91,27,49,57,29,144,109,120,104,105,25,98,136,107,142,119],clean:[91,129,29,60,30,63,136,135,101],enctyp:123,latest:[81,136,131,29],awesom:131,s_c_ver:120,attach_cid:23,mcrypt_mode_cfb:104,carefulli:[73,148,31,104],alphanumer:29,phooei:142,top_level_onli:[109,96],row_object:51,appver:29,session:[47,89,29,50,77,117,9,16,118],particularli:[12,29,131,93,42,103,126,135],worri:[73,41,86,136],exit_error:[108,41],font:[49,140,29],fine:[45,75],find:[132,0,40,41,7,123,126,88,12,93,52,98,72,137,58,59,91,27,29,110,73,31,146,116,136,148],impact:[96,73],access:[0,2,5,120,93,7,117,9,89,13,51,94,134,100,72,60,30,104,144,106,28,69,70,29,109,73,31,75,77,50,38,78],pretti:[30,101],url_help:27,myutil:69,unattend:98,ruin:29,less:[142,1,29,120,41,48,75,46],solut:[73,110,30,121,25,98,78],is_referr:[88,29],validate_url:[116,29],"public":[0,73,120,9,123,117,45,46,10,89,91,129,13,131,6,98,72,21,22,105,81,144,29,30,50,136,38],couldn:29,templat:[65,47,82,29,41,146,78],factor:[48,30,144,31],"_server":[98,101,30,14,29],i_respond:91,charcter:73,xss:[100,29],unus:[98,29],albeit:137,amount_paid:144,express:[144,29],ffield_nam:29,blank:[23,69,29,49,124,103,75,120,52,53,46,101],nativ:[89,2,12,82,29,51,44,117,105,25,100],ci_log:29,mainten:29,quotes_to_ent:[130,29],xss_clean:[85,63,96,29],liabl:71,post_controller_constructor:[124,29],restart:29,set_capt:119,callback_foo:46,builder:29,repair_t:69,uri_seg:[56,29],date_cooki:86,crt:29,set_dbprefix:[144,44,29],whenev:[120,30,41,31,29],full_tag_clos:56,rfc:[23,86,73,29],common:[12,29],newest_first:125,greater_than:[46,29],empty_t:[144,29],delete_dir:[143,29],set_error:116,crl:29,arr:120,set:[89,12,70,29,82,51,31,44,76,144,106,141,136],blog_templ:110,php_eol:[45,101],backtrack:29,cookie_prefix:[98,85,3,101],organ:[31,29],vinc:137,utf8_en:[108,29],seg:145,simpler:[124,29],see:[39,73,0,120,93,105,7,31,9,123,5,86,45,46,89,12,129,92,51,14,96,53,133,121,98,54,100,101,19,142,60,21,22,103,140,91,63,106,141,27,131,144,70,29,109,30,74,42,75,34,117,134],sec:74,arg:[130,119],reserv:29,horizont:49,flavor:[3,103],php:29,chose:[98,73,104],legend_text:87,simultan:141,mt_rand:130,inconveni:[13,30],someth:[0,50,125,123,124,86,9,46,88,89,91,129,92,93,14,52,98,135,101,56,103,140,107,65,143,144,110,74,75,116,136],particip:126,debat:29,imagejpeg:29,inner:[144,124,29],won:[23,144,73,92,30,51,31,75,77,117,93,98],migration_t:81,source_imag:49,mismatch:29,experi:[62,98],nope:104,compliment:106,altern:29,stored_procedur:29,prefix_singl:82,latin:[134,29],imagemagick:[49,62,29],numer:[11,81,19,29,109,130,30,93,144,125,147,86,134,25,46,101],all_userdata:29,this_string_is_entirely_too_long_and_might_break_my_design:142,javascript:[47,29,13,74,96,75,85,87,134,100],output_paramet:91,isol:29,call_hook:29,some_par:28,sandal:0,cell_alt_end:119,"_create_t":29,raw_input_stream:[101,29],distinguish:120,slash_item:[30,7],date_lang:86,classnam:[39,34],struct:91,verbos:[120,14],both:[73,84,117,125,91,49,13,98,100,136,104,144,107,69,70,29,30,74,75,145,50,101],last:[29,19,82,92,51,103,44,76,146,101],delimit:[23,69,29,30,93,75,123],is_write_typ:[82,29],hyperlink:75,is_natural_no_zero:46,event:[29,31,75,123,7,87,46,101],pg_exec:44,imageid:140,pdo:[89,29,51,76,141,64],add_suffix:132,context:[98,73],forgotten:134,mb_enabl:[25,108,29],pdf:[23,74,29],author_id:76,set_empti:119,whole:[10,30,51,73,29],wm_y_transp:49,load:[69,70,29,51,74,31,117,106,141],xspf:29,markdown:74,simpli:[132,0,73,39,121,41,7,125,123,124,44,9,46,126,127,12,129,49,130,131,95,98,101,56,138,144,103,143,105,91,107,65,27,23,69,29,110,30,31,75,34,116,117,37,136,119],cast5:73,point:[136,144,31,100,29],instanti:[0,48,91,82,29,51,124,98,117,141],schedul:30,format:[27,80,69,29,74,76,146,25,134,136],arbitrarili:46,header:[0,139,129,29,120,75,77,100],fashion:[57,73],littl:[110,138,148,31,116],total_rseg:145,linux:[45,98,88],mistak:[30,29],db_connect:[82,29],csrf_exclude_uri:[135,29],file_exist:131,backend:[60,3,29],expressionengin:[49,122,30],identif:29,unsuccess:12,user_id:144,devic:[120,88,29],create_t:[81,70,29],empti:[0,120,86,46,87,97,88,51,6,135,56,21,144,107,23,69,70,29,75,116,37,119],implicit:29,whom:71,secret:[134,73,104],comment_textarea_alia:13,wm_hor_align:49,your_lang:[147,86],cell_alt_start:119,devis:29,nonexist:29,invis:39,save_path:98,load_class:[108,29],imag:[47,23,63,29,13,123,7,140,96,6,75,134,46,148,149,150,141],array_replace_recurs:[25,29],restrictor:144,sess_save_path:[98,30,29],gap:81,phpdocument:29,coordin:49,understand:[10,12,53,133,91,98],file_write_mod:[108,29],func:[46,29],demand:[30,12],other_db:[69,70],vulner:[30,29],weekdai:19,include_bas:103,foreign_char:[142,96],ignit:29,look:[43,136,44,29],localhost2:89,bill:130,histor:[130,30,73],cluster:[31,104],"_has_oper":29,"while":[73,120,93,41,125,46,11,91,49,51,14,133,98,101,89,81,141,142,23,144,29,109,30,74,146,38],unifi:29,smart:12,abov:[0,50,5,93,7,87,123,124,44,86,9,46,89,142,91,129,49,130,13,51,146,6,137,18,98,141,72,56,138,125,19,136,20,60,21,22,103,118,73,104,105,144,106,107,64,27,23,69,70,71,29,109,110,30,75,76,77,116,39,117,37,101,119],checksum:29,anonym:46,ci_output:92,loop:[120,51,29],javascript_ajax_img:39,subsect:74,real:[23,91,129,29,74,122,37],pound:142,uri_str:[77,145,75,29],nl2br_except_pr:[42,20],readi:[29,49,13,103,133,106],member_ag:144,"3g2":29,pakistan:86,last_link:[56,29],jpg:[142,23,139,49,92,140,123,6,107],password_default:25,itself:[144,29,120,41,73,51,98,46,126,150,136],rid:96,saferplu:73,recompil:107,row_alt_start:119,form_checkbox:[87,29],shirt:[87,125,93],grant:71,limit_charact:116,msexcel:29,belong:30,myconst:120,up95:86,shorter:[46,30],redisplai:46,decod:[29,73,42,96,104,134,135],onclick:87,octal:[49,109,143],date_rfc1036:86,blogview:129,conflict:[81,7,29],bom:120,parse_templ:19,archiv:[30,107,21,29],imagin:131,optim:[31,29],"3gp":29,defeat:6,piec:[91,60,73,21,104,116,98],moment:[37,12],strength:96,mousedown:39,user:[120,93,41,44,86,9,89,13,51,18,134,99,137,140,105,25,28,69,70,29,109,74,31,75,146],"_exception_handl":[108,29],extrem:[62,96,126],repopul:[46,29],robust:[121,23],wherev:18,transitori:104,cilex:74,recreat:[143,107],subpackag:120,travers:[135,11,63],task:[45,27,126,78,98],unicod:[120,29],discourag:[120,30],eleg:28,somet:76,exit__auto_min:[108,41],parenthes:144,honor:29,person:[10,23,71,135,103,123,107],tb_id:116,gambier:86,elev:107,traffic:[91,129],table_exist:[43,82],result_id:[2,31],anybodi:98,full_path:123,predetermin:46,add_package_path:103,ci_secur:[135,63,42,29],ceo:122,"_file":29,rule:[0,29],obscur:[49,73],vietnames:29,shape:[137,6,91],unix_to_tim:86,mysql:[89,69,70,29,82,144,44,76,86,12,141,148,64],love:[126,6],question:[29,130,58,31,44,8,6,133,136],sidebar:129,failsaf:101,move:[50,51,127,29],cut:[51,29],errand:129,point1:37,restructuredtext:74,theoret:73,m4u:29,mydatabas:[141,72],num_link:[56,29],label_text:87,tweak:29,xml_rpc_respons:91,unlik:[27,91,120,60,30,41,75,125,101],subsequ:[39,128,18,103,29],app:[62,37],myothermethod:124,build:[0,89,50,91,5,49,74,30,41,31,75,59,133,93,144,92,127,135,126,78,109],bin:49,australia:86,varchar:[81,70,140,21,95,113,116,98],transpar:[49,92,29],improperli:29,is_writ:100,file_ext_tolow:[123,29],get_post:29,intuit:62,corner_styl:39,nginx:14,game:137,backtick:[44,29],bit:[29,73,82,30,74,104,98,126,135,136],characterist:73,array_pop:27,intel:88,table2:[144,69],table3:144,table1:[144,69],captcha_tim:140,heading_cell_start:119,post_system:124,userfil:123,alpha_numer:46,resolv:[102,136,29],enable_hook:[124,53],collect:[27,31],"boolean":[73,82,120,43,125,123,44,86,87,46,88,11,91,129,49,93,6,53,98,135,100,72,56,138,19,139,89,103,143,144,107,141,65,23,69,29,109,110,30,75,34,116,101],mycustomclass:87,highlight_str:142,password_verifi:25,popular:[98,60,73,12],smtp_crypto:23,word_limit:[142,29],xmlrpc_client:91,encount:[29,30,41,103,146,135,101],mylist:6,often:[89,2,20,120,73,14,8,30,131,98],mcrypt_rijndael_256:104,sess_match_ip:98,fcpath:108,creation:[49,29],some:[132,0,2,39,120,121,41,73,8,43,87,138,5,86,9,46,117,88,10,89,91,129,49,13,93,14,96,52,133,98,135,100,101,56,57,139,142,60,21,22,103,81,105,25,144,141,108,27,131,23,69,29,109,110,30,74,31,75,124,37,134,82],back:[56,81,12,29,60,73,93,31,22,21,82,69,91,25,46,126,135],if_not_exist:70,sampl:[80,70],get_zip:107,error_gener:[65,41],redi:29,phpredi:[98,60],scale:78,chocol:103,culprit:29,sku_965qr:125,exect:29,exec:[100,29],per:[69,18,29],foreign:[69,29],usernam:[132,89,23,91,72,144,146,143,98,87,46,141],substitut:110,larg:[0,23,69,29,120,30,51,145,62,87,9,91,78,119],slash:[131,29,120,130,30,93,7,145,143,124,134],unsanit:44,reproduc:136,newdata:98,machin:81,id_:93,object:[82,2,31,141,29],run:[84,89,2,144,70,29,82,51,31,44,43,76,106],field_id:13,irkutsk:86,raspberri:29,agreement:[47,126],cal_cell_content_todai:19,step:[27,58,50,31,134,136],form_dropdown:[87,29],news_item:21,db_driver:29,prep_for_form:[46,29],concoct:104,victoria:86,mssql:[82,64,29],cautious:104,reduce_linebreak:42,sess_encrypt_cooki:[30,103,29],constraint:[98,81,134,70,29],row:[76,106,82,144,29],extract_url:116,prove:[120,121],highlight_cod:[142,29],manag:29,rowcount:29,idl:[82,141,29],regular:[82,70,29],add_row:119,product_opt:125,mcrypt:[30,29,73,96,104,54],update_entri:[91,72],uncach:144,cookie_path:[98,3],reduct:29,upload_data:123,primarili:57,init_pagin:29,within:[0,2,70,29,74,117,18],pdostat:29,upgrad:[47,134,29],product_edit:93,ci_except:29,jimmi:130,todai:19,alpha:[29,130,134,125,46,101],contributor:122,announc:122,total_queri:82,pcre:29,websit:[98,30,29],inclus:29,institut:[122,71],bangladesh:86,next_prev_url:[19,29],spam:[75,116],fledg:8,proprietari:29,sock:60,stylesheet:[142,6,75,7],"long":[27,23,19,70,29,120,73,140,134,25,98,127,101],custom:29,optimize_t:[69,29],flashdata:[30,104,29],forward:[81,51,30,93,7,145,135],update_post:91,cur_tag_open:56,etc:[39,2,82,120,43,9,117,45,46,88,11,91,129,92,98,135,136,19,142,102,36,89,62,134,141,27,23,144,70,29,73,74,31,76,116],files:109,zealand:86,doctyp:[6,29],repeatedli:73,great:[126,6,136,29],said:[98,30,73],twenti:56,current_url:[75,29],add_insert:69,perman:[120,98,96,104],link:[27,3,29,120,102,13,74,75,6],translat:[109,93,69,70,29],newer:[25,120,64,136,29],atom:[60,86,29],azor:86,ci_form_valid:46,ci_:[9,27,96,105,29],angri:6,info:[63,29,109,41,93,42,75,100],bevel:39,utf:[23,29,120,6,92,103,97,35,116,87,88],consist:[65,10,142,29,138,132,96,98],cid:23,myfield:87,seven:[91,19,119],mod_mime_fix:[123,29],cal_cell_cont:19,highlight:[142,19,29,120,30,74,119],similar:82,curv:133,ci_input:[63,29,30,85,105,101],enlarg:113,exit_success:108,rowid:125,bind:[82,29],trans_start:[12,82],parser:[47,111,120,29,78,136],hash_pbkdf:134,mouseup:39,doesn:[48,50,144,29,121,30,51,131,73,25,146,87,100,134,9,98,37,107,58],dog:[39,37,36],convert_text:120,incomplet:[116,29],oof:120,guarante:[98,135,38],apache_request_head:101,rewritecond:5,gecko:88,bracket:[124,29],another_mark_end:37,anyth:[89,73,29,30,93,75,125,104,87,134,37,136,127],crypt:25,sequenti:[81,29],form_valid:[99,29],water:91,invalid:[19,91,29,49,120,86,98,46,135],id_123:93,smtp_pass:23,setenv:14,librari:[0,80,144,29,40,74,117,105,141,100,136],trans_begin:[12,29],ellipsi:[142,20],xss_filter:30,particular:[132,82,7,43,124,125,46,127,12,129,130,51,98,88,142,144,91,141,27,69,71,72,31,75,76,116,37],is_mobil:[88,29],ctr:73,draw:140,rijndael:73,drop_column:[70,29],elsewher:[125,98],js_library_driv:39,eval:[146,100,29],curtail:116,cal_cell_no_cont:19,smilei:[83,29],um35:86,index_pag:[6,58,75,29],curl:45,algorithm:[63,29,96,104,25,134],vice:49,svg:6,callback_username_check:46,sftp:143,parse_smilei:13,depth:[119,11,73,29],xmlrpc_server:91,key_prefix:[60,29],image_librari:49,far:[46,91,98,82],fresh:[144,30,94,95,96,97],script_head:39,slash_seg:145,scroll:39,set_output:92,oop:[9,132,29],fopen_read_write_create_destruct:108,basic11:6,partial:[119,29],examin:[125,128,91,144],scratch:[126,78],mysql_to_unix:86,rewriteengin:5,ellips:[142,6,29],last_upd:92,urandom:[25,30,135,73],do_hash:[96,63,29],router:[32,128,105,30,29],compact:120,ci_session_driv:98,privat:29,current_us:31,get_mime_by_extens:[109,29],you_said:91,friendli:[65,5,58,73,74,29,75],send:[137,0,69,139,129,29,109,121,30,75,82,120,85,124,87,134,37,141,136],code_start:37,lower:[89,29,130,73,93,75,123,9,100,101],blaze:98,opposit:[39,86],aris:71,function_exist:100,bcc_batch_siz:23,sent:[0,82,121,41,124,46,128,91,92,52,18,98,136,137,139,103,23,70,29,110,116,37],passiv:143,unzip:50,convert_ascii:116,whichev:144,"_plugin":29,vlc:29,plain_text:73,account:[0,101,86,78,29],blog_id_site_id:70,ofb8:73,spoof:29,syntax:[84,141,144,44,29],smtp_keepal:[23,29],relev:[89,42],tri:[135,53,7,58],db_debug:[89,72,141,29],byte_format:[147,29],magic:[98,29],succeed:82,http_client_ip:[101,29],notabl:[30,51,29],non_existent_directori:102,ci_config:[30,75,7,29],lombardi:137,overli:[120,31,29],"try":[89,144,44,29],last_queri:[76,77,82,29],noninfring:71,mysubmit:87,pleas:[0,50,3,4,39,7,31,87,136,86,9,46,126,146,90,63,112,49,13,77,94,95,96,97,52,53,98,141,15,16,17,72,125,115,66,60,92,103,148,118,68,99,104,105,25,106,73,65,27,67,28,144,29,109,54,134,30,42,75,55,32,33,34,113,114,35,61,149,37,101,38,142,150],malici:[134,135],impli:71,constrain_by_prefix:[82,29],cdr:29,set_radio:[87,46,29],myuser:50,anoym:124,cfb:73,encourag:[73,133,29,93,30,51,7,62,75,53,104,116,9,134,106,148,95],crop:[49,62,29],date_atom:[30,86],cron:[45,144],video:29,ci_db_driv:[82,29],download:[69,29],odd:145,click:[27,39,120,13,75,87],"_is_ascii":29,compat:29,index:[108,0,29,51,41,31,14,124,74,105,45,134,106,127],phpdoc:136,sapi:101,compar:[144,29],use_global_url_suffix:[56,29],page2:144,methodolog:124,"_set_overrid":29,cal_cel_oth:19,xor_encod:29,experiment:[39,30],helper3:27,helper2:27,helper1:27,text_watermark:29,this_string_is_:142,bird:37,can:[0,2,5,7,8,9,11,12,13,14,19,20,21,22,28,25,27,23,29,30,31,34,37,39,40,41,42,43,45,46,49,50,51,52,18,56,57,59,60,65,69,70,72,73,74,75,76,77,132,81,82,85,86,87,88,89,91,92,93,95,6,98,99,100,101,103,104,105,106,107,109,110,44,116,117,119,120,123,124,125,126,127,128,129,130,131,134,135,136,137,138,139,140,141,142,143,144,145,146],ci_sessions_timestamp:98,sybas:[30,29],imagepng:29,preg_quot:29,is_cli_request:29,elips:6,len:130,sqlsrv_cursor_stat:29,closur:[124,29],hkk:29,logout:98,blog_name_blog_label:70,session_write_clos:98,safer:[76,144,44],vertic:49,encryption_kei:104,crypt_blowfish:25,design:[5,73,19,29,110,13,44,62,104,125,134,126,119,72],select_avg:[144,29],ineffect:30,metro:145,artifici:134,larger:[49,96,41],technolog:[122,71],alaska:86,mb_substr:25,migration_typ:[81,29],cert:29,ci_pars:110,another_field:[30,70],heading_cell_end:119,"_fetch_uri_str":29,typic:[56,0,11,91,86,129,27,49,93,72,51,31,44,103,59,104,134,125,98,88],set_ciph:104,wm_hor_offset:49,chanc:[137,98,30],field1:[144,101],firefox:29,danger:[100,29],foreign_key_check:[69,29],new_fil:143,approxim:104,base_url:[56,29,75,97,117,7,9],bad_dat:86,standpoint:48,api:[39,91,29,73,14,135],blog:[27,0,81,144,129,72,110,13,93,31,75,103,143,116],oval:6,apc:29,file_ext:123,day_typ:19,blog_set:7,heading_next_cel:19,sorri:98,tailor:[49,56,23,73],cache_expir:0,zip:[47,111,69,29],commun:[89,91,29,122,98,136],ci_control:[108,0,131,81,91,129,72,13,21,96,117,45,46,123],doubl:[1,69,144,29,120,130,20,93,42,87,91],seamless:104,my_arch:107,"throw":29,implic:105,eleven:[142,119],usr:[49,23],clear_data:107,expiri:[98,136],rick:[122,76,44],sort:[125,98,91,145],comparison:[120,138,144,29],wincach:29,error_lang:132,benchmark:[0,105,124,29],about:[82,136,29],balanc:144,wm_text:49,trail:[143,29,130,30,93,7,145,124],from:[2,82,29,31,106,141,136],listen:[98,91],actual:[56,39,131,73,139,29,93,30,41,110,132,121,140,102,25,98,100,64],getter:98,harvest:[19,75,29],focu:[39,126,74,78,57],firebird:[64,69,29],signific:46,retriev:[106,82,31,29],alia:[30,19,144,29,92,13,51,42,75,103,82,130,85,86,98,87,63,136,100,101],critic:134,cumbersom:12,annoi:6,smart_escape_str:29,obvious:2,collat:[89,70,29],meet:[48,120,73,134,46,136],valid_base64:[46,29],has_userdata:[98,29],aliv:29,control:[136,144,31,29],distrubut:98,sqlite:[89,64,29],weaker:73,tap:[124,29],pre_control:124,chosen:[50,12,73,60,30,95,98],process:[12,29,51,76,18,141],lock:[109,98,30,29],tax:31,high:[142,48,29,73,104,116,98],tag:29,entry_id:116,tab:[69,29,120,74,75,135],epallerol:29,sought:144,onlin:12,serial:[31,29],image_size_str:123,everywher:98,surfac:29,is_str:138,filepath:[124,143,107,103],soon:[30,148],tamper:29,six:119,database_exist:[69,29],xml_convert:1,build_str:120,crlf:[23,29],copyright:[49,71],subdirectori:[28,103,29],instead:[0,1,120,43,45,124,86,87,63,9,130,13,93,6,134,139,105,144,141,27,69,70,29,109,31,146,36,117],reestablish:[82,29],zip_fil:107,convers:[29,14,103,20],stock:[95,34],docblock:[120,29],loui:137,likewis:49,prolif:120,overridden:[0,104,29],singular:[48,36,29],interchang:[73,103],watch:[41,21],table_clos:[19,119],act:[131,91,129,29,30,103,85,135,100,101],sundai:[19,86],pasteur:137,my_cached_item:60,attent:[62,29],discard:103,redund:29,dbutil:[69,103],exit_config:108,trim_slash:[130,29],chown:98,some_var:41,drop:29,"20121031100537_add_blog":81,friendlier:85,light:104,m4a:29,robot:[6,88,29],suppress_debug:143,issu:29,webroot:134,days_in_month:[19,86,29],wordwrap:[23,29],allow:[0,73,120,7,87,123,86,9,46,126,48,12,49,130,13,93,146,53,98,135,101,56,138,125,19,144,60,103,81,105,91,65,68,69,29,109,110,30,31,75,145,76,34,147,116,134,119],append_output:[92,29],fallback:[120,30,136,29],per_pag:56,furnish:71,json_encod:92,y_axi:49,include_path:[109,29],screensend:82,cryptographi:73,sess_regener:98,insight:8,optgroup:[87,29],product_id:145,passion:6,comma:[23,69,29,98,116,46,136],gender:145,is_dir:143,georg:137,bunch:30,get_csrf_token_nam:[94,135],enclosur:69,cubird:70,outer:144,reilli:130,pecl:98,wget:45,adjust_d:19,maxlifetim:98,fetch_:30,form_password:87,button:[87,46,29],apache2:102,therefor:[80,29,30,31,98,125,46],pixel:[49,123],img_height:140,double_encod:29,docx:29,fourth:[87,142,23,69,86],handl:29,auto:[141,12,29],remove_package_path:103,overal:29,camino:88,auth:[93,29],p10:29,mention:[98,73,29],p12:29,password_bcrypt:25,overkil:[9,27,105],tbody_clos:119,front:[109,128,29],profiler_no_memori:29,csrf_protect:[135,29],escape_identifi:[82,29],strive:48,models_info:109,another_nam:98,somewher:107,data_to_cach:60,xml:29,edit:[93,75,29],unlimit:70,wm_x_transp:49,tran:6,json_unescaped_unicod:92,ping_url:116,scrollbar:75,myfold:[143,107],mystyl:6,batch:[23,144,29],disregard:68,mycheck:87,error_report:41,register_glob:29,pygment:74,few:[73,19,29,120,30,93,22,8,53,116,25,98,126,136,100,101],yakutsk:86,better_d:86,due:[39,73,69,29,30,144,138,96,98],intellig:[129,29,75,62,7,141],"_lang":132,einstein:137,product:[65,0,89,50,29,30,93,14,7,145,81,5,134,125,98,73],consum:[37,77,29],sha224:73,meta:[43,6,51,29],"static":[47,112,94,95,96,97,52,53,54,55,17,18,57,115,21,65,66,67,68,29,15,30,16,32,33,34,113,114,35,61,118,148,149,150],driver_nam:80,connor:130,our:[48,73,144,103,131,98,30,21,22,8,134,133,116,45,46,126],meth:[23,74],hiddenemail:87,"_after":70,special:[28,91,70,29,98,134,116,87,46,101],out:[108,137,23,91,71,29,49,50,31,22,8,82,120,146,81,134,87,98,136,100,73],variabl:[0,89,69,29,51,146,41,14,44,77,117,27,9,144,141,100,127],set_flashdata:98,reload:46,influenc:73,parse_str:[110,29],hmac_digest:73,some_librari:120,categori:[120,27],thoma:137,clockwis:49,rel:[11,23,72,49,102,29,103,109,123,6,124],inaccess:45,inspir:122,rec:6,plural:[36,29],char_set:[89,118,70,141,29],math:6,random_el:[137,27],ecb:73,insid:[132,28,3,29,110,30,74,144,22,124,105,98,117,107,127],sendmail:[62,23,29],frank:144,msssql:29,sess_cookie_nam:98,umark_flash:98,readm:[98,74],get_var:[103,29],get_wher:[144,21,29],transliter:142,releas:[30,38,100,29],csrf_regener:[135,29],group_id:120,chatham:86,bleed:122,greedi:[120,29],prefix_tablenam:44,marginleft:39,get_day_nam:19,select_sum:[144,29],nowher:102,indent:136,should_do_someth:74,tripled:73,migration_add_blog:81,could:[39,2,120,41,73,45,46,126,127,91,131,52,98,100,136,21,81,70,29,92,30,75,78],lexer:74,put:[0,30,51,45,123,87,46,127,12,129,49,13,93,18,98,101,56,138,58,21,140,134,91,23,144,29,73,31,44,116,37,119],email_lang:132,timer:[0,37,92,44],keep:[31,29],profiler_no_memory_usag:29,length:[142,82,130,29,43,18,25,134],unidentifi:88,wrote:[21,136],outsid:[39,5,73,142,29],url:[0,29,93,45,24,27,9,117,76,100],retain:[98,104,29],do_xss_clean:[96,29],timezon:29,south:86,softwar:[138,71,59,73,41,133],cache_info:60,delete_cooki:[85,29],diplay_error:49,blown:[110,138],blogger:91,ci_ftp:143,qualiti:[49,62,136],echo:[69,70,51,44,43,76,144,106],whoop:131,date:[144,106,72,69,29],proxy_ip:[101,29],submit:[132,87,85,86,46,125,97,10,9,49,130,51,6,53,134,136,19,128,22,140,144,107,141,69,29,31,44,76,123,119],pgp:29,quick_refer:29,owner:[98,134],child_on:28,shortcut:6,facil:136,b99ccdf16028f015540f341130b6d8ec:125,utc:86,prioriti:[23,29,73,41,103,98],forgeri:[134,29],fair:[135,12],timestamp:[81,19,29,30,140,86,98],newus:98,unknown:[146,30],licens:[10,47,29],perfectli:0,mkdir:[98,143],system:[89,12,29,40,31,44,144,136],wrapper:[60,51,82],avoid:[132,23,29,120,60,30,7,145,123,98,87,46,101],attach:[62,138,23,29],attack:[29,73,22,123,134,98,135,101],physic:23,which:[0,2,3,39,120,93,73,8,87,138,5,44,86,68,9,46,126,127,48,12,129,101,49,130,50,51,14,95,53,148,98,141,135,100,18,56,57,125,19,136,139,142,60,89,103,140,23,104,91,25,63,107,110,27,131,28,144,29,92,30,31,75,145,76,77,35,116,81,134,119],termin:[45,116,100,75,29],erron:29,"final":[0,142,124,29],ipv4:[46,101],find_migr:81,haystack:[25,27],lot:[51,42,22,105,98,135],big:29,subsubsubsect:74,fetch_method:29,col_arrai:13,third_parti:29,shall:71,accompani:30,essenti:136,ogg:29,exactli:[144,70,29,49,110,93,104,98,9,46,101],haven:[46,73,103,22,98],kamchatka:86,rss:[59,6,86],prune:45,detail:[39,73,91,29,49,60,30,41,14,7,103,62,120,85,53,134,9,98,106,96,126],jsref:75,structur:[84,29],charact:[1,73,82,120,86,87,46,88,89,49,130,92,93,6,53,98,135,100,101,20,22,104,134,25,142,23,69,70,29,109,30,74,42,75,113,35,116],claim:71,your_str:56,htaccess:[5,29,109,50,14,134,126],session_data:[98,77],sens:[59,27,30,29],becom:[56,5,48,23,19,27,49,73,103,75,120,131,135,119],sensit:[98,80,69,134,29],foobarbaz:60,signifi:140,stricter:135,pgsql:89,accept_lang:[88,29],send_error_messag:91,"function":[136,29],counter:49,codeignitor:29,faster:[110,73,75,52,98,126,78],terribl:[46,86],falsi:87,explicit:[120,29],basepath:[65,108,81,19,29,103,9],respons:[81,129,29,92,41,31,75,116],clearli:120,correspond:[132,3,120,40,7,123,46,91,129,49,130,13,93,98,99,19,21,22,4,110,31,145,77],sufix:56,corrupt:29,have:[0,3,5,6,7,8,9,10,12,13,14,15,16,17,118,19,21,22,23,25,28,29,30,31,32,33,34,35,39,41,42,43,46,48,49,51,52,53,54,55,56,116,65,66,67,68,69,70,72,73,74,75,77,81,82,85,86,89,90,91,92,93,94,95,96,97,98,101,103,104,105,110,44,112,113,114,115,61,117,120,123,124,125,127,129,131,133,134,136,137,138,140,141,143,144,145,18,148,149,150],close:[136,29],get_metadata:[60,29],member_nam:82,superobject:[124,29],pg_version:29,tb_date:116,migration_auto_latest:81,admin:[30,69],in_arrai:27,rout:[45,0,124,24,29],fileproperti:120,accuraci:29,tighten:29,mix:[132,137,82,93,41,7,85,86,46,91,130,92,51,6,98,135,100,101,56,138,139,60,21,103,81,25,107,142,23,144,74,123,75,145,147,119],discret:[27,28,29,85,46,119,101],cheatsheet:29,hkdf:73,codeigniter_profil:29,or_where_in:[144,29],mit:29,singl:[89,82,136,31,29],uppercas:[0,29,120,130,104,101],address_info:87,unless:[73,120,85,125,10,129,49,92,51,53,98,137,138,20,103,104,25,107,144,70,29,30,42,123],post_control:124,ci_cor:29,oracl:[89,64,144,29],galleri:49,textmat:74,row_alt_end:119,header1:23,form_validation_rul:30,eight:119,max_filenam:[123,29],deploi:[81,29],segment:[82,136,31,29],payment:144,page_query_str:56,newprefix:44,placement:29,expert:73,child_two:28,gather:[43,88],upset:6,set_error_delimit:[46,29],character_limit:[142,29],face:20,inde:[120,29],my_log:30,determin:[76,82,31,29],built:[87,123,131,75,101],constrain:29,stark:126,plaintext_str:104,fact:[98,30,129,104,73],my_bio:107,ci_user_ag:88,cal_cell_start:19,extension_load:104,send_respons:91,ci_sess:[95,30,113,148,98],model_nam:[103,72],bring:[122,96],new_imag:49,format_charact:[29,20],trivial:[98,136],anywai:[73,29],texb:[49,140],redirect:[5,23,91,29,93,75,117,9],dbcollat:[89,118,70,141,29],textual:19,locat:[132,0,50,39,41,7,124,86,9,46,88,89,49,13,131,98,127,99,72,60,103,65,27,29,30,75,145,116],strip_image_tag:[46,63,29],blog_entri:110,holder:71,illus:137,calendar_lang:3,mug:125,should:[132,0,50,3,39,120,40,41,73,8,45,123,87,5,44,86,9,46,128,89,91,129,101,49,13,93,131,94,95,96,97,52,53,98,136,141,15,16,17,18,138,125,19,115,142,135,21,103,118,68,104,134,25,64,65,66,67,23,69,70,29,109,54,112,30,74,31,75,55,32,33,34,113,114,35,61,124,6,81,148,149,150,119],jan:19,lightest:48,smallest:48,suppor:29,intrigu:6,elseif:[120,146,88],local:[108,0,82,29,74,105,9],hope:8,meant:[132,98],um10:86,strip_slash:130,gettyp:29,server_url:91,sess_match_userag:[30,29],convert:[142,1,63,29,130,42,75,86,87],error_404:[65,93,41,150,29],wordi:120,made:[39,48,131,144,129,29,30,21,22,94,95,97,52,38,136],csrf:29,orig_data:104,db1:141,target_vers:81,in_list:[46,29],edg:[49,122,29],cur_tag_clos:56,endless:25,application_config:120,getuserinfo:91,dishearten:6,enabl:29,is_uniqu:[46,29],nl2br:[42,20],upper:[49,101],or_wher:[144,29],bounc:39,htmlspecialchar:[46,119,100,29],sha:73,csrf_token_nam:[94,135],image_url:13,integr:[45,142,73],contain:[79,0,1,5,120,93,41,31,43,85,124,44,86,87,11,63,130,13,51,95,97,134,6,136,137,142,102,140,25,144,106,147,141,65,27,28,69,70,29,109,72,74,42,75,113,114,36,82],menuitem:110,grab:131,view:[82,144,31,29],conform:134,legaci:[0,30,98,104,29],avg:[144,29],cal_cell_blank:19,frame:6,knowledg:[10,98],exit_unknown_class:108,group_nam:141,qty:[125,29],popup:75,rc2:73,equip:36,form_input:[87,125,29],my_uri:29,sphinxcontrib:74,entitl:7,thead_open:119,unexist:29,log_file_extens:29,error:[89,82,136,29],segment_arrai:145,adodb:12,correctli:[142,131,29,121,20,73,41,76,107,136],record:[10,144,29,30,21,22,96,98,135],mimes_typ:29,pointer:[57,51,29],boundari:29,last_visit:29,newnam:[23,29],written:[56,0,89,29,49,30,41,21,22,146,75,138,116,18,27,122,98,109],stacktrac:136,ci_trackback:116,progress:39,multiplelanguag:132,equiv:6,thumbnail:49,get_compiled_insert:[144,29],get_dir_file_info:[109,29],perfect:[49,22],core_class:34,sole:101,bed:137,kei:[82,29],vrt:49,weak:134,matic:91,simple_queri:[82,44,29],salli:146,fopen_write_create_destruct:108,job:[45,131],entir:[56,27,143,69,29,120,110,57,50,31,14,105,98,9,46,37,60],joe:[143,144,130,93,145,146,87],has_rul:46,poof:29,argument:[45,144,29],parenthesi:[120,144,29],thumb:49,proxy_port:91,date_rfc850:86,quote_identifi:29,plugin:[65,118,90,35,29],wrapchar:23,goal:[47,126,78],mpg:29,incident:30,foobaz:120,april:29,my_calendar:103,cachedir:[34,141,89,29],grain:75,mysecretkei:103,db_set_charset:[82,29],gmdate:92,fopen_read_write_create_strict:108,messagebodi:46,onchang:87,comment:[0,29,144,31,27],shirts_on_sal:87,unmark:98,sqlsrv_cursor_client_buff:29,ci_db_pdo_driv:29,password:[89,141,29],hyphen:29,heavi:[98,31,141],print_r:[120,69,143,19,91],chmod:[98,143,29],walk:51,image_reproport:29,rpc:[47,111,134,29],"0script":100,respect:[89,69,29,130,30,93,87,96,25,46],tuesdai:19,mcrypt_mode_cbc:[104,29],append:[56,89,23,129,29,130,92,75,123,7,87],utf8_general_ci:[89,141,70,118],mailto:75,quit:[27,91,138,120,74,6,18,116,126],foofoo:120,tort:71,addition:[70,29,120,40,30,103,7,6,99,101],endforeach:[129,123,21,146,125,126],get_inst:29,form_prep:[87,29],watermark:29,compon:[48,19,29,125,98,136],json:92,write_fil:[109,69],treat:[5,12,82,29,6,107],date_w3c:86,popul:[19,29],xlsx:29,curli:[29,20],censor:142,overlay_watermark:29,interbas:[76,64,69,29],togeth:[56,144,129,131,44,140,46],user_guid:34,fail_gracefulli:[103,7],mouseov:39,present:[89,29],opac:49,request_head:[101,29],replic:98,multi:[89,129,29,110,6,124,125,98,119],cypher:104,"14t16":86,plain:[13,63,29,92,30,73,104,110,25,134],align:[49,125],some_photo:107,harder:137,return_path:[23,29],cursor:29,defin:[51,70,100,29],filename_secur:29,suport:86,encrypted_str:104,hex2bin:[25,73,29],decept:6,wild:29,get_compiled_delet:[144,29],sess_time_to_upd:[98,118],"8bit":25,mydogspot:36,layer:[25,134,64,21,29],purchas:125,customiz:[56,89],cell:29,almost:[98,11,73,145],field_data:[43,82,51,31,29],site:29,langfil:132,some_class:[74,105],ruri_str:[145,29],svg11:6,bigint:[98,140],substanti:[105,71,29],lightweight:132,sting:88,incom:[91,116],unneed:29,symbolic_permiss:[109,29],test_datatyp:138,free_result:[51,31,29],uniti:29,human_to_unix:[86,29],let:[89,2,144,82,29,31,44,43,18],welcom:[93,129,105],ciper:73,parti:[74,21],cross:[63,29,6,134,100,101],ci_tabl:119,member:[144,82,31,122,46,101],code_end:37,data_seek:[51,29],pingomat:91,android:29,fubar:103,difficult:49,prais:8,immedi:[124,18,29],columbia:[122,71],hostnam:[29,89,143,82,72,141],equival:[120,142,13,131],keepal:29,maxlength:[87,125,29],upon:[10,29,49,82,8,46,126,135,101],effect:[31,29],coffe:125,dai:[119,29,19,86,8],column_nam:70,retriv:101,raboof:120,having_or:29,sooner:[95,30],set_:87,alpha_dash:46,expand:[29,22,8],andretti:137,ofb:73,orig_nam:123,my_const:120,off:[56,0,143,12,10,29,31,76,123,87,134,136],center:[49,131],reuse_query_str:[56,29],epub:74,unl:30,colour:29,well:[132,39,120,86,45,46,126,88,11,6,98,100,56,138,64,23,144,29,109,30,146,78],set_cooki:[85,101,29],weblog:[91,116],exampl:[89,2,82,29,31,141,136],command:[144,141,69,29],filesystem:81,undefin:[138,29],audio:29,loss:98,sibl:28,usual:[5,73,91,39,49,30,93,103,75,142,85,143,98,46,126,107,123,101],next:[30,144,29,130,13,51,31,14,136],taller:49,display_overrid:124,newest:[125,81],camel:36,drop_databas:[70,29],half:98,obtain:[132,71],tcp:[98,60],jar:29,settabl:29,ci_xmlrpc:[91,29],some_cookie2:101,rest:[93,89,72,74,8],glue:131,new_post:91,sku:125,web:31,"50off":125,filter_validate_email:121,fopen:[109,29],idiom:132,disagre:136,multipart:[87,123,29],arandom:25,smith:[45,91],my_backup:107,myprefix_:101,add:[0,5,40,9,44,87,89,142,129,130,51,6,52,53,93,136,58,140,105,144,141,65,27,69,70,29,74,75,34,147,36],wm_vrt_align:49,error_email_miss:132,foobar:[120,137,72],display_pag:56,logger:29,suit:[49,138],warrant:96,old_table_nam:70,gmt:[92,86],exot:101,set_mim:139,xmlrpc:[120,91,29],agnost:82,varieti:[74,78,29],http_x_cluster_client_ip:[101,29],foreign_charact:29,camelcas:120,five:[125,130,119],know:[0,73,69,70,30,93,131,22,43,134,136,104,105,45,98,101,62,64],convert_xml:116,octal_permiss:[109,29],set_select:[87,46,29],"2nd":29,recurs:[11,143,29,96,25,107],get_item:[125,29],desc:144,insert:[82,31,29],resid:3,like:[0,1,2,3,5,120,93,7,43,45,123,87,124,44,86,9,46,126,88,146,89,142,12,129,101,49,13,51,14,143,82,96,137,53,98,127,135,100,72,56,138,125,19,110,20,59,103,22,148,140,68,104,105,25,91,107,73,65,27,131,23,144,141,29,92,30,74,31,75,145,76,34,50,116,39,117,37,81,134,78,119],lost:[98,29],safe_mailto:75,um11:86,up105:86,sessionhandlerinterfac:98,num_tag_clos:56,interfer:98,session_regenerate_id:98,unord:[6,29],necessari:[0,144,82,120,29,87,16],active_r:[65,118,29],messi:46,lose:[120,137,73],resiz:[49,39,62,75,29],get_temp_kei:98,xsl:29,path_info:3,unabl:[109,116],exceed:[23,141,82],revers:29,"_html_entity_decode_callback":29,migration_path:[81,29],suppli:[2,82,121,41,43,123,87,46,89,49,13,135,100,101,138,19,103,140,25,106,107,143,144,29,109,30,75,136],update_batch:[144,29],daylight:86,"export":29,superclass:120,proper:[29,73,144,82,120,30,41,123,46,135],home:[131,88],use_strict:138,form_item:46,transport:91,auto_typographi:[29,42,20],week_row_start:19,trust:29,lead:[120,130,145,93,29],broad:[78,26],"_get":[101,30,134,29],lean:[110,126],februari:29,leap:86,log_error:[132,34,41,29],default_method:0,speak:70,malsup:39,myfunct:124,um12:86,congratul:[98,22],liabil:71,acronym:29,journal:93,"10px":87,usag:[84,144,70,29,51,31,43],values_pars:29,facilit:29,maintain_ratio:[49,29],host:[89,82,60,29,6,98,78,141],hash_pbkdf2:[25,134,29],nutshel:[45,0],cal_cell_oth:19,although:[56,27,73,30,44,18,46,126,78],offset:[56,144,29,49,60,51,145,86,25],product_name_rul:125,parserequest:29,slug:[130,21,22],stage:124,rsegment_arrai:145,sbin:23,rare:[98,96,73,44],interven:92,last_citi:120,column:[82,29],prop:49,sqlsrv:[30,64,29],error_username_miss:132,entity_decod:[135,42,29],includ:[5,2,39,120,40,82,125,123,86,9,46,126,10,11,91,129,50,131,143,96,133,98,135,100,72,136,142,21,22,103,30,134,144,107,27,23,69,70,71,29,109,110,73,74,75,145,77,101,148,149,150],member_id:[87,91,31,82],constructor:[141,117,29],cal_row_end:19,repercuss:53,powerpoint:29,is_tru:138,creating_librari:34,set_data:[46,29],own:[0,12,29,31,44,117,25,144,136],delete_al:29,inlin:[23,6,13,29],"_ci_autoload":29,easy_instal:74,automat:[2,136,31,29],first_tag_open:56,warranti:71,guard:[73,104,116],wm_overlay_path:49,awhil:29,col_limit:119,relicens:29,hang:8,mere:[137,136],merg:[144,71,29,103,7,136],is_brows:[88,29],beep:142,myform:[87,46],ctype_alpha:29,unix_start:86,val:[144,120,92,103,140,46,119],pictur:[6,23],myforg:70,transfer:[101,73,143,29],howland:86,support:29,db_query_build:[144,29],beer:124,language_kei:[79,132],macintosh:88,standard_d:[86,29],much:[81,29,30,103,86,25,98,126,78,101],pool:[140,29],filemtim:29,"var":[29,120,60,103,98,100],venezuelan:86,strtolow:[93,29],application_fold:[50,127],new_data:104,total_row:56,unexpect:98,unwrap:23,bcc_batch_mod:[23,29],brand:88,my_model:118,multical:29,"_util":0,is_natur:46,bodi:[23,144,129,29,110,13,51,131,123,121,46,106],gain:[95,60,73,31,104],select_min:[144,29],dbforg:[103,30,70,81,29],highest:[23,107],eat:6,count:[82,29],group_start:144,cleanup:29,temp:110,rc4:73,wish:[132,39,120,41,7,125,124,87,11,91,129,49,50,93,18,98,101,138,19,142,103,104,144,27,143,69,70,73,75,145,37],unload:39,writeabl:109,flip:49,ci_model:[96,21,72],asynchron:135,directori:[89,82,40,29,31,18],below:[5,73,39,41,7,9,123,124,86,87,46,12,129,49,13,98,125,19,142,21,103,140,105,91,106,141,27,23,144,70,29,72,74,31,77,134,150,119],item_valu:7,limit:[106,2,29],tini:6,fetch:[137,144,129,29,60,30,51,43,25],view_cascad:103,otherwis:[132,0,73,121,85,125,49,93,14,134,100,101,103,98,25,108,23,69,71,29,30,37,136],problem:[142,29,30,41,133,98,46,136],weblogupd:91,reliabl:[98,88,142,75,29],evalu:[120,138,29],timespan:[86,29],"int":[82,41,85,86,125,11,91,130,92,51,143,6,98,135,100,101,19,60,21,140,81,104,25,142,23,144,70,109,73,74,145,147,116,37,119],dure:[132,27,72,29,134,77,124,98,25,46],filenam:[132,27,23,63,139,29,49,135,30,120,123,7,109,34,81,124,105,9,69,107],novemb:29,implement:[132,73,12,144,29,30,98,82,25,116,9,46],some_nam:98,userag:23,path_cach:120,mistaken:120,ing:29,up1275:86,httponli:[98,85,101],inc:122,spell:29,my_:[9,27,34,60,105],last_tag_open:56,percent:[134,86],front_control:65,virtual:98,plular:36,other:[5,73,3,82,120,41,43,9,85,87,124,86,45,10,12,129,130,50,14,6,134,100,118,125,19,104,141,65,27,144,29,30,74,123,75,136],bool:[132,39,1,92,82,121,41,7,125,85,86,87,46,88,11,63,49,130,13,51,6,98,135,100,101,137,138,139,102,60,36,103,144,143,25,91,107,23,69,70,109,110,74,42,75,116,123,119],bin2hex:73,rememb:[129,31,44,103,45,46],unix_to_human:86,php4:0,php5:102,myphoto:107,stat:[0,29],repeat:[130,6,29],misc_model:30,my_db:70,repeat_password:87,"class":[136,29],oci_fetch:29,june:[19,29],ci_email:[9,23],"_parse_argv":29,news_model:[21,22],theother:130,is_ascii:29,unnecessarili:29,mondai:[19,119],has_opt:125,throughout:[29,27,72,40,73,41,132,128,135,141],trackback:[47,111,29],clean_email:29,ci_load:103,basketbal:46,stai:[125,137],experienc:[49,98,120,73],thead_clos:119,sphinx:74,amp:1,strpo:120,baker:86,root_path:107,extran:29,bcc:[23,29],form_radio:[87,29],"_protect_identifi":29,portion:[25,144,41,71],emerg:136,ci_uri:[145,29]},objtypes:{"0":"php:method","1":"php:function","2":"php:class"},objnames:{"0":["php","method","PHP method"],"1":["php","function","PHP function"],"2":["php","class","PHP class"]},filenames:["general/controllers","helpers/xml_helper","database/call_function","installation/upgrade_b11","installation/upgrading","general/urls","helpers/html_helper","libraries/config","tutorial/conclusion","general/creating_libraries","DCO","helpers/directory_helper","database/transactions","helpers/smiley_helper","general/environments","installation/upgrade_163","installation/upgrade_162","installation/upgrade_161","general/caching","libraries/calendar","libraries/typography","tutorial/news_section","tutorial/create_news_items","libraries/email","general/index","general/compatibility_functions","overview/index","general/helpers","general/drivers","changelog","installation/upgrade_300","database/caching","installation/upgrade_152","installation/upgrade_153","installation/upgrade_150","installation/upgrade_154","helpers/inflector_helper","libraries/benchmark","installation/downloads","libraries/javascript","general/autoloader","general/errors","helpers/typography_helper","database/metadata","database/queries","general/cli","libraries/form_validation","index","overview/goals","libraries/image_lib","installation/index","database/results","installation/upgrade_141","installation/upgrade_140","installation/upgrade_220","installation/upgrade_221","libraries/pagination","tutorial/index","installation/troubleshooting","overview/mvc","libraries/caching","installation/upgrade_212","overview/features","helpers/security_helper","general/requirements","installation/upgrade_130","installation/upgrade_131","installation/upgrade_132","installation/upgrade_133","database/utilities","database/forge","license","general/models","libraries/encryption","documentation/index","helpers/url_helper","database/helpers","general/profiling","general/welcome","helpers/language_helper","general/creating_drivers","libraries/migration","database/db_driver_reference","helpers/index","database/index","helpers/cookie_helper","helpers/date_helper","helpers/form_helper","libraries/user_agent","database/configuration","installation/upgrade_120","libraries/xmlrpc","libraries/output","general/routing","installation/upgrade_202","installation/upgrade_203","installation/upgrade_200","installation/upgrade_201","libraries/sessions","general/libraries","general/common_functions","libraries/input","helpers/path_helper","libraries/loader","libraries/encrypt","general/core_classes","database/examples","libraries/zip","general/reserved_names","helpers/file_helper","libraries/parser","libraries/index","installation/upgrade_214","installation/upgrade_211","installation/upgrade_210","installation/upgrade_213","libraries/trackback","general/ancillary_classes","installation/upgrade_160","libraries/table","general/styleguide","helpers/email_helper","general/credits","libraries/file_uploading","general/hooks","libraries/cart","overview/at_a_glance","general/managing_apps","overview/appflow","general/views","helpers/string_helper","tutorial/static_pages","libraries/language","overview/getting_started","general/security","libraries/security","contributing/index","helpers/array_helper","libraries/unit_testing","helpers/download_helper","helpers/captcha_helper","database/connecting","helpers/text_helper","libraries/ftp","database/query_builder","libraries/uri","general/alternative_php","helpers/number_helper","installation/upgrade_170","installation/upgrade_171","installation/upgrade_172"],titles:["Controllers","XML Helper","Custom Function Calls","Upgrading From Beta 1.0 to Beta 1.1","Upgrading From a Previous Version","CodeIgniter URLs","HTML Helper","Config Class","Conclusion","Creating Libraries","Developer’s Certificate of Origin 1.1","Directory Helper","Transactions","Smiley Helper","Handling Multiple Environments","Upgrading from 1.6.2 to 1.6.3","Upgrading from 1.6.1 to 1.6.2","Upgrading from 1.6.0 to 1.6.1","Web Page Caching","Calendaring Class","Typography Class","News section","Create news items","Email Class","General Topics","Compatibility Functions","CodeIgniter Overview","Helper Functions","Using CodeIgniter Drivers","Change Log","Upgrading from 2.2.x to 3.0.0","Database Caching Class","Upgrading from 1.5.0 to 1.5.2","Upgrading from 1.5.2 to 1.5.3","Upgrading from 1.4.1 to 1.5.0","Upgrading from 1.5.3 to 1.5.4","Inflector Helper","Benchmarking Class","Downloading CodeIgniter","Javascript Class","Auto-loading Resources","Error Handling","Typography Helper","Database Metadata","Queries","Running via the CLI","Form Validation","CodeIgniter User Guide","Design and Architectural Goals","Image Manipulation Class","Installation Instructions","Generating Query Results","Upgrading from 1.4.0 to 1.4.1","Upgrading from 1.3.3 to 1.4.0","Upgrading from 2.1.4 to 2.2.0","Upgrading from 2.2.0 to 2.2.1","Pagination Class","Tutorial","Troubleshooting","Model-View-Controller","Caching Driver","Upgrading from 2.1.1 to 2.1.2","CodeIgniter Features","Security Helper","Server Requirements","Upgrading from 1.2 to 1.3","Upgrading from 1.3 to 1.3.1","Upgrading from 1.3.1 to 1.3.2","Upgrading from 1.3.2 to 1.3.3","Database Utility Class","Database Forge Class","The MIT License (MIT)","Models","Encryption Library","Writing CodeIgniter Documentation","URL Helper","Query Helper Methods","Profiling Your Application","Welcome to CodeIgniter","Language Helper","Creating Drivers","Migrations Class","DB Driver Reference","Helpers","Database Reference","Cookie Helper","Date Helper","Form Helper","User Agent Class","Database Configuration","Upgrading From Beta 1.0 to Final 1.2","XML-RPC and XML-RPC Server Classes","Output Class","URI Routing","Upgrading from 2.0.1 to 2.0.2","Upgrading from 2.0.2 to 2.0.3","Upgrading from 1.7.2 to 2.0.0","Upgrading from 2.0.0 to 2.0.1","Session Library","Using CodeIgniter Libraries","Common Functions","Input Class","Path Helper","Loader Class","Encrypt Class","Creating Core System Classes","Database Quick Start: Example Code","Zip Encoding Class","Reserved Names","File Helper","Template Parser Class","Libraries","Upgrading from 2.1.3 to 2.1.4","Upgrading from 2.1.0 to 2.1.1","Upgrading from 2.0.3 to 2.1.0","Upgrading from 2.1.2 to 2.1.3","Trackback Class","Creating Ancillary Classes","Upgrading from 1.5.4 to 1.6.0","HTML Table Class","PHP Style Guide","Email Helper","Credits","File Uploading Class","Hooks - Extending the Framework Core","Shopping Cart Class","CodeIgniter at a Glance","Managing your Applications","Application Flow Chart","Views","String Helper","Static pages","Language Class","Getting Started With CodeIgniter","Security","Security Class","Contributing to CodeIgniter","Array Helper","Unit Testing Class","Download Helper","CAPTCHA Helper","Connecting to your Database","Text Helper","FTP Class","Query Builder Class","URI Class","Alternate PHP Syntax for View Files","Number Helper","Upgrading from 1.6.3 to 1.7.0","Upgrading from 1.7.0 to 1.7.1","Upgrading from 1.7.1 to 1.7.2"],objects:{"":{"CI_DB_driver::platform":[82,0,1,""],"CI_DB_forge::add_field":[70,0,1,""],mysql_to_unix:[86,1,1,""],"CI_DB_query_builder::or_where_in":[144,0,1,""],"CI_Input::get_request_header":[101,0,1,""],"CI_Calendar::get_total_days":[19,0,1,""],"CI_URI::segment":[145,0,1,""],"CI_FTP::delete_dir":[143,0,1,""],auto_link:[75,1,1,""],form_textarea:[87,1,1,""],"CI_Session::keep_flashdata":[98,0,1,""],"CI_DB_utility::repair_table":[69,0,1,""],"CI_DB_driver::update_string":[82,0,1,""],get_file_info:[109,1,1,""],base_url:[75,1,1,""],site_url:[75,1,1,""],"CI_DB_forge::add_column":[70,0,1,""],"CI_Output::set_output":[92,0,1,""],CI_Security:[135,2,1,""],"CI_DB_result::last_row":[51,0,1,""],"CI_Cart::destroy":[125,0,1,""],"CI_DB_query_builder::not_like":[144,0,1,""],"CI_DB_driver::cache_delete_all":[82,0,1,""],"CI_Encrypt::encode":[104,0,1,""],date_range:[86,1,1,""],underscore:[36,1,1,""],"CI_DB_query_builder::get_compiled_delete":[144,0,1,""],"CI_DB_driver::simple_query":[82,0,1,""],force_download:[139,1,1,""],"CI_Calendar::get_day_names":[19,0,1,""],"CI_Cache::is_supported":[60,0,1,""],byte_format:[147,1,1,""],"CI_Migration::latest":[81,0,1,""],"CI_DB_driver::trans_complete":[82,0,1,""],"CI_DB_driver::reconnect":[82,0,1,""],"CI_DB_utility::database_exists":[69,0,1,""],heading:[6,1,1,""],"CI_FTP::mirror":[143,0,1,""],CI_DB_query_builder:[144,2,1,""],CI_Loader:[103,2,1,""],nbs:[6,1,1,""],doctype:[6,1,1,""],word_limiter:[142,1,1,""],write_file:[109,1,1,""],quotes_to_entities:[130,1,1,""],"CI_DB_driver::db_select":[82,0,1,""],"CI_Unit_test::report":[138,0,1,""],sanitize_filename:[63,1,1,""],"CI_Image_lib::rotate":[49,0,1,""],standard_date:[86,1,1,""],mdate:[86,1,1,""],"CI_Calendar::get_month_name":[19,0,1,""],"CI_DB_query_builder::limit":[144,0,1,""],"CI_Input::server":[101,0,1,""],"CI_Output::_display":[92,0,1,""],"CI_DB_query_builder::where":[144,0,1,""],xss_clean:[63,1,1,""],"CI_Input::get_post":[101,0,1,""],"CI_DB_forge::drop_database":[70,0,1,""],"CI_Form_validation::error_string":[46,0,1,""],"CI_DB_driver::trans_strict":[82,0,1,""],"CI_Trackback::send":[116,0,1,""],camelize:[36,1,1,""],form_button:[87,1,1,""],"CI_User_agent::version":[88,0,1,""],"CI_URI::uri_string":[145,0,1,""],directory_map:[11,1,1,""],strip_image_tags:[63,1,1,""],"CI_Upload::do_upload":[123,0,1,""],gmt_to_local:[86,1,1,""],"CI_DB_query_builder::get":[144,0,1,""],"CI_DB_driver::list_tables":[82,0,1,""],current_url:[75,1,1,""],"CI_Lang::line":[132,0,1,""],mb_substr:[25,1,1,""],"CI_Input::input_stream":[101,0,1,""],"CI_Cart::contents":[125,0,1,""],"CI_Xmlrpc::send_error_message":[91,0,1,""],"CI_DB_result::first_row":[51,0,1,""],"CI_DB_query_builder::or_where":[144,0,1,""],"CI_DB_query_builder::having":[144,0,1,""],"CI_Config::slash_item":[7,0,1,""],"CI_Table::clear":[119,0,1,""],"CI_DB_driver::trans_start":[82,0,1,""],"CI_Cart::remove":[125,0,1,""],"CI_Upload::data":[123,0,1,""],CI_Benchmark:[37,2,1,""],"CI_Output::cache":[92,0,1,""],"CI_Zip::get_zip":[107,0,1,""],CI_DB_driver:[82,2,1,""],Some_class:[74,2,1,""],form_reset:[87,1,1,""],"CI_DB_query_builder::select_min":[144,0,1,""],"CI_FTP::rename":[143,0,1,""],"CI_Trackback::receive":[116,0,1,""],"CI_Loader::helper":[103,0,1,""],form_fieldset_close:[87,1,1,""],"CI_DB_result::free_result":[51,0,1,""],"CI_DB_utility::backup":[69,0,1,""],"CI_DB_result::unbuffered_row":[51,0,1,""],"CI_Trackback::convert_ascii":[116,0,1,""],"CI_Security::xss_clean":[135,0,1,""],set_select:[87,1,1,""],form_prep:[87,1,1,""],form_open:[87,1,1,""],"CI_URI::slash_segment":[145,0,1,""],"Some_class::should_do_something":[74,0,1,""],"CI_FTP::connect":[143,0,1,""],"CI_Loader::view":[103,0,1,""],"CI_Image_lib::display_errors":[49,0,1,""],"CI_DB_driver::trans_status":[82,0,1,""],"CI_Encryption::encrypt":[73,0,1,""],"CI_DB_query_builder::or_not_group_start":[144,0,1,""],"CI_Migration::version":[81,0,1,""],CI_DB_result:[51,2,1,""],"CI_DB_query_builder::replace":[144,0,1,""],"CI_DB_driver::cache_delete":[82,0,1,""],"CI_Trackback::extract_urls":[116,0,1,""],"CI_Form_validation::set_message":[46,0,1,""],array_column:[25,1,1,""],url_title:[75,1,1,""],get_instance:[117,1,1,""],CI_Lang:[132,2,1,""],trim_slashes:[130,1,1,""],xml_convert:[1,1,1,""],"CI_DB_query_builder::or_having":[144,0,1,""],"CI_DB_query_builder::from":[144,0,1,""],show_error:[41,1,1,""],"CI_DB_query_builder::offset":[144,0,1,""],singular:[36,1,1,""],"CI_DB_result::field_data":[51,0,1,""],show_404:[41,1,1,""],array_replace_recursive:[25,1,1,""],random_element:[137,1,1,""],"CI_Security::sanitize_filename":[135,0,1,""],form_checkbox:[87,1,1,""],"CI_Trackback::validate_url":[116,0,1,""],"CI_User_agent::is_robot":[88,0,1,""],"CI_Email::message":[23,0,1,""],"CI_FTP::close":[143,0,1,""],create_captcha:[140,1,1,""],"CI_Config::item":[7,0,1,""],"CI_DB_driver::db_pconnect":[82,0,1,""],"CI_Input::user_agent":[101,0,1,""],element:[137,1,1,""],"CI_Encryption::create_key":[73,0,1,""],days_in_month:[86,1,1,""],"CI_Session::unset_userdata":[98,0,1,""],"CI_Encrypt::set_mode":[104,0,1,""],"CI_DB_utility::csv_from_result":[69,0,1,""],"CI_Cache::decrement":[60,0,1,""],"CI_DB_query_builder::get_compiled_update":[144,0,1,""],"CI_Form_validation::error":[46,0,1,""],form_submit:[87,1,1,""],"CI_DB_driver::count_all":[82,0,1,""],"CI_DB_result::num_rows":[51,0,1,""],"CI_DB_driver::field_exists":[82,0,1,""],"CI_Trackback::limit_characters":[116,0,1,""],CI_Output:[92,2,1,""],password_hash:[25,1,1,""],CI_Encrypt:[104,2,1,""],"CI_Table::set_caption":[119,0,1,""],CI_Image_lib:[49,2,1,""],config_item:[100,1,1,""],"CI_Migration::find_migrations":[81,0,1,""],get_clickable_smileys:[13,1,1,""],form_password:[87,1,1,""],"CI_DB_query_builder::truncate":[144,0,1,""],"CI_Email::from":[23,0,1,""],"CI_User_agent::charsets":[88,0,1,""],ellipsize:[142,1,1,""],CI_Config:[7,2,1,""],"CI_Typography::nl2br_except_pre":[20,0,1,""],"CI_Zip::clear_data":[107,0,1,""],timezone_menu:[86,1,1,""],now:[86,1,1,""],"CI_DB_query_builder::count_all_results":[144,0,1,""],set_value:[87,1,1,""],strip_slashes:[130,1,1,""],"CI_DB_query_builder::or_where_not_in":[144,0,1,""],"CI_User_agent::accept_lang":[88,0,1,""],"CI_DB_query_builder::where_not_in":[144,0,1,""],highlight_phrase:[142,1,1,""],CI_Encryption:[73,2,1,""],"CI_Input::ip_address":[101,0,1,""],smiley_js:[13,1,1,""],"CI_URI::slash_rsegment":[145,0,1,""],"CI_DB_driver::db_set_charset":[82,0,1,""],"CI_Encrypt::set_cipher":[104,0,1,""],"CI_DB_driver::version":[82,0,1,""],"CI_Xmlrpc::timeout":[91,0,1,""],is_really_writable:[100,1,1,""],"CI_DB_driver::elapsed_time":[82,0,1,""],set_realpath:[102,1,1,""],"CI_Benchmark::elapsed_time":[37,0,1,""],nice_date:[86,1,1,""],"CI_DB_query_builder::update":[144,0,1,""],"CI_URI::segment_array":[145,0,1,""],CI_Cache:[60,2,1,""],"CI_DB_query_builder::reset_query":[144,0,1,""],"CI_Session::umark_flash":[98,0,1,""],"CI_DB_query_builder::not_group_start":[144,0,1,""],plural:[36,1,1,""],remove_invisible_characters:[100,1,1,""],"CI_Calendar::adjust_date":[19,0,1,""],"CI_DB_driver::call_function":[82,0,1,""],hash_equals:[25,1,1,""],CI_Pagination:[56,2,1,""],is_countable:[36,1,1,""],"CI_DB_result::list_fields":[51,0,1,""],"CI_Input::post_get":[101,0,1,""],"CI_Security::get_csrf_hash":[135,0,1,""],"CI_Table::set_template":[119,0,1,""],"CI_Image_lib::resize":[49,0,1,""],"CI_Config::load":[7,0,1,""],"CI_DB_driver::table_exists":[82,0,1,""],link_tag:[6,1,1,""],"CI_User_agent::mobile":[88,0,1,""],"CI_DB_query_builder::start_cache":[144,0,1,""],"CI_Email::bcc":[23,0,1,""],"CI_DB_driver::list_fields":[82,0,1,""],"CI_Encrypt::encode_from_legacy":[104,0,1,""],"CI_DB_driver::db_connect":[82,0,1,""],"CI_DB_query_builder::insert":[144,0,1,""],increment_string:[130,1,1,""],"CI_Email::reply_to":[23,0,1,""],"CI_Cache::cache_info":[60,0,1,""],"CI_DB_query_builder::select":[144,0,1,""],"CI_DB_query_builder::flush_cache":[144,0,1,""],"CI_Cart::product_options":[125,0,1,""],"CI_Loader::database":[103,0,1,""],"CI_Benchmark::memory_usage":[37,0,1,""],prep_url:[75,1,1,""],"CI_URI::uri_to_assoc":[145,0,1,""],encode_php_tags:[63,1,1,""],"CI_DB_query_builder::empty_table":[144,0,1,""],"CI_DB_query_builder::get_where":[144,0,1,""],"CI_Calendar::initialize":[19,0,1,""],"CI_DB_query_builder::group_end":[144,0,1,""],"CI_Parser::set_delimiters":[110,0,1,""],"CI_DB_query_builder::select_sum":[144,0,1,""],"CI_DB_forge::add_key":[70,0,1,""],"CI_Config::site_url":[7,0,1,""],"CI_Form_validation::has_rule":[46,0,1,""],"CI_URI::total_segments":[145,0,1,""],"CI_Email::attach":[23,0,1,""],"CI_Session::__set":[98,0,1,""],"CI_DB_forge::drop_column":[70,0,1,""],"CI_DB_utility::list_databases":[69,0,1,""],reduce_double_slashes:[130,1,1,""],"CI_Loader::dbforge":[103,0,1,""],"CI_Table::add_row":[119,0,1,""],"CI_Upload::initialize":[123,0,1,""],valid_email:[121,1,1,""],"CI_DB_result::next_row":[51,0,1,""],CI_Unit_test:[138,2,1,""],"CI_Cache::increment":[60,0,1,""],"CI_Session::sess_regenerate":[98,0,1,""],index_page:[75,1,1,""],delete_files:[109,1,1,""],is_php:[100,1,1,""],"CI_Email::set_alt_message":[23,0,1,""],"CI_Output::append_output":[92,0,1,""],"CI_Encryption::decrypt":[73,0,1,""],"CI_Table::set_heading":[119,0,1,""],humanize:[36,1,1,""],"CI_Session::__get":[98,0,1,""],anchor_popup:[75,1,1,""],"CI_DB_query_builder::get_compiled_select":[144,0,1,""],"CI_DB_result::data_seek":[51,0,1,""],"CI_Session::sess_destroy":[98,0,1,""],"CI_Trackback::data":[116,0,1,""],"CI_DB_query_builder::where_in":[144,0,1,""],"CI_Session::flashdata":[98,0,1,""],"CI_DB_driver::cache_off":[82,0,1,""],"CI_Config::system_url":[7,0,1,""],"CI_Loader::model":[103,0,1,""],"CI_Unit_test::active":[138,0,1,""],"CI_Session::has_userdata":[98,0,1,""],"CI_Cache::save":[60,0,1,""],"CI_Xmlrpc::server":[91,0,1,""],"CI_DB_query_builder::set_update_batch":[144,0,1,""],"CI_Session::userdata":[98,0,1,""],CI_Email:[23,2,1,""],"CI_Session::umark_temp":[98,0,1,""],set_status_header:[100,1,1,""],convert_accented_characters:[142,1,1,""],CI_Cart:[125,2,1,""],alternator:[130,1,1,""],"CI_Session::set_tempdata":[98,0,1,""],"CI_Unit_test::run":[138,0,1,""],"CI_Migration::current":[81,0,1,""],"CI_Loader::config":[103,0,1,""],"CI_Output::set_status_header":[92,0,1,""],CI_Zip:[107,2,1,""],"CI_Loader::driver":[103,0,1,""],nl2br_except_pre:[42,1,1,""],random_string:[130,1,1,""],"CI_Cart::total_items":[125,0,1,""],CI_FTP:[143,2,1,""],"CI_Unit_test::set_test_items":[138,0,1,""],"CI_Cart::total":[125,0,1,""],redirect:[75,1,1,""],strip_quotes:[130,1,1,""],"CI_Email::print_debugger":[23,0,1,""],"CI_User_agent::is_mobile":[88,0,1,""],mb_strpos:[25,1,1,""],"CI_Security::get_random_bytes":[135,0,1,""],CI_Parser:[110,2,1,""],"CI_DB_result::set_row":[51,0,1,""],"CI_DB_query_builder::stop_cache":[144,0,1,""],"CI_DB_driver::last_query":[82,0,1,""],ascii_to_entities:[142,1,1,""],CI_DB_forge:[70,2,1,""],"CI_Xmlrpc::display_error":[91,0,1,""],"CI_User_agent::agent_string":[88,0,1,""],octal_permissions:[109,1,1,""],form_error:[87,1,1,""],"CI_DB_query_builder::update_batch":[144,0,1,""],"CI_Calendar::parse_template":[19,0,1,""],form_multiselect:[87,1,1,""],"CI_FTP::delete_file":[143,0,1,""],"CI_DB_result::result_object":[51,0,1,""],highlight_code:[142,1,1,""],"CI_Email::cc":[23,0,1,""],"CI_Cart::has_options":[125,0,1,""],"CI_Session::set_flashdata":[98,0,1,""],"CI_Input::post":[101,0,1,""],local_to_gmt:[86,1,1,""],"CI_Image_lib::watermark":[49,0,1,""],"CI_Session::get_flash_keys":[98,0,1,""],"CI_Form_validation::error_array":[46,0,1,""],"CI_Xmlrpc::display_response":[91,0,1,""],timezones:[86,1,1,""],"CI_User_agent::is_referral":[88,0,1,""],password_get_info:[25,1,1,""],"CI_DB_driver::primary":[82,0,1,""],send_email:[121,1,1,""],"CI_DB_driver::close":[82,0,1,""],"CI_Form_validation::reset_validation":[46,0,1,""],validation_errors:[87,1,1,""],"CI_Table::make_columns":[119,0,1,""],"CI_Loader::get_vars":[103,0,1,""],"CI_DB_query_builder::delete":[144,0,1,""],form_close:[87,1,1,""],"CI_DB_driver::initialize":[82,0,1,""],"CI_URI::ruri_string":[145,0,1,""],"CI_Xmlrpc::send_request":[91,0,1,""],"CI_Loader::add_package_path":[103,0,1,""],"CI_DB_query_builder::set_insert_batch":[144,0,1,""],"CI_Session::mark_as_temp":[98,0,1,""],"CI_Calendar::default_template":[19,0,1,""],"CI_Xmlrpc::request":[91,0,1,""],"CI_Form_validation::set_rules":[46,0,1,""],"CI_URI::total_rsegments":[145,0,1,""],"CI_Encryption::hkdf":[73,0,1,""],"CI_Output::enable_profiler":[92,0,1,""],"CI_Cache::delete":[60,0,1,""],"CI_DB_query_builder::or_like":[144,0,1,""],"CI_DB_result::row":[51,0,1,""],"CI_Cart::get_item":[125,0,1,""],"CI_Config::base_url":[7,0,1,""],"CI_Encryption::initialize":[73,0,1,""],img:[6,1,1,""],CI_Trackback:[116,2,1,""],"CI_User_agent::browser":[88,0,1,""],CI_Session:[98,2,1,""],"CI_DB_result::custom_result_object":[51,0,1,""],set_radio:[87,1,1,""],"CI_Security::get_csrf_token_name":[135,0,1,""],"CI_DB_forge::create_table":[70,0,1,""],"CI_DB_utility::optimize_database":[69,0,1,""],"CI_Cart::update":[125,0,1,""],"CI_Lang::load":[132,0,1,""],"CI_Loader::vars":[103,0,1,""],"CI_DB_forge::drop_table":[70,0,1,""],"CI_Input::set_cookie":[101,0,1,""],"CI_Table::set_empty":[119,0,1,""],"CI_Migration::error_string":[81,0,1,""],mailto:[75,1,1,""],hash_pbkdf2:[25,1,1,""],CI_Form_validation:[46,2,1,""],"CI_DB_query_builder::set_dbprefix":[144,0,1,""],reduce_multiples:[130,1,1,""],"CI_Form_validation::set_error_delimiters":[46,0,1,""],"CI_Email::subject":[23,0,1,""],"CI_FTP::upload":[143,0,1,""],"CI_Output::set_profiler_sections":[92,0,1,""],"CI_Zip::add_dir":[107,0,1,""],get_filenames:[109,1,1,""],"CI_Typography::format_characters":[20,0,1,""],unix_to_human:[86,1,1,""],array_replace:[25,1,1,""],"CI_DB_query_builder::like":[144,0,1,""],"CI_Session::set_userdata":[98,0,1,""],"CI_DB_query_builder::distinct":[144,0,1,""],"CI_Unit_test::use_strict":[138,0,1,""],CI_Upload:[123,2,1,""],"CI_DB_driver::trans_off":[82,0,1,""],form_upload:[87,1,1,""],hex2bin:[25,1,1,""],CI_Calendar:[19,2,1,""],parse_smileys:[13,1,1,""],"CI_DB_query_builder::select_avg":[144,0,1,""],anchor:[75,1,1,""],uri_string:[75,1,1,""],"CI_Form_validation::run":[46,0,1,""],"CI_DB_driver::cache_on":[82,0,1,""],"CI_Output::get_output":[92,0,1,""],"CI_DB_driver::escape_str":[82,0,1,""],"CI_DB_query_builder::or_group_start":[144,0,1,""],human_to_unix:[86,1,1,""],"CI_Output::set_header":[92,0,1,""],"CI_Input::request_headers":[101,0,1,""],"CI_Loader::file":[103,0,1,""],word_censor:[142,1,1,""],"CI_DB_forge::modify_column":[70,0,1,""],CI_Xmlrpc:[91,2,1,""],form_fieldset:[87,1,1,""],"CI_Email::set_header":[23,0,1,""],"CI_Cart::insert":[125,0,1,""],"CI_Loader::remove_package_path":[103,0,1,""],"CI_Security::entity_decode":[135,0,1,""],"CI_Session::get_temp_keys":[98,0,1,""],"CI_DB_driver::escape":[82,0,1,""],"CI_FTP::move":[143,0,1,""],form_label:[87,1,1,""],"CI_DB_driver::protect_identifiers":[82,0,1,""],"CI_Cache::get":[60,0,1,""],"CI_DB_result::previous_row":[51,0,1,""],"CI_DB_query_builder::group_start":[144,0,1,""],"CI_Zip::download":[107,0,1,""],"CI_DB_driver::escape_identifiers":[82,0,1,""],"CI_Loader::get_var":[103,0,1,""],"CI_User_agent::parse":[88,0,1,""],"CI_Encrypt::decode":[104,0,1,""],"CI_Cache::clean":[60,0,1,""],html_escape:[100,1,1,""],symbolic_permissions:[109,1,1,""],form_hidden:[87,1,1,""],log_message:[41,1,1,""],"CI_DB_driver::cache_set_path":[82,0,1,""],"CI_Unit_test::set_template":[138,0,1,""],"CI_DB_driver::field_data":[82,0,1,""],"CI_URI::rsegment":[145,0,1,""],"CI_Loader::language":[103,0,1,""],get_dir_file_info:[109,1,1,""],set_checkbox:[87,1,1,""],"CI_Input::cookie":[101,0,1,""],"CI_Cache::get_metadata":[60,0,1,""],"CI_URI::assoc_to_uri":[145,0,1,""],"CI_Benchmark::mark":[37,0,1,""],"CI_FTP::changedir":[143,0,1,""],"CI_Parser::parse":[110,0,1,""],"CI_Output::get_content_type":[92,0,1,""],entity_decode:[42,1,1,""],"CI_FTP::chmod":[143,0,1,""],do_hash:[63,1,1,""],password_verify:[25,1,1,""],safe_mailto:[75,1,1,""],"Some_class::some_method":[74,0,1,""],"CI_Image_lib::clear":[49,0,1,""],character_limiter:[142,1,1,""],"CI_DB_result::result":[51,0,1,""],"CI_DB_query_builder::or_not_like":[144,0,1,""],"CI_FTP::download":[143,0,1,""],"CI_Zip::read_file":[107,0,1,""],"CI_Unit_test::result":[138,0,1,""],"CI_Zip::archive":[107,0,1,""],"CI_DB_driver::is_write_type":[82,0,1,""],"CI_Calendar::generate":[19,0,1,""],"CI_Form_validation::set_data":[46,0,1,""],read_file:[109,1,1,""],word_wrap:[142,1,1,""],"CI_DB_driver::compile_binds":[82,0,1,""],password_needs_rehash:[25,1,1,""],"CI_DB_result::row_object":[51,0,1,""],"CI_Xmlrpc::initialize":[91,0,1,""],"CI_Upload::display_errors":[123,0,1,""],auto_typography:[42,1,1,""],CI_Table:[119,2,1,""],"CI_Trackback::set_error":[116,0,1,""],"CI_Image_lib::initialize":[49,0,1,""],"CI_DB_forge::rename_table":[70,0,1,""],"CI_DB_result::custom_row_object":[51,0,1,""],CI_URI:[145,2,1,""],form_dropdown:[87,1,1,""],br:[6,1,1,""],"CI_DB_utility::optimize_table":[69,0,1,""],"CI_Input::valid_ip":[101,0,1,""],"CI_URI::ruri_to_assoc":[145,0,1,""],"CI_DB_utility::xml_from_result":[69,0,1,""],ol:[6,1,1,""],"CI_Output::set_content_type":[92,0,1,""],"CI_User_agent::referrer":[88,0,1,""],"CI_Input::is_ajax_request":[101,0,1,""],quoted_printable_encode:[25,1,1,""],"CI_DB_driver::insert_string":[82,0,1,""],"CI_DB_query_builder::set":[144,0,1,""],"CI_Email::attachment_cid":[23,0,1,""],"CI_DB_driver::display_error":[82,0,1,""],"CI_DB_query_builder::order_by":[144,0,1,""],"CI_Input::method":[101,0,1,""],"CI_Xmlrpc::method":[91,0,1,""],"CI_Input::is_cli_request":[101,0,1,""],"CI_DB_result::row_array":[51,0,1,""],CI_User_agent:[88,2,1,""],"CI_Session::all_userdata":[98,0,1,""],"CI_Session::tempdata":[98,0,1,""],"CI_DB_query_builder::insert_batch":[144,0,1,""],"CI_Trackback::convert_xml":[116,0,1,""],"CI_Pagination::initialize":[56,0,1,""],"CI_Zip::read_dir":[107,0,1,""],"CI_DB_driver::escape_like_str":[82,0,1,""],"CI_Zip::add_data":[107,0,1,""],"CI_Email::send":[23,0,1,""],"CI_Loader::is_loaded":[103,0,1,""],repeater:[130,1,1,""],is_cli:[100,1,1,""],"CI_DB_query_builder::select_max":[144,0,1,""],"CI_Output::get_header":[92,0,1,""],get_mime_by_extension:[109,1,1,""],"CI_Trackback::get_id":[116,0,1,""],mb_strlen:[25,1,1,""],"CI_User_agent::accept_charset":[88,0,1,""],"CI_DB_query_builder::get_compiled_insert":[144,0,1,""],"CI_Email::clear":[23,0,1,""],"CI_DB_query_builder::group_by":[144,0,1,""],"CI_FTP::mkdir":[143,0,1,""],is_https:[100,1,1,""],ul:[6,1,1,""],"CI_Input::get":[101,0,1,""],meta:[6,1,1,""],"CI_DB_forge::create_database":[70,0,1,""],"CI_User_agent::robot":[88,0,1,""],get_mimes:[100,1,1,""],"CI_Pagination::create_links":[56,0,1,""],"CI_URI::rsegment_array":[145,0,1,""],timespan:[86,1,1,""],"CI_Loader::dbutil":[103,0,1,""],"CI_DB_driver::total_queries":[82,0,1,""],"CI_DB_query_builder::dbprefix":[144,0,1,""],"CI_Email::to":[23,0,1,""],"CI_Trackback::display_errors":[116,0,1,""],"CI_DB_result::num_fields":[51,0,1,""],"CI_Loader::get_package_paths":[103,0,1,""],"CI_Table::generate":[119,0,1,""],"CI_Config::set_item":[7,0,1,""],"CI_User_agent::platform":[88,0,1,""],"CI_DB_result::result_array":[51,0,1,""],"CI_Loader::library":[103,0,1,""],elements:[137,1,1,""],"CI_User_agent::languages":[88,0,1,""],CI_Input:[101,2,1,""],CI_Typography:[20,2,1,""],"CI_Image_lib::crop":[49,0,1,""],function_usable:[100,1,1,""],lang:[79,1,1,""],"CI_Trackback::process":[116,0,1,""],"CI_Session::mark_as_flash":[98,0,1,""],"CI_Loader::clear_vars":[103,0,1,""],CI_DB_utility:[69,2,1,""],"CI_DB_query_builder::join":[144,0,1,""],CI_Migration:[81,2,1,""],form_radio:[87,1,1,""],"CI_FTP::list_files":[143,0,1,""],"CI_User_agent::is_browser":[88,0,1,""],"CI_Trackback::send_success":[116,0,1,""],"CI_Parser::parse_string":[110,0,1,""]}},titleterms:{all:[134,31],code:[120,106],chain:144,queri:[5,89,69,120,51,44,76,144,106],month:19,prefix:[9,27,44,105],row:[125,51],content:[0,70,72,120,45,46],privat:[120,0],specif:[46,73,144],depend:25,friendli:126,send:[23,91,116],form_prep:30,digit:56,string:[5,70,120,130,30,25],fals:[120,30],util:[9,69],verb:93,my_secur:94,word:23,fadeout:39,list:[43,69,105],upload:123,"try":[45,0,123,91,46],item:[39,30,22,52,7,125],adjust:96,quick:106,sign:136,design:48,cache_on:31,pass:[9,0,19,70],download:[38,139],slidetoggl:39,compat:[25,120,96,136],index:[65,5,34,3,95],what:[0,91,72,125,27,45,98],hide:[56,39,134],sub:[9,0,129],compar:120,section:[77,74,21],current:56,delet:[144,18],version:[9,106,4,29],xss_clean:30,method:[0,144,49,74,30,51,76,120,46],metadata:[43,98],hash:25,gener:[47,126,51,24,138],is_cli_request:30,punch:126,directory_map:30,let:[45,0],cart:[125,30],address:113,path:[39,102],modifi:70,encryption_kei:73,valu:[87,120,89],convert:96,memcach:[98,60],bbedit:120,credit:122,chang:[119,46,30,95,29],portabl:73,overrid:[23,30],via:45,display_error:134,prefer:[56,23,19,49,123,81,98,69],deprec:30,instal:[47,50,127],redi:[98,60],total:37,select:144,from:[3,90,33,94,95,96,97,52,53,54,55,17,118,115,4,65,66,67,68,70,15,112,30,16,32,76,34,113,114,35,61,148,149,150],zip:107,memori:37,internation:132,upgrad:[3,90,112,94,95,96,97,52,53,54,55,17,118,115,4,65,66,67,68,15,30,16,32,33,34,113,114,35,61,148,149,150],next:[56,19],call:[0,2,94,96,124,46],type:[49,30,91],prep:46,toggl:39,form_valid:30,claus:30,benchmark:[37,77],agent:88,xss:[134,30,135,101],cach:[60,144,31,18],retriev:[43,98,69],setup:39,work:[143,73,31,44,7,98,18],uniqu:30,fetch:[132,7],aliv:141,control:[108,0,131,59,13,146,123,97,46],sqlite:30,stream:101,process:[49,0,123,91,116],time_to_upd:118,wincach:60,"404_overrid":30,templat:[138,19,110,30,126,150],topic:[47,24],captcha:140,tag:[120,146],system_url:30,read_fil:30,multipl:[132,27,129,30,14,124,125,106,141,127],goal:48,secur:[63,30,94,134,135,101],charset:35,ping:116,write:74,how:[46,73,31,98,18],url_titl:30,instead:30,csv:69,config:[56,39,23,3,49,113,30,96,7,95,34,97,52,53,35,46,118,65,123,114],updat:[125,33,94,95,96,97,52,53,54,55,17,118,115,65,66,67,68,144,15,30,16,32,112,34,113,114,35,61,148,149,150],remap:0,cache_delete_al:31,resourc:[9,40],after:30,global_xss_filt:30,random_str:30,date:[30,86],underscor:30,associ:[46,91],trim_slash:30,"short":[120,146],practic:134,light:126,issu:[30,136],callback:[46,93],"switch":132,environ:[14,7],reloc:[3,127],callabl:46,order:144,origin:10,cache_delet:31,move:[94,96,30],autoload:[95,30,52,35,118],reconnect:141,system_path:150,digest:25,paramet:[9,73,91,141],style:[120,136],group:[46,144],cli:45,fix:29,clickabl:13,main:[95,34],easier:76,good:136,"return":[120,30,129],handl:[132,134,41,14,44],auto:[132,27,72,7,40],initi:[39,9,123,125,88,91,49,98,138,19,20,104,106,107,143,69,70,110,73,77,116,119],"break":120,framework:[126,124,14],now:[27,30],introduct:47,drop_tabl:30,name:[108,0,81,69,120,30,9,46],anyth:46,edit:3,troubleshoot:58,drop:70,authent:73,separ:30,mode:[138,73,12],debug:120,register_glob:134,reset:144,weight:126,replac:[3,30,95,97,113,114,105,9],individu:46,"static":131,connect:[141,72],event:39,variabl:[108,39,120,110],ftp:143,typecast:120,space:120,miss:30,profil:[37,77],rel:56,determin:[43,69],watermark:49,migrat:81,manipul:49,free:126,standard:[25,106],cooki:[85,101],base:60,mime:[97,30,113,16],dblib:30,anchor_class:30,indent:120,befor:134,keep:141,filter:[134,30,135,101],length:[73,104],pagin:[56,30],codeignit:[5,150,9,126,127,47,12,112,94,95,96,97,52,53,133,54,55,17,118,115,148,62,68,99,26,65,66,67,28,15,30,74,16,32,33,34,113,114,35,61,136,38,149,78],timezon:86,first:56,oper:120,suffix:5,fetch_directori:30,arrai:[137,46,106,51,91],number:147,cache_off:31,hook:124,instruct:[96,50],open:120,forgeri:135,convent:9,strict:[138,12],data:[19,129,73,144,134,96,91,98,46,101],licens:71,system:105,messag:[25,46,73,104],statement:120,"final":90,slidedown:39,tool:74,fetch_method:30,user_ag:[95,114],third_parti:95,apppath:95,enclos:56,than:46,remov:[5,30,94,95,96,98,150],structur:[80,146],jqueri:39,store:[96,31,129],bind:44,consumpt:37,typographi:[42,20],ani:[96,30],dash:30,packag:103,reserv:[108,0,93],"null":[120,30],engin:126,alias:13,ancillari:117,destroi:98,rout:[131,30,93,21,22],note:[56,91,110,116,96,98,69],exampl:[56,132,81,69,60,93,143,144,106,119,107,88],thoroughli:126,mit:71,singl:106,anatomi:[91,7,72],simplifi:44,who:78,chart:128,textmat:120,beta:[90,3,29],regular:[93,44],pair:110,segment:[0,5],why:45,fetch_class:30,avail:[79,1,121,85,86,87,11,63,130,13,6,137,139,102,140,141,142,109,42,75,147,36],renam:[52,70,127],url:[5,126,30,75,116],tempdata:98,request:[135,91],uri:[0,5,30,93,145,134],doe:[126,31,18],dummi:60,ext:[95,30],bracket:120,clean:126,pars:110,hmac:73,shop:125,show:[39,19,46],text:[49,120,30,132,142],concurr:98,syntax:[146,148],session:[95,30,148,98],corner:39,xml:[91,1,69],cell:19,transact:12,configur:[39,89,73,14],folder:[96,3],local:120,info:47,contribut:[47,136],get:[133,101],express:93,nativ:9,fadein:39,csrf:[134,135],"new":[21,22],report:[138,14,136],requir:[126,74,64],enabl:[5,12,138,31,77,124,18],organ:0,common:100,default_control:30,contain:30,where:96,view:[39,129,59,110,103,146],certif:10,set:[56,27,23,19,39,49,30,93,21,7,77,69,104,105,9,46,123,73],tablesort:39,mysql:30,highlight_phras:30,result:[69,106,51,144],respons:91,close:[120,141],calendar:[19,3,39],best:134,kei:[16,104,70],databas:[65,47,89,69,70,72,30,31,44,43,76,34,140,134,98,106,141,95,84,118],label:132,dynam:129,approach:12,email:[121,23,30],attribut:56,altern:[60,146],call_funct:2,extend:[9,27,124,105],all_userdata:30,javascript:[39,30],extens:[96,30,126],popul:46,protect:[134,44],last:56,delimit:46,plugin:[39,96],pdo:30,tutori:[46,57,13,47],logic:[120,131],improv:31,load:[79,132,1,121,7,9,85,86,87,11,63,129,130,13,94,96,6,40,137,139,142,102,140,27,72,109,42,75,147,36],point:[37,124,77],overview:[46,13,26],loader:103,header:150,rpc:91,guid:[120,123,47,96,52,53,15,16,17,118,35,65,66,67,68,32,33,34,114,115,61,148,149,150],github:38,basic:[47,44],magic_quotes_runtim:134,argument:120,present:43,look:[144,119],defin:[0,124],behavior:[73,14],error:[65,12,120,30,41,14,44,91,46,150],anchor:56,loop:129,pack:126,file:[132,5,80,81,3,120,7,123,9,46,146,112,49,14,94,95,96,97,52,53,98,54,55,17,118,56,115,60,103,68,134,65,66,67,23,69,109,15,30,31,16,32,33,34,113,114,35,61,148,149,150],helper:[79,1,121,83,85,86,87,46,47,11,63,130,13,51,96,6,137,139,142,102,140,27,109,30,42,75,76,147,36],slideup:39,tabl:[69,70,120,43,95,113,116,148,119],site:[135,31],inform:76,parent:96,inflector:36,develop:10,welcom:[47,78],get_post:30,perform:31,make:76,cross:135,same:124,fragment:110,html:[6,30,119],document:[74,126,69,136],http:93,optim:69,driver:[80,28,82,60,30,73,98],effect:[39,14],user:[126,88,47,96,52,53,15,16,17,118,35,65,66,67,68,32,33,34,114,115,61,148,149,150],mani:30,php:[65,5,136,114,120,60,30,146,95,34,97,52,53,35,113,118,101],sha1:30,builder:[89,144,106],object:106,anim:39,client:91,command:45,thi:[79,1,2,121,31,85,86,87,11,63,130,13,6,137,139,102,140,142,109,42,75,147,36],model:[68,72,59,21,22,118],explan:[46,89,91],comment:120,identifi:44,execut:[76,37],tip:[98,136],"_post":46,toggleclass:39,languag:[79,132,30,3,35],previous:30,web:18,get_dir_file_info:96,add:[3,35,118],valid:[46,30,148,134],guidelin:136,input:[134,30,101],save:46,applic:[128,96,103,77,126,127],format:[120,91],world:[45,0],password:[25,134],insert:[134,106,144],do_hash:30,success:[46,123],whitespac:120,manual:[12,44,7,141],server:[101,91,64],necessari:96,cascad:46,output:[0,92],manag:[12,31,127],subhead:74,parenthet:120,"export":69,bonu:98,apc:60,librari:[47,23,39,30,73,94,138,104,111,9,98,99],confirm:150,definit:88,per:120,unit:138,overlai:49,refer:[132,82,7,84,123,86,125,46,88,47,91,49,92,51,143,95,98,135,101,56,138,19,20,60,103,81,104,25,144,107,23,69,70,110,73,31,145,116,37,119],core:[96,30,124,105],previou:[56,19,4],run:[45,138,12,127],usag:[81,69,110,60,30,143,107],step:[3,33,94,95,96,97,52,53,54,55,17,118,115,65,66,67,68,15,30,16,32,112,34,113,114,35,61,148,149,150],post:[97,101],mssql:30,about:[76,98],column:70,commun:126,page:[56,0,72,131,74,123,18,45,46],cipher:73,modal:39,constructor:[0,96],backup:69,disabl:[56,138,77],repair:69,own:[27,28,91,93,105,9,46,99],within:[9,129],encod:107,automat:[146,141],two:49,wrap:23,storag:9,your:[0,73,3,39,43,9,46,127,91,76,93,77,94,95,96,97,52,53,134,15,16,17,118,19,115,66,61,21,68,99,104,105,141,65,27,67,28,69,72,54,112,30,31,55,32,33,34,113,114,35,116,37,148,149,150,119],log:[30,29],support:[146,73,136],fast:126,custom:[56,98,138,2,73],standard_d:30,start:[106,133],flashdata:98,add_column:30,"function":[79,1,2,120,121,31,85,86,87,11,63,130,13,6,100,137,139,142,102,140,25,108,27,109,30,42,75,147,36],head:74,form:[132,30,22,123,97,87,46,101],forg:[30,70],link:[56,19],translat:46,line:[45,120,30,132],"true":120,bug:29,conclus:8,count:144,"default":[120,0,73,14,97],bugfix:29,access:[98,101],displai:[125,138,37,19,21],limit:144,sampl:132,similar:144,featur:62,constant:[108,120,30,14,95,25,16],creat:[132,138,80,28,19,70,129,105,22,123,81,91,116,9,46,117,99],get_inst:117,multibyt:25,flow:128,parser:110,decrypt:73,exist:[43,69],glanc:126,check:[97,30],echo:146,encrypt:[96,30,16,104,73],when:9,field:[43,46,13,70,87],other:46,branch:136,test:[138,106,12],imag:49,architectur:48,repeat:30,wildcard:93,"class":[132,0,73,39,120,7,125,123,117,9,46,88,91,49,92,51,143,96,98,135,101,56,138,19,20,60,103,81,104,105,144,106,107,23,69,70,110,30,31,145,77,116,37,119],sql:120,trackback:116,smilei:[13,30],markup:56,receiv:116,algorithm:73,directori:[0,11,3,129,30,80,123,127],descript:69,rule:[46,30,93],potenti:30,time:37,escap:[87,134,44],hello:[45,0]}}) |
ajax/libs/forerunnerdb/1.3.677/fdb-core.min.js | pvnr0082t/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":25,"./Shared":28}],3:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c(),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b(),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d(),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({
lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":28}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":28}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":23,"./Shared":28}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){
return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":24,"./Serialiser":27}],16:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],17:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":24}],18:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":24}],22:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":25,"./Shared":28}],24:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":28}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":28}],27:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.677",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]); |